SQL:以1行显示结果

时间:2017-07-24 18:25:56

标签: sql oracle count sum

我有一个查询,根据状态列显示计数。

此查询:

SELECT t2.id, t1.PDC_ID, t1.STATUS, COUNT(t1.ID) cnt 
    FROM   table1 t1, table2 t2
    WHERE  t1.dds_id = t2.id
    AND    T2.ID = 75790 and T1.PDC_ID = 2
    GROUP BY t1.PDC_ID, t2.id, t1.STATUS

返回:

ID    PDC_ID   STATUS     CNT
75790   2       Active     13
75790   2       Inactive    3

有没有办法在一行中显示结果总计活动状态的计数和两种状态,如:

ID    PDC_ID  ACTIVE_CNT  ALL_CNT
75790   2       13         16

谢谢

2 个答案:

答案 0 :(得分:2)

基本上只是修复GROUP BY并添加条件聚合:

SELECT t2.id, SUM(CASE WHEN t1.STATUS = 'ACTIVE' THEN 1 ELSE 0 END) as ACTIVE_CNT, 
       COUNT(t1.ID) ALL_CNT 
FROM table1 t1 JOIN
     table2 t2
     ON t1.dds_id = t2.id
WHERE T2.ID = 75790 and T1.PDC_ID = 2
GROUP BY t1.PDC_ID;

请注意,我还修复了FROM子句以使用正确的JOIN语法。

答案 1 :(得分:0)

你可以通过分析函数使用oracle over partition 请参阅此处的文档partition by examples