首页 > 解决方案 > 如何在oracle中加入和计算多个条件

问题描述

我有 2 张桌子:

table1(id, name)
1233    AAA
3424    BBB
4345    CCC
4342    DDD
1243    RRR
3453    GGG

table2(id,date,status)
1233    01/07/19    1
3424    01/07/19    1
4342    01/07/19    2
1243    01/07/19    1
4342    01/07/19    1
4345    02/07/19    2
1243    02/07/19    1
1233    02/07/19    1
4345    03/07/19    1
4342    03/07/19    2
1233    03/07/19    1
4342    04/07/19    2
4345    04/07/19    2
4342    04/07/19    1
1243    04/07/19    2

15 行

我试过这段代码

SELECT    rn.id, name, NVL(cnt, 0) jum
    FROM     table1 rn
    LEFT JOIN (SELECT   id, COUNT(id) AS cnt
               FROM     VIEW_AKTIFITAS
               WHERE extract(year from date)=2019
               AND extract(month from date)=7
               GROUP BY id,extract(month from date) n ON n.id= rn.id

我想得到这个结果如何计算表 2 中的状态条目

RESULT
ID  COUNT_STATUS_1 COUNT_STATUS_2 TOTAL_COUNT
1233    2           0       2
3424    2           0       2
4345    1           2       3 
4342    2           3       5
1243    2           1       3
3453    0           0       0

请帮我解决这个问题..谢谢

标签: sqloraclejoincount

解决方案


在 Oracle 11.1 及更高版本中,您可以使用PIVOT运算符进行聚合。像这样的东西:

select id, name, count_status_1, count_status_2, 
       count_status_1 + count_status_2 as total_count
from   (select t1.id, t1.name, t2.status from table1 t1 left join table2 t2
                                                        on t1.id = t2.id)
pivot  (count(*) for status in (1 as count_status_1, 2 as count_status_2))
order  by id   --  if needed
;

推荐阅读