繁体   English   中英

SQL 连接其他表的数据计数

[英]SQL Join data count from another tables

我有数据库

来自表格用户列表

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

您可以尝试加入 count 的子查询

select  t1.my_month month, t2.count_name, t3.count_text
from( 
  select  month(create ) my_month
  from userlist
  union  
  select  month(create) 
  from usertext
) t1 
left join  (
 select month(create) month, count(*) count_name
 from  userlist 
 group by month(create)
) t2 on t2.month  = t1.my_month
left join  (
 select month(create) month, count(*) count_text
 from  usertext
 group by month(create)
) t3 on t3.month  = t1.my_month

联合,然后聚合。

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 

下面是一小块 sql 生成 12 个月。 它可能是内部查询中的额外 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM