简体   繁体   English

如何使用 COUNT 和 WHERE 子句从两个不同的表中选择 2 个不同的列

[英]How to select 2 different columns from two different tables with COUNT and WHERE clause

I really need your help on this, I have these queries where I want to select 2 columns of 2 different tables with count and where statement..我真的需要你的帮助,我有这些查询,我想用 count 和 where 语句选择 2 个不同表的 2 列。

SELECT Error_Code as ISERR, 
       COUNT(Error_Code) as A 
FROM COMPIS 
WHERE test_date BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00' 
  AND Error_Code <> ' ' 
GROUP BY Error_Code

SELECT error_code as SCERR, 
       COUNT(error_code) as B 
FROM COMPSER 
WHERE test_date_time BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00' 
  AND error_code <> ' ' 
GROUP BY error_code

I have tried these queries, but this only showed me null values.我试过这些查询,但这只显示空值。

SELECT A, a.ISERR, B, b.SCERR
FROM ( SELECT Error_Code as ISERR, 
              COUNT(Error_Code) as A 
       FROM COMPIS 
       WHERE test_date BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00' 
         AND Error_Code <> ' ' 
       GROUP BY Error_Code ) a,
     ( SELECT error_code as SCERR, 
              COUNT(error_code) as B 
       FROM COMPSER 
       WHERE test_date_time BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00' 
         AND error_code <> ' ' 
       GROUP BY error_code ) b

OUTPUT was:输出是:

A    | ISERR | B   | SCERR
-----+-------+-----+------
null   null   null   null

Your help will be appreciated.您的帮助将不胜感激。 Thanks谢谢

SELECT error_code, 
       SUM(CASE WHEN table='A' THEN cnt END) cnt_A, 
       SUM(CASE WHEN table='B' THEN cnt END) cnt_B
FROM ( SELECT Error_Code as ISERR, 
              COUNT(Error_Code) as cnt,
              `A` as table 
       FROM COMPIS 
       WHERE test_date BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00' 
         AND Error_Code <> ' ' 
       GROUP BY Error_Code
     UNION ALL
       SELECT error_code, 
              COUNT(error_code),
              'B'
       FROM COMPSER 
       WHERE test_date_time BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00' 
         AND error_code <> ' ' 
       GROUP BY error_code ) total
GROUP BY error_code

If you need NULL instead of zeros use MAX instead SUM.如果您需要 NULL 而不是零,请使用 MAX 代替 SUM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM