In SQL, it is very difficult to do, because SQL is designed to generate its result set at the most basic level, comparing a set of column values ββon one row with another value. What you are trying to do is compare one column value (or multiple column values) across multiple rows with another set of multiple rows.
To do this, you need to create some kind of order signature. Strictly speaking, this cannot be done using query syntax; You will have to use some T-SQL.
declare @Orders table ( idx int identity(1, 1), OrderID int, Signature varchar(MAX) ) declare @Items table ( idx int identity(1, 1), ItemID int, Quantity int ) insert into @Orders (OrderID) select OrderID from [Order] declare @i int declare @cnt int declare @j int declare @cnt2 int select @i = 0, @cnt = max(idx) from @Orders while @i < @cnt begin select @i = @i + 1 declare @temp varchar(MAX) delete @Items insert into @Items (ItemID, Quantity) select ItemID, Count(ItemID) from OrderItem oi join @Orders o on o.idx = @i and o.OrderID = oi.OrderID group by oi.ItemID order by oi.ItemID select @j = min(idx) - 1, @cnt2 = max(idx) from @Items while @j < @cnt2 begin select @j = @j + 1 select @temp = isnull(@temp + ', ','') + '(' + convert(varchar,i.ItemID) + ',' + convert(varchar, i.Quantity) + ')' from @Items i where idx = @j end update @Orders set Signature = @temp where idx = @i select @temp = null end select o_other.OrderID from @Orders o join @Orders o_other on o_other.Signature = o.Signature and o_other.OrderID <> o.OrderID where o.OrderID = @OrderID
This assumes (based on the wording of your question) that ordering multiple items of the same order in order will result in multiple rows, not the Quantity column. If so, simply remove group by from the @Items and replace Count(ItemID) with Quantity .
Adam robinson
source share