Oracle sql 计算单列中不同值的实例

标签 oracle pivot

我有一个带有状态列的表。我想要一个 Oracle sql 查询,它将仅在一行中列出每个状态中的行数。
例如,如果我的 table 是

Table A
Id       Status  Fkey
1         20      500
2         20      500  
3         30      501
4         40      501
5         30      502

输出应该是
Fkey     Count_status20     Count_status30    Count_status40
500        2                      0                 0
501        0                      1                 1

这里稍微有点扭曲
Table B 
FKey TKey 
500   1001 
501   1001
502   1002 

现在输出应该是
TKey Count_status20     Count_status30    Count_status40 
1001     2                     1                    1 
1002     0                     1                    0

最佳答案

如果您使用的是 Oracle 11g,那么您可以使用 PIVOT功能:

select *
from
(
  select tkey, status, 
    status as col
  from tableB b
  left join tableA a
    on a.fkey = b.fkey
) src
pivot
(
  count(status)
  for col in ('20' as Count_Status20, 
              '30' as Count_Status30,
              '40' as Count_Status40)
) piv;

SQL Fiddle with Demo

如果您没有使用 Oracle11g,那么您可以使用带有 CASE 的聚合函数陈述:
select tkey, 
  count(case when status = 20 then 1 else null end) as Count_Status20,
  count(case when status = 30 then 1 else null end) as Count_Status30,
  count(case when status = 40 then 1 else null end) as Count_Status40
from tableB b
left join tableA a
  on b.fkey = a.fkey
group by tkey

SQL Fiddle with Demo

关于Oracle sql 计算单列中不同值的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13238142/

相关文章:

也许是 SQL Server PIVOT?

python - Python 中的光滑枢轴和映射

oracle - 如何在oracle中创建xml

sql - Oracle SQL - 如何在一行中显示一对多关系?

linux - 我需要在 oracle 数据库卡住时测试我的应用程序的行为。因此我需要模拟 oracle DB freeze

sql-server - SQL 数据透视问题

oracle - 全局临时表并发

java - tableView(JavaFX) 填写表单 ObservableList 不起作用

mysql - 使用动态列名进行分组和求和