单行中多选语句的输出

时间:2017-07-13 10:46:36

标签: sql sql-server tsql

我有多个查询,根据不同的条件提供计数。

是否可以将所有结果都放在单行中。

例如:

Query1: 
SELECT COUNT(COL25) ASSURED, FROM TAB1 WHERE COL1= 'ALPHA' AND COL2='ROLE'

Query2:
SELECT COUNT(COL25) RELEASE FROM TAB1 WHERE COL3 in('BEETA','X','Y') AND COLSTATUS='ABC'

The result for 1st query is ASSURED = 100
and 2nd Query is RELEASE = 5000

我正在尝试将输出显示为

ASSURED  | RELEASE
100      | 5000

2 个答案:

答案 0 :(得分:4)

使用条件聚合:

SELECT SUM(CASE WHEN COL1 = 'ALPHA' AND COL2 = 'ROLE' THEN 1 ELSE 0 END)  as ASSURED,
       SUM(CASE WHEN COL3 = 'BEETA' AND COLSTATUS = 'ABC' THEN 1 ELSE 0 END) as RELEASE
FROM TAB1; 

编辑:

如果您确实需要计算非NULL值,则可以明确(我的偏好):

SELECT SUM(CASE WHEN COL1 = 'ALPHA' AND COL2 = 'ROLE' AND col25 IS NOT NULL THEN 1 ELSE 0 END)  as ASSURED,
       SUM(CASE WHEN COL3 = 'BEETA' AND COLSTATUS = 'ABC' AND col25 IS NOT NULL THEN 1 ELSE 0 END) as RELEASE
FROM TAB1; 

或者更隐蔽一点:

SELECT COUNT(CASE WHEN COL1 = 'ALPHA' AND COL2 = 'ROLE' THEN col25 END) as ASSURED,
       COUNT(CASE WHEN COL3 = 'BEETA' AND COLSTATUS = 'ABC' THEN col25 END) as RELEASE
FROM TAB1; 

答案 1 :(得分:0)

你也可以使用联接,但@Gordon Linoff的回答比这更清晰,也更短。

SELECT first.ASSURED, second.RELEASE
FROM
    (SELECT
         COUNT(COL25) ASSURED
    FROM TAB1 
    WHERE COL1= 'ALPHA' AND COL2='ROLE') AS first
INNER JOIN (SELECT 
                 COUNT(COL25) RELEASE 
             FROM TAB1 
             WHERE COL3 in('BEETA','X','Y') 
             AND COLSTATUS='ABC') AS second
         ON 1=1