J'ai cette requête et je sais qu'il y a une meilleure façon de l'écrire. Voici la requête qui compte les commandes pour savoir ce qu'il reste en stock.
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
\====================================
voici un script pour les tables
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' )