sql 查询不同

发布于 2024-09-16 02:01:52 字数 413 浏览 5 评论 0原文

我的数据库记录如下:-

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

可以安排成这样的形式吗?
假设最大总和(数量)=3

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

My database record is as below:-

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

Can it be arrange into this form?
Assume that the max sum(qty)=3

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

维持三分热 2024-09-23 02:01:52

您看起来像是在尝试对按 cartid 订购的同一 foodid 的连续范围(岛)求和?

;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

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
顾铮苏瑾 2024-09-23 02:01:52

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

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文