3

我的数据库记录如下:-

cartid  orderid   foodid   qty
==============================
92      107       5        1
93      107       5        1
94      107       5        1
95      107       11       1
96      107       5        1
97      108       5        1

可以安排成这种形式吗?
假设最大 sum(qty)=3

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

2 回答 2

5

您看起来好像正在尝试对相同foodid排序的连续范围(岛)求和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)

退货

foodid      sum(qty)
----------- -----------
5           3
11          1
5           2
于 2010-08-25T10:34:33.307 回答
0

我不确定您所说的 Max Sum(qty)=3 是什么意思...

但这里有一些 SQL 可以帮助您入门:

SELECT        foodid
            , SUM(qty)
FROM        YourTableName
GROUP BY    foodid
于 2010-08-25T10:30:22.167 回答