lippert
asked on
Need an efficient SQL query
I have a table of parts and a table of orders. I need to construct a query that pulls a subset of parts needed for an assembly and the last order placed for each of those parts. These are huge tables so this needs to be an efficient query. I am working in MS SQL 2012
CREATE TABLE [dbo].[Parts_Master](
[PartNo] [bigint] NOT NULL,
[Nomenclature] [varchar](255) NOT NULL,
[bldg] [int] NULL,
[room] [int] NULL,
[unit] [int] NULL,
[row] [int] NULL,
[shelf] [int] NULL,
[slot] [int] NULL,
[IsSubAssy] [bit] NOT NULL,
[IsAssy] [bit] NOT NULL,
[Overflow] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Parts_Orders](
[UID] [bigint] IDENTITY(1,1) NOT NULL,
[VendorID] [int] NOT NULL,
[VendorOrderID] [varchar](50) NOT NULL,
[OrderDate] [datetime] NOT NULL,
[DetailLine] [int] NOT NULL,
[PartNo] [bigint] NOT NULL,
[Quantity] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Parts_Master](
[PartNo] [bigint] NOT NULL,
[Nomenclature] [varchar](255) NOT NULL,
[bldg] [int] NULL,
[room] [int] NULL,
[unit] [int] NULL,
[row] [int] NULL,
[shelf] [int] NULL,
[slot] [int] NULL,
[IsSubAssy] [bit] NOT NULL,
[IsAssy] [bit] NOT NULL,
[Overflow] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Parts_Orders](
[UID] [bigint] IDENTITY(1,1) NOT NULL,
[VendorID] [int] NOT NULL,
[VendorOrderID] [varchar](50) NOT NULL,
[OrderDate] [datetime] NOT NULL,
[DetailLine] [int] NOT NULL,
[PartNo] [bigint] NOT NULL,
[Quantity] [int] NOT NULL
) ON [PRIMARY]
ASKER
I don't need the last order for assys or sub assys only for parts. Let me give this a try and see if it works.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
This also means you'll want to define PartNo as the primary key on Parts_Master
ALTER TABLE Parts_Orders
ADD CONSTRAINT PK_Parts_Orders PRIMARY KEY CLUSTERED (PartNo)
GO
ASKER
Foreign key already exists.
ASKER
This worked.
Thanks for the grade, but I'm a little confused as to what worked for you, as you accepted a comment relating to a foreign key, but later stated that 'Foreign key already exists'.
If that's all it is, then give this a whirl..
Open in new window