获取组内每个条件的单独计数

时间:2015-04-29 00:53:49

标签: sql oracle group-by oracle10g aggregate-functions

我试图从Oracle 10g表中获取表信息的视图,该表列出了各列中特定值的计数,每行都是组值。

例如: 第一个选择是:

SELECT processed_by, count(priority) as P2
FROM agreement_activity
WHERE priority = '2'
GROUP BY processed_by

哪个输出:

PROCESSED_BY                           P2
------------------------------ ----------
Alicia                                  2
Christine                               2

第二个选择是:

SELECT processed_by, count(priority) as P1
FROM agreement_activity
WHERE priority = '1'
GROUP BY processed_by

哪个输出:

PROCESSED_BY                           P1
------------------------------ ----------
Bonita                                  2
Alicia                                  6
Christine                               2

我要找的是输出这些值如下:

PROCESSED_BY                           P1         P2
------------------------------ ---------- ----------
Bonita                                  2          
Alicia                                  6          2        
Christine                               2          2

这可能吗?

2 个答案:

答案 0 :(得分:2)

您可以将sumcase表达式一起使用来获取条件计数:

select processed_by
     , sum(case when priority = 1 then 1 else 0 end) as P1
     , sum(case when priority = 2 then 1 else 0 end) as P2
from agreement_activity
group by processed_by

P.S。如果您不关心P1P2可能null而不是0,则可以在两个表达式中省略else

答案 1 :(得分:0)

这是我实现sql的方式。我正在使用firebird代码,但我认为你可以将代码转换为你的sql

SELECT
a.equipmentid,
a.name equipname,
w1.countwarranty1 ,
w2.countwarranty2
FROM TBL_EQUIPMENTMST a 
inner JOIN
    (select c.equipmentid, count(c.WARRANTYID) countwarranty1 from tbl_equipwarranty c where c.serviceproduct='1' group by c.equipmentid) w1
ON w1.equipmentid = a.equipmentid
inner JOIN
     (select d.equipmentid, count(d.WARRANTYID) countwarranty2 from tbl_equipwarranty d where d.serviceproduct='2' group by d.equipmentid) w2 
ON w2.equipmentid = a.equipmentid
inner JOIN
(select e.equipmentid, count(e.equiplocationid) countlocation from tbl_equiplocation e group by e.equipmentid) w3
ON w3.equipmentid = a.equipmentid

这是输出

enter image description here

我的保修表只有2个设备保修,这就是为什么它只显示2.

您也可以使用不同的计数内连接到同一个表。 如您所见,我的保修有多重保修,其中每张桌子上的服务产品不同

如果我编辑你的代码就会像这样

SELECT a.processed_by, b.priority as p2, c.priority as p1
FROM agreement_activity a
inner join
 (
  SELECT w1.processed_by, count(w1.priority) as P2 FROM agreement_activity w1
  WHERE w1.priority = '2' GROUP BY w1.processed_by
 ) b 
on a.processed_by = b.processed_by
inner join
 (
  SELECT w2.processed_by, count(w2.priority) as P2 FROM w2.agreement_activity
  WHERE w2.priority = '1' GROUP BY w2.processed_by
 ) c 
on a.processed_by = c.processed_by

测试它