Sql-Server

連接兩個表並在單個查詢中返回數據和計數

  • February 7, 2018

我在 SQL Server 數據庫中有兩張表,一張有兩列,一張有四列:

  1. tbl_email_list

  2. email_list_id int(PK)

  3. email_list_name varchar

  4. tbl_email-details

  5. email_uniq_id int(PK)

  6. email_list_id int(FK)

  7. email_address varchar

  8. blacklist bit

我想在一個應該返回的查詢中檢索數據

  1. tbl_email_list 中的所有電子郵件列表;
  2. 與特定 email_list_id 關聯的 email_address 總數;
  3. 列入白名單的電子郵件地址總數(其中 blacklist=0);
  4. 列入黑名單的電子郵件地址總數(其中 blacklist=1)。
select l.email_list_id, l.email_list_name,
   count(d.email_uniq_id) as full_count,
   count(case when d.blacklist = 0 then d.email_uniq_id end) as white_count,
   count(case when d.blacklist = 1 then d.email_uniq_id end) as black_count
from tbl_email_list as l
left join [tbl_email-details] as d on d.email_list_id = l.email_list_id
group by l.email_list_id, l.email_list_name;

通過計算可能為空的事物,我們讓零出現在結果集中,這是一種非常有用的技術。在這裡,我對黑名單結果和整體(基於外連接)都這樣做。

引用自:https://dba.stackexchange.com/questions/98663