我有這個查詢,我知道有一個更好的方式來寫它。這裏是查詢命令,以查找庫存中剩下的內容。更好的SQL統計條款數與條款
DECLARE @reserveDate as Datetime = '10/5/2011 10:20'
SELECT p.Name
, p.Quantity
, (SELECT COUNT(*)
FROM [Order] o
WHERE o.ProductId = p.Id
AND o.Completed = 1) as Completed
, (SELECT COUNT(*)
FROM [Order] o
WHERE o.ProductId = p.Id
AND o.Completed <> 1
AND o.ModifiedDate >= @reserveDate) as Reserved
, (SELECT COUNT(*)
FROM [Order] o
WHERE o.ProductId = p.Id
AND o.Completed <> 1
AND o.ModifiedDate < @reserveDate) as ReserveExpired
--, (Quantity - Completed - Reserved) as Available
FROM Product p
====================================
這裏是一個腳本表
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Order]') AND type IN (N'U')) DROP TABLE [Order]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Product]') AND type IN (N'U')) DROP TABLE [Product]
-- Product --
PRINT N' [Product] '
CREATE TABLE Product
(
[Id] INT NOT NULL IDENTITY PRIMARY KEY,
[Name] NVARCHAR(50) ,
[Quantity] INT ,
);
SET IDENTITY_INSERT Product ON
INSERT INTO Product ([Id] , [Name] , [Quantity]) VALUES ('1', 'Tea Package', 7000)
INSERT INTO Product ([Id] , [Name] , [Quantity]) VALUES ('2', 'Sugar Package', 8000)
SET IDENTITY_INSERT Product OFF
-- Order --
PRINT N' [Order]'
CREATE TABLE [Order]
(
[Id] INT NOT NULL IDENTITY PRIMARY KEY ,
[ProductId] INT ,
[Completed] Bit,
[ModifiedDate] DATETIME
);
ALTER TABLE [Order] ADD CONSTRAINT FK_Product_Order FOREIGN KEY (ProductId) REFERENCES [Product] (Id)
GO
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 1, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 1, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 0, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 0, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 0, '10/5/2011 11:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 0, '10/6/2011 11:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (1, 0, '10/6/2011 11:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (2, 1, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (2, 1, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (2, 0, '10/5/2011 10:10' )
INSERT INTO [Order] ([ProductId], [Completed], [ModifiedDate] ) VALUES (2, 0, '10/6/2011 10:10' )