Given the following table:
CREATE TABLE [dbo].[Orders]( [OrderID] [int] IDENTITY(1,1) NOT NULL, [CustomerID] [int] NULL, [OrderDate] [datetime] NULL, CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED ( [OrderID] ASC ) )
The following operator shows the last order placed by the customer over a period of time, followed by other orders.
;With OrderList As ( Select Top 100 Percent * From dbo.Orders Where OrderDate >= DateAdd(hh, -1, GetDate()) Order By OrderDate Desc ) Select 'First' As DataType, CustomerID, Min(OrderID) As OrderID, Min(OrderDate) As OrderDate From OrderList Group By CustomerID Union All Select 'Second' As DataType, CustomerID, OrderID, OrderDate From OrderList Where OrderID Not In ( Select Min(OrderID) As OrderID From OrderList Group By CustomerID )
The last part is commented out as I used it to check if I really got the correct lines.
In short, the With statement restricts orders from the table to those that were installed in the last hour based on the current system date, and orders them by order date. The first expression (Select "First") retrieves only the first sales orders. The second statement (Select "Second") retrieves all other orders that are not in the first expression.
This should work as you expected, Mohammed, however I do not have 1000 lines to check this. Performance should be in order, as part "C" will create a temporary table for work.
KMB
source share