需要MYSQL个数据库查询方案
Need MYSQL database query solution
在 MySQL 我有以下 table:
date
work
code
2022-01-01 11:41:24
10
1
2022-01-01 10:41:24
10
1
2022-01-03 09:41:24
0
0
2022-02-04 06:41:24
10
1
2022-02-05 05:41:24
40
1
我的SQL代码:
SELECT extract(MONTH FROM date) AS month, count(number) AS sum_number FROM be WHERE code='1' group by month
这是这段代码的结果:
结果
month
sum_work
1
20
2
50
我怎样才能得到这个结果,我需要在查询中更改什么?
work_days: 每个月工作多少天
最终结果:
month
work_days
sum_work
1
1
20
2
2
50
您必须计算不同的日期:
SELECT MONTH(date) AS month,
COUNT(DISTINCT DATE(date)) AS work_days,
COUNT(*) AS sum_number -- or SUM(work) as your expected result
FROM be
WHERE code='1'
GROUP BY month;
如果我对您的要求的猜测是正确的,您希望每个月的天数有一个或多个记录。
您可以尝试这样的操作:
SELECT LAST_DAY(date) AS month_ending,
COUNT(number) AS sum_number
COUNT (DISTINCT DATE(date)) AS workd_days
FROM be
WHERE code='1'
GROUP BY LAST_DAY(DATE)
LAST_DAY(date) 比 EXTRACT(MONTH FROM date) 更好,因为 2021-01-06
和 2022-01-06
都是 return 1 来自后者。
在 MySQL 我有以下 table:
date | work | code |
---|---|---|
2022-01-01 11:41:24 | 10 | 1 |
2022-01-01 10:41:24 | 10 | 1 |
2022-01-03 09:41:24 | 0 | 0 |
2022-02-04 06:41:24 | 10 | 1 |
2022-02-05 05:41:24 | 40 | 1 |
我的SQL代码:
SELECT extract(MONTH FROM date) AS month, count(number) AS sum_number FROM be WHERE code='1' group by month
这是这段代码的结果:
结果
month | sum_work |
---|---|
1 | 20 |
2 | 50 |
我怎样才能得到这个结果,我需要在查询中更改什么?
work_days: 每个月工作多少天
最终结果:
month | work_days | sum_work |
---|---|---|
1 | 1 | 20 |
2 | 2 | 50 |
您必须计算不同的日期:
SELECT MONTH(date) AS month,
COUNT(DISTINCT DATE(date)) AS work_days,
COUNT(*) AS sum_number -- or SUM(work) as your expected result
FROM be
WHERE code='1'
GROUP BY month;
如果我对您的要求的猜测是正确的,您希望每个月的天数有一个或多个记录。
您可以尝试这样的操作:
SELECT LAST_DAY(date) AS month_ending,
COUNT(number) AS sum_number
COUNT (DISTINCT DATE(date)) AS workd_days
FROM be
WHERE code='1'
GROUP BY LAST_DAY(DATE)
LAST_DAY(date) 比 EXTRACT(MONTH FROM date) 更好,因为 2021-01-06
和 2022-01-06
都是 return 1 来自后者。