开发者

sql query distinct

开发者 https://www.devze.com 2023-01-13 04:32 出处:网络
My database record is as below:- cartidorderidfoodidqty ============================== 92107开发者_JAVA技巧51

My database record is as below:-

cartid  orderid   foodid   qty
==============================
92      107       开发者_JAVA技巧5        1
93      107       5        1
94      107       5        1
95      107       11       1
96      107       5        1
97      108       5        1

Can it be arrange into this form?

Assume that the max sum(qty)=3

foodid   sum(qty)
=================
5        3
11       1
5        2


You look like you are trying to sum contiguous ranges (islands) of the same foodid ordered by cartid?

;with cart as
(
SELECT 92 AS cartid,107 AS orderid,5 AS foodid, 1 AS qty UNION ALL
SELECT 93,107,5, 1 UNION ALL
SELECT 94,107,5, 1 UNION ALL
SELECT 95,107,11,1 UNION ALL
SELECT 96,107,5, 1 UNION ALL
SELECT 97,108,5, 1 

),
NumberedCart As
(
SELECT cartid,foodid,qty,
ROW_NUMBER() OVER (ORDER BY cartid)- 
       ROW_NUMBER() OVER (PARTITION BY foodid ORDER BY cartid) AS G
 FROM cart
 )

 SELECT foodid, SUM(qty) AS [sum(qty)]
 FROM NumberedCart
 GROUP BY foodid,G
 ORDER BY MIN(cartid)

Returns

foodid      sum(qty)
----------- -----------
5           3
11          1
5           2


I'm not sure what you mean by Max Sum(qty)=3...

But here is some SQL to get you started:

SELECT        foodid
            , SUM(qty)
FROM        YourTableName
GROUP BY    foodid
0

精彩评论

暂无评论...
验证码 换一张
取 消