簡體   English   中英

如何統計匹配和不匹配的記錄

[英]How to count matching and non-matching records

有什么方法可以計算服務器中兩個不同表(表ih )中的匹配和非匹配記錄。 例如,如果i.id = h.id計算匹配記錄,如果i.id != h.id則計算非匹配記錄。

這個邏輯在我的腦海中是有道理的,但我正在努力想出代碼。 我已經嘗試過case語句,但是沒有用。 我只需要匹配記錄的總數和表h未匹配記錄的總數。

我不確定您到底需要什么,但也許類似的東西可以幫助您:

SELECT
    COUNT(i.id) AS matching_count,
    COUNT(h.id) - COUNT(i.id) AS non_matching_count
FROM h
    LEFT JOIN i ON h.id = i.id;

上面的查詢將告訴有多少個 id 存在於兩個表中,以及表h中有多少個 id 在表i中不存在。

或者逆邏輯:

SELECT
    COUNT(h.id) AS matching_count,
    COUNT(i.id) - COUNT(h.id) AS non_matching_count
FROM i
    LEFT JOIN h ON i.id = h.id;

上面的查詢會告訴多少IDS在表和多少IDS的表存在i沒有在表中存在h

或者也許你想要這樣的東西:

SELECT
    COUNT(CASE WHEN h.id = i.id THEN 1 ELSE NULL END) AS matching_count,
    COUNT(CASE WHEN h.id != i.id THEN 1 ELSE NULL END) AS non_matching_count
FROM h, i;

上面的查詢將說明兩個表中存在多少個 id,以及笛卡爾積中存在多少個分歧。

我想你可能想先在id級別總結一下:

select id, max(in_i) as in_i, max(in_h) as in_h
from ((select id, 1 as in_i, 0 as in_h
       from i
      ) union all
      (select id, 0, 1
       from h
      )
     ) ih
group by id;

然后總結一下:

select count(*) as num_total_ids,
       sum(in_i) as num_i, sum(in_h) as num_h,
       sum(in_i * (1 - in_h)) as in_i_only,
       sum(in_h * (1 - in_i)) as in_h_only,
       sum(in_i * in_h) as num_both,
from (select id, max(in_i) as in_i, max(in_h) as in_h
      from ((select id, 1 as in_i, 0 as in_h
             from i
            ) union all
            (select id, 0, 1
             from h
            )
           ) ih
      group by id
     ) i

暫無
暫無

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

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