SQL:计算总和达到特定值的行数
我有一个看起来或多或少类似于此表的数据。让我们称此“费用”表。
日期 | 运输 | 水果 | 蔬菜 |
---|---|---|---|
2022-05-25 | 10 | 10 | 30 |
2022-05-26 | 10 | 0 | 40 |
2022-05-27 | 10 | 20 | 20 40 |
2022-05-28 | 10 | 20 30 | 20 30 |
2022-05-29 | 10 | 0 | 60 |
2022-05-05-30 | 10 | 10 | 30 |
2022-05-31 | 10 | 10 | 40 |
2022-06-01 | 10 | 10 | 30 |
2022-06-06-02 | 10 | 20 30 | 30 |
2022-06-06-03 | 10 | 30 30 | 40 |
2022-06-06-04 | 10 | 10 0 | 20 |
2022-06-06-06-05 | 30 | 30 30 30 | 30 30 30 |
2022-06-06 | 10 | 20 | 30 |
2022-06-07 | 10 | 0 | 30 |
2022-06-06-08 | 10 | 0 | 30 |
2022-06-09 | 10 | 10 | 20 |
2022-06-10 | 10 | 30 30 | 30 |
我想知道有多少天,用于多少天五月和六月的几个月,水果的总和和蔬菜等于或大于50。
我希望得到的答案是4天5月(05-27,05-28,05-29,05-31)和6月的5天(06-02,06-02,06-03,06-05,06-05,06-06 ,06-10)
我尝试使用此脚本,但是...
select date_format(date,'%m''%y'), count (date)< br> 来自费用
组由 date_format(日期,'%m''%y')
具有 sum(水果 +蔬菜)&gt; = 50
...而不是仅计算每月的数字,其水果总和等于或大于50,在两个月的时间里,它在桌上均计算,也就是说,它的答案是5月的7天和6月的10天。
我正在使用MySQL的最新版本。
I have a data that looks like more or less like this table. Let's call this "expenses" table.
date | transportation | fruits | vegetables |
---|---|---|---|
2022-05-25 | 10 | 10 | 30 |
2022-05-26 | 10 | 0 | 40 |
2022-05-27 | 10 | 20 | 40 |
2022-05-28 | 10 | 20 | 30 |
2022-05-29 | 10 | 0 | 60 |
2022-05-30 | 10 | 10 | 30 |
2022-05-31 | 10 | 10 | 40 |
2022-06-01 | 10 | 10 | 30 |
2022-06-02 | 10 | 20 | 30 |
2022-06-03 | 10 | 30 | 40 |
2022-06-04 | 10 | 0 | 20 |
2022-06-05 | 10 | 30 | 30 |
2022-06-06 | 10 | 20 | 30 |
2022-06-07 | 10 | 0 | 30 |
2022-06-08 | 10 | 0 | 30 |
2022-06-09 | 10 | 10 | 20 |
2022-06-10 | 10 | 30 | 30 |
I want to know how many days, for the months of May and June, the sum of fruits and vegetables was equal to or greater than 50.
The answer that I'm expecting to get is 4 days for May (05-27,05-28, 05-29, 05-31) and 5 days for June (06-02, 06-03, 06-05, 06-06, 06-10)
I tried to use this script, however...
SELECT date_format(date, '%M' '%Y'), COUNT(date)
FROM expenses
GROUP BY date_format(date, '%M' '%Y')
HAVING SUM(fruits + vegetables)>=50
...instead of counting only the number days per month whose sum of fruits and vegetables was equal to or greater than 50, it counts all days in the table for the two months, that is to say, it yields an answer of 7 days for May and 10 days for June.
I am using the latest version of MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是
具有
子句,而是用 过滤行。查询
sql小提琴
Instead of
having
clause, filter the rows withWhere
.Query
SQL Fiddle