Select all rows from table having two given values anywhere in rows - sql

I have a table of bus route. this table has fields like bus no. , route code , starting point , end point, and upto 10 halts from halt1 , halt2...halt10 . i have filled data in this table. now i want to select all rows having two values,for example jaipur and vasai. in my table, there are two rows that have jaipur and vasai. In one row, jaipur is in column halt2 and vasai in halt9. Similarly another row has jaipur in halt4 column and vasai in halt10 column.
please help me to find out sql query. I am using MS SQL server.
scrip
USE [JaipuBus]
GO
/****** Object: Table [dbo].[MyRoutes] Script Date: 02/24/2014 13:28:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MyRoutes](
[id] [int] IDENTITY(1,1) NOT NULL,
[Route_No] [nvarchar](50) NULL,
[Route_Code] [nvarchar](50) NULL,
[Color] [nvarchar](50) NULL,
[Start_Point] [nvarchar](200) NULL,
[End_Point] [nvarchar](200) NULL,
[halt1] [nvarchar](50) NULL,
[halt2] [nvarchar](50) NULL,
[halt3] [nvarchar](50) NULL,
[halt4] [nvarchar](50) NULL,
[halt5] [nvarchar](50) NULL,
[halt6] [nvarchar](50) NULL,
[halt7] [nvarchar](50) NULL,
[halt8] [nvarchar](50) NULL,
[halt9] [nvarchar](50) NULL,
[halt10] [nvarchar](50) NULL,
CONSTRAINT [PK_MyRoutes] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

use CONTAINS
SELECT *
WHERE CONTAINS((startingpoint,endpoint,halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10), 'jaipur')
AND CONTAINS((startingpoint,endpoint,halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10), 'vasai');

SELECT * FROM bus_rout WHERE (halt1='aaa' OR halt2='aaa' OR .... halt10='aaa') AND (halt1='bbb' OR halt2='bbb' OR ....... halt10='bbb')
The where clause could be generated by code.

Based on your input, it seems to be a necessity for you to have Normalized table structure.
CREATE TABLE [dbo].[MyRoutes](
[id] [int] IDENTITY(1,1) NOT NULL,
[Route_No] [nvarchar](50) NULL,
[Route_Code] [nvarchar](50) NULL,
[Color] [nvarchar](50) NULL,
[Start_Point] [nvarchar](200) NULL,
[End_Point] [nvarchar](200) NULL,
[HaltNum] INT,
[Halt] [nvarchar](50) NULL
)
Then a query to solve the routes problem can be written as below:
SELECT a.Route_No, a.Route_Code, a.Color, a.Start_Point, a.End_Point,
a.HaltNum StartNum, b.HaltNum StopNum
FROM MyRoutes a
INNER JOIN MyRoutes b
ON a.id = b.id
WHERE a.Halt = 'jaipur' AND b.Halt = 'vasai'
AND a.HaltNum < b.HaltNum
Even better design of the table structure would be to have a separate master table for all Stops where you can maintain only StopId and StopName. In the MyRoutes table then you can have HaltId as foreign key referencing StopId column of the all stops master table. The above query would then need to inner join with this table twice to have conditions on StopName

Related

I need help in an sql query

I have a table where the attendance of the employees is recorded. We only insert the present days. I want to show all dates of the month along with recorded attendance days. where not recorded days will show absent. Need Help.
Here is the Table Employee Attendance. Please Note that We only insert Present days into this table. Absent and Holidays are not inserted into this table.
`CREATE TABLE [dbo].[EmployeeAttendance](
[CompanyCode] [int] NOT NULL,
[BranchCode] [int] NOT NULL,
[TransactionDate] [datetime] NOT NULL,
[EmployeeCode] [int] NOT NULL,
[AttendanceCount] [int] NOT NULL,
[ShiftCode] [int] NOT NULL,
[ScheduledTimeIn] [datetime] NULL,
[ScheduledTimeOut] [datetime] NULL,
[BreakStartTime] [datetime] NULL,
[BreakEndTime] [datetime] NULL,
[FlexiLateTime] [int] NULL,
[FlexiEarlyTime] [int] NULL,
[RecordedTimeIn] [datetime] NULL,
[RecordedTimeOut] [datetime] NULL,
[RemarksIn] [varchar](500) NULL,
[RemarksOut] [varchar](500) NULL,
[AddByUserId] [int] NULL,
[AddDateTimeIn] [datetime] NULL,
[AddDateTimeOut] [datetime] NULL,
CONSTRAINT [PK_EmployeeAttendance_1] PRIMARY KEY CLUSTERED
(
[CompanyCode] ASC,
[BranchCode] ASC,
[TransactionDate] ASC,
[EmployeeCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]`
First: You need to create a "table" that has all the days of the month in it. Then you left join your recorded attendance data to that range of dates.
SELECT d.date, a.*
FROM [dates] AS d -- this is a set of rows, one per needed date
LEFT JOIN EmployeeAttendance AS a ON d.[date] = a.[RecordedTimeIn]
Now, depending on the database being used, you can generate the needed date rows in a variety of ways (eg a recursive common table expression).
Regardless of method you need one row per date is your first step and this will be the "from" table.

Recursive query to speed up system

My application reads a table with parent child relation. The application queries every level of the tree on his own and it really slow (must do multiple levels deep). I has searching for another solution and came to the recursive queries. With the examples that I have found I cannot map it to my data structure.
My structure looks like:
CREATE TABLE [products].[BillOfMaterial](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[parentNumber] [nvarchar](50) NOT NULL,
[warehouse] [nvarchar](50) NOT NULL,
[sequenceNumber] [int] NOT NULL,
[childNumber] [nvarchar](50) NOT NULL,
[childDescription] [nvarchar](50) NULL,
[qtyRequired] [numeric](18, 3) NOT NULL,
[childItemClass] [nvarchar](50) NULL,
[childItemType] [nvarchar](50) NULL,
[scrapFactor] [numeric](18, 3) NULL,
[bubbleNumber] [int] NOT NULL,
[operationNumber] [int] NOT NULL,
[effectivityDate] [date] NULL,
[discontinuityDate] [date] NULL,
[companyID] [bigint] NOT NULL,
CONSTRAINT [PK_BillOfMaterial] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Some example data:
When I query for parentNumber 1 it should give me all those rows:
And for parentNumber 3 the output must be:
Now I need all the children of a parent in a recursive way. How can I achieve this using only sql? (I'm using SQL server)
I tried already using the with statement in sql, but it will now give a lot of results.
WITH bom ( [id]
,[parentNumber]
,[warehouse]
,[sequenceNumber]
,[childNumber]
,[childDescription]
,[qtyRequired]
,[childItemClass]
,[childItemType]
,[scrapFactor]
,[bubbleNumber]
,[operationNumber]
,[effectivityDate]
,[discontinuityDate]
,[companyID] )
AS
(
select * from [CR_ApplicationSuite].[products].[BillOfMaterial] where parentNumber IN ('F611882261', '2912435206')
UNION ALL
select b.* from [CR_ApplicationSuite].[products].[BillOfMaterial] b
INNER JOIN [CR_ApplicationSuite].[products].[BillOfMaterial] c on c.childNumber = b.parentNumber
)
SELECT *
FROM bom
Here's an example that uses a table variable for demonstration purposes.
For a recursive query you need to use the CTE within itself.
I included a rootParentNumber, so it's more obvious what the base parent was.
The WHERE clauses are commented in the example.
Because you can either put a WHERE clause within the Recursive Query, or at the outer query. The former should be faster.
declare #BillOfMaterial TABLE (
[id] [bigint] IDENTITY(1,1) NOT NULL,
[parentNumber] [nvarchar](50) NOT NULL,
[warehouse] [nvarchar](50) NOT NULL,
[sequenceNumber] [int] NOT NULL,
[childNumber] [nvarchar](50) NOT NULL,
[childDescription] [nvarchar](50) NULL,
[qtyRequired] [numeric](18, 3) NOT NULL,
[childItemClass] [nvarchar](50) NULL,
[childItemType] [nvarchar](50) NULL,
[scrapFactor] [numeric](18, 3) NULL,
[bubbleNumber] [int] NOT NULL,
[operationNumber] [int] NOT NULL,
[effectivityDate] [date] NULL,
[discontinuityDate] [date] NULL,
[companyID] [bigint] NOT NULL
);
insert into #BillOfMaterial (parentNumber, childNumber, warehouse, sequenceNumber, qtyRequired, bubbleNumber, operationNumber, companyID) values
('1','2','WH1',1,0,0,0,1),
('2','4','WH1',2,0,0,0,1),
('3','4','WH1',3,0,0,0,1),
('4','5','WH1',4,0,0,0,1),
('5','0','WH1',5,0,0,0,1);
WITH BOM
AS
(
select parentNumber as rootParentNumber, *
from #BillOfMaterial
--where parentNumber IN ('1','3')
union all
select bom.rootParentNumber, b.*
from BOM
INNER JOIN #BillOfMaterial b
on (BOM.childNumber = b.parentNumber and b.childNumber <> '0')
)
SELECT
[rootParentNumber]
,[parentNumber]
,[childNumber]
,[id]
,[warehouse]
,[sequenceNumber]
,[childDescription]
,[qtyRequired]
,[childItemClass]
,[childItemType]
,[scrapFactor]
,[bubbleNumber]
,[operationNumber]
,[effectivityDate]
,[discontinuityDate]
,[companyID]
FROM BOM
--WHERE rootParentNumber IN ('1','3')
ORDER BY [rootParentNumber], [parentNumber], [childNumber]
;

How to copy column Data of one Table to another

I am using the code below:
Insert into JV(PurchaseID)
select PurchaseID from PurchaseReturnDetail
But when I execute the query it gives an error:
Cannot insert the value NULL into column 'column1', table 'database.table1'; column does not allow nulls.
Then my INSERT fails. What could be the issue?
The error says the table has a non-null constraint for the column. To change the column to allow nulls, run this query (for Oracle DB):
alter table TABLE_NAME modify (COLUMN_NAME null);
If first columns is identity column, make sure that auto increment is enabled for that column .
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JV](
[JVID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[JVInvoiceNo] [nvarchar](50) NULL,
[JVDate] [datetime] NULL,
[StoreID] [numeric](18, 0) NULL,
[BusinessID] [numeric](18, 0) NULL,
[UserID] [numeric](18, 0) NULL,
[Currency] [nvarchar](50) NULL,
[Rate] [decimal](18, 10) NULL,
[DueDate] [datetime] NULL,
[Reference] [nvarchar](50) NULL,
[RefID] [numeric](18, 0) NULL,
[Narration] [nvarchar](max) NULL,
[InvoiceRef] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL,
[Type] [nvarchar](50) NULL,
[PurchaseID] [numeric](18, 0) NULL,
CONSTRAINT [PK_JV] PRIMARY KEY CLUSTERED
(
[JVID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Date time index sql server 2005

I know this is a common topic but i stil feel my scenario requires some custom advice. I was selecting from a table the other day and it took me an AGE to select on a datetime column that has not been indexed. I want to index this, only problem ebing is that the "production" 2005 box i am unfamiliar with and how it will handle the index creation. With that in mind i am wondering what the safest way for me to create an index on the table is. All the details i think people will need are below (i hope) :
Index to be created on field 5 (possibly field4 also)
Table 1 definition:
CREATE TABLE [dbo].[TABLE 1](
[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_BLA] DEFAULT (newid()),
[field1] [nvarchar](7) NULL,
[field2] [nvarchar](10) NULL,
[field3] [nvarchar](2) NULL,
[field4] [datetime] NULL,
[field5] [datetime] NULL,
[field6] [smallint] NULL,
[field7] [nvarchar](1) NULL,
[field8] [nvarchar](7) NULL,
[field9] [nvarchar](60) NULL,
[field10] [smallint] NULL,
[field11] [nvarchar](15) NULL,
[field12] [datetime] NULL,
CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Total count of rows in Table 1 : 2926836

SQL Foreign key issue with Primary Keys

I do have a problem connecting two tables on MSSQL Management studio.
My goal is connect tables by foreign key and if I delete user I want 2nd table entry will be deleted automatically. I plan to use DELETE Cascade method for that.
User:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Email is Primary key
Payments:
CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[Investor] [nvarchar](89) NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Investments] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ID is Primary key
My FK should be like USER->PAYMENTS or PAYMENTS->USER?
When I am trying to connect User -> Payments using foregn key by Email -> Investor, it tell me such error:
The columns in table 'Payments' do not match an existing primary key or UNIQUE constraint.
Could you please explain me where problem is? And what I am doing wrong?
Change your structure to:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL);
ALTER TABLE [Users]
ADD CONSTRAINT PK_UsersID PRIMARY KEY (ID);
and then
CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[UserID] [bigint] NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL);
ALTER TABLE Investments
ADD CONSTRAINT PK_InstestmentsID PRIMARY KEY (ID);
ALTER TABLE Investments
ADD CONSTRAINT FK_UsersInvestments
FOREIGN KEY (UserID)
REFERENCES Users(ID);
Then join Users.ID on Investments.UserID
I searched for the error message you are seeing (without the table name) and the general consensus
seems to be that a PRIMARY KEY or UNIQUE contraint has not been correctly set in your tables. The error also tells me you are (probably) using SQL Server.
From technet.microsoft.com:
The columns on the primary key side of a foreign key relationship must
participate in either a Primary Key or a Unique Constraint. After
setting up a Primary Key or a Unique constraint for one of the tables
you've selected, you can then define other relationships for that
table.
Check your PRIMARY KEYS in both tables. Without the actual DDL of your tables it's difficult to be of more help.
EDIT: You have Email as the PRIMARY KEY in your Users table but I do not see an Email field in the Investments table. Which fields are you joining on in your contraint?