sql - 如何在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
请帮我解决这个问题..谢谢
解决方案
在 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
;
推荐阅读
- c# - ASP.NET MVC WebAPI JsonContent 返回流不是 WebServer 预期的 JSON
- java - 无法在 Spring Boot 中反序列化嵌套对象“Role”
- php - 使用 MySql 连接登录 PHP
- html - 我可能以错误的方式使用 div 标签请告诉我正确的方式
- firebase - 在 Firestore Vue 中使用自定义键
- android-studio - 创建没有 Counter Project 模板的项目
- php - 记录在查看页面上获得了两次
- vb.net - 尝试...抓住:性能
- java - 当我将实体转换为 Json 时,为什么 LocalDate 格式会发生变化?
- python - 函数中的列表理解