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

时间:2018-10-24 09:36:31

标签: mysql amazon-redshift

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

表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中有多少个条目是错误的。

我正在使用亚马逊redshift。

所需的输出应如下所示:

TRUE    FALSE     NULL
  1       2        1

2 个答案:

答案 0 :(得分:1)

用例何时

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

答案 1 :(得分:0)

  • 使用Left join从Table2向Table1进行ID
  • 使用诸如boost::bimap之类的聚合函数以及诸如Sum()Ifnull()之类的条件函数/运算符。
  • CodeIS NOT NULL。您应该避免将其用作表名,而应使用其他名称。如果仍然需要使用它,则必须在其周围使用反引号。

尝试以下操作( keyword in MySQL ):

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 DEMO):

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;