簡體   English   中英

如何通過組合來自 3 個不同表的數據獲得 output 如下

[英]How to get the output as following by combining data from 3 different tables

所以我的數據庫中有 3 個表,其中所有 3 個表都包含一個具有相似數據的列,但是所有 3 個表中該列的名稱都不同,下面是一個示例。

禁止表

用戶身份 ban_user_id 禁止日期 原因 結束日期
1300 1 xyz xyz xyz
32 1 xyz xyz xyz
43 2 xyz xyz xyz

報告表

用戶身份 last_modified_user_id 報告日期 原因 結束日期
1300 1 xyz xyz xyz
32 2 xyz xyz xyz
43 2 xyz xyz xyz

警告表

用戶身份 警告用戶 ID 警告日期 原因 結束日期
1300 1 xyz xyz xyz
32 2 xyz xyz xyz
43 3 xyz xyz xyz

現在我想通過組合這 3 個表來獲取數據,其中 ban_user_id、last_modified_user_id 和 warning_user_id 包含采取行動的員工的數據,所以我想按員工 id 對數據進行分組。

我正在尋找的 output 如下:

員工編號 總報告 總禁令 總警告
1 1 2 1
2 2 1 1
3 0 0 1

它通過分別對第二列 ban_user_id、last_modified_user_id、warning_user_id 進行分組來計算每個表的數據。 而不是結合數據。

我嘗試了 UNION All 之類的東西,但沒有成功。

預先感謝您的幫助

對所有 3 個表使用UNION ALL ,然后聚合:

SELECT staff_id,
       COUNT(report) AS total_reports,
       COUNT(ban) AS total_bans,
       COUNT(warning) AS total_warnings
FROM (
  SELECT last_modified_user_id AS staff_id, 1 AS report, null AS ban, null AS warning FROM Reports
  UNION ALL
  SELECT ban_user_id, null, 1, null FROM Ban
  UNION ALL
  SELECT warning_user_id, null, null, 1 FROM Warning
) t
GROUP BY staff_id;

或者:

SELECT staff_id,
       SUM(report) AS total_reports,
       SUM(ban) AS total_bans,
       SUM(warning) AS total_warnings
FROM (
  SELECT last_modified_user_id AS staff_id, 1 AS report, 0 AS ban, 0 AS warning FROM Reports
  UNION ALL
  SELECT ban_user_id, 0, 1, 0 FROM Ban
  UNION ALL
  SELECT warning_user_id, 0, 0, 1 FROM Warning
) t
GROUP BY staff_id;

請參閱演示

您可以使用表連接(內/外/左/右)來獲取數據而不是聯合。 我假設 staff_id 相當於 user_id 列,因為您沒有提到任何相關內容,因此您的腳本將如下所示:

SELECT W.user_id AS staff_id, 
    B.ban_user_id, 
    R.last_modified_user_id, 
    W.warning_user_id
FROM Warning AS W
LEFT JOIN Reports AS R on R.user_id = W.user_id
LEFT JOIN Ban AS B on B.user_id = W.user_id
group by W.user_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM