簡體   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