Sql - 替代WITH ... AS

时间:2017-04-17 13:40:08

标签: sql oracle

此示例中是否有高效备用SQL?我不想使用WITH ... AS,这是主要标准

WITH TEMP_TABLE AS (
     SELECT status, COUNT(1) as total FROM XYZ GROUP BY status
    )
SELECT 
         NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'A'),0) AS A_COUNT ,
         NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'B'),0) AS B_COUNT ,
         NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'C'),0) AS C_COUNT ,
         NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'D'),0) AS D_COUNT , 
         NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'E'),0) AS E_COUNT ,
         NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'F'),0) AS F_COUNT  
FROM DUAL; 

我读过类似的问题,但他们使用其他ddl的东西,我只想要一个基本的SQL语句。

3 个答案:

答案 0 :(得分:4)

只需使用条件聚合:

SELECT SUM(CASE WHEN STATUS = 'A' THEN 1 ELSE 0 END) AS A_COUNT ,
       SUM(CASE WHEN STATUS = 'B' THEN 1 ELSE 0 END) AS B_COUNT ,
       SUM(CASE WHEN STATUS = 'C' THEN 1 ELSE 0 END) AS C_COUNT ,
       SUM(CASE WHEN STATUS = 'D' THEN 1 ELSE 0 END) AS D_COUNT ,
       SUM(CASE WHEN STATUS = 'E' THEN 1 ELSE 0 END) AS E_COUNT ,
       SUM(CASE WHEN STATUS = 'F' THEN 1 ELSE 0 END) AS F_COUNT 
FROM XYZ ;

我应该指出,将值放在不同的行上会更容易:

select status, count(*)
from xyz
group by status;

答案 1 :(得分:2)

这是一个简单的PIVOT查询

select *
from (select status from XYZ )
pivot (
   count(*) for status in (
      'A' as a_count, 'B' as b_count, 
      'C' as c_count, 'D' as d_count, 
      'E' as e_count, 'F' as f_count 
));

答案 2 :(得分:1)

已经给出的答案是完美的,你应该使用它们。但是,为了向您提供一般解决方案(也许您必须转换其他查询),它将是这一个:

SELECT 
     NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'A'),0) AS A_COUNT ,
     NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'B'),0) AS B_COUNT ,
     NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'C'),0) AS C_COUNT ,
     NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'D'),0) AS D_COUNT , 
     NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'E'),0) AS E_COUNT ,
     NVL((SELECT TOTAL  FROM TEMP_TABLE WHERE STATUS = 'F'),0) AS F_COUNT  
FROM 
    (SELECT status, COUNT(1) as total FROM XYZ GROUP BY status) TEMP_TABLE;