我有数据库
来自标签用户列表
NO NAMA DATE
1 THIS 2019-01-17 18:40:45
2 IS 2019-01-17 18:40:45
3 NAME 2019-02-17 18:40:45
来自表格用户文本
ID TEXT CREATE
1 THIS 2019-01-18 18:40:45
2 IS 2019-02-21 18:40:45
3 TEXT 2019-03-19 18:40:45
如何使用 sql 查询返回这样的结果
Month Name Text
Jan 2 1
Feb 1 1
Mar 0 1
我已经试过了
SELECT MONTHNAME(userlist.date) as Month, COUNT(userlist.no) as name, COUNT(usertext.id) as text FROM userlist, usertext WHERE MONTH(userlist.date) < 12 AND YEAR(userlist.date) = YEAR(CURRENT_TIMESTAMP) GROUP BY MONTHNAME(date)
然后像这样返回
Month Name Text
Jan 1 1
Feb 1 1
Mar 1 1
最佳答案
联合,然后聚合。
SELECT Month, SUM(usr) as Name, SUM(txt) as Text
FROM
(
SELECT MONTH(t.date) AS monthnum, MONTHNAME(t.date) AS Month, 1 AS usr, 0 AS txt
FROM userlist t
WHERE YEAR(t.date) = YEAR(CURRENT_TIMESTAMP)
AND MONTH(t.date) < 12
UNION ALL
SELECT MONTH(t.create) AS monthnum, MONTHNAME(t.create) AS Month, 0 AS usr, 1 AS txt
FROM usertext t
WHERE YEAR(t.create) = YEAR(CURRENT_TIMESTAMP)
AND MONTH(t.create) < 12
) q
GROUP BY monthnum, Month
ORDER BY monthnum
下面是一小段生成 12 个月的 sql。它可以是内部查询中的额外 UNION ALL,以填补缺失月份的空白。
select n as monthnum, monthname(100*n+1) as month, 0 as usr, 0 as txt
from (
select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 union all select 10 union all select 11 union all select 12
) q
关于mysql - SQL Join 来自另一个表的数据计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58594715/