SQL:计算总和达到特定值的行数

发布于 2025-02-06 12:01:55 字数 1871 浏览 5 评论 0原文

我有一个看起来或多或少类似于此表的数据。让我们称此“费用”表。

日期运输水果蔬菜
2022-05-25101030
2022-05-2610040
2022-05-27102020 40
2022-05-281020 3020 30
2022-05-2910060
2022-05-05-30101030
2022-05-31101040
2022-06-01101030
2022-06-06-021020 3030
2022-06-06-031030 3040
2022-06-06-041010 020
2022-06-06-06-053030 30 3030 30 30
2022-06-06102030
2022-06-0710030
2022-06-06-0810030
2022-06-09101020
2022-06-101030 3030

我想知道有多少天,用于多少天五月和六月的几个月,水果的总和和蔬菜等于或大于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.

datetransportationfruitsvegetables
2022-05-25101030
2022-05-2610040
2022-05-27102040
2022-05-28102030
2022-05-2910060
2022-05-30101030
2022-05-31101040
2022-06-01101030
2022-06-02102030
2022-06-03103040
2022-06-0410020
2022-06-05103030
2022-06-06102030
2022-06-0710030
2022-06-0810030
2022-06-09101020
2022-06-10103030

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 技术交流群。

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

发布评论

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

评论(1

初见 2025-02-13 12:01:55

而不是具有子句,而是用 过滤行。

查询

select date_format(date, '%M' '%Y') as month, count(*) as no_of_days
from expenses
where fruits + vegetables >= 50
group by date_format(date, '%M' '%Y');

sql小提琴

Instead of having clause, filter the rows with Where.

Query

select date_format(date, '%M' '%Y') as month, count(*) as no_of_days
from expenses
where fruits + vegetables >= 50
group by date_format(date, '%M' '%Y');

SQL Fiddle

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