如何比较两个表的真计数和假计数

lpwwtiir  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(299)

我在下面提到了两个表格:
表1:

ID        Code
URT-112   AAB
URT-113   12F
URT-114   234
URT-115   [Null]

表2:

Merchant_ID     Flag
URT-112         CDE
URT-113         11F
URT-114         234
URT-115         DEW

利用上述表格,并考虑 Table2 准确地说,我想知道有多少条目是错误的 Table1 .
我用的是亚马逊红移。
所需输出应如下所示:

TRUE    FALSE     NULL
  1       2        1
2izufjch

2izufjch1#

使用案例

SELECT 
  SUM(case when  t2.Flag = t1.Code then 1 else 0 end) AS TRUE_CNT, 
  SUM(case when t1.Code is not null and t2.Flag <> t1.Code then 1 else 0 end) AS FALSE_CNT,  
  SUM(case when  t1.Code IS NULL then 1 else 0 end) AS  NULL_CNT
FROM Table2 AS t2 
LEFT JOIN Table1 AS t1 ON t2.Merchant_ID = t1.ID
oknrviil

oknrviil2#

做一个 Left join 从表2到表1使用 ID .
使用聚合函数,如 Sum() ,具有条件函数/运算符,如 Ifnull() , IS NOT NULL . Code 是mysql中的关键字。您应该避免将其用作表名,而是使用其他名称。如果您仍然需要使用它,您将不得不在它周围使用反记号。
尝试以下操作(db fiddle演示):

SELECT 
  SUM(IF(t1.`Code` IS NOT NULL, t2.Flag = t1.`Code`, 0)) AS `TRUE`, 
  SUM(IF(t1.`Code` IS NOT NULL, t2.Flag <> t1.`Code`, 0)) AS `FALSE`, 
  SUM(IF(t1.`Code` IS NULL, 1, 0)) AS `NULL`
FROM Table2 AS t2 
LEFT JOIN Table1 AS t1 ON t1.ID = t2.Merchant_ID

缩短版(db fiddle):

SELECT 
  SUM(t1.`Code` IS NOT NULL AND t2.Flag = t1.`Code`) AS `TRUE`, 
  SUM(t1.`Code` IS NOT NULL AND t2.Flag <> t1.`Code`) AS `FALSE`,  
  SUM(t1.`Code` IS NULL) AS `NULL`
FROM Table2 AS t2 
LEFT JOIN Table1 AS t1 ON t1.ID = t2.Merchant_ID;

相关问题