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

Oracle sql to count instances of different values in single column(Oracle sql计算单列中不同值的实例)
本文介绍了Oracle sql计算单列中不同值的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有状态列的表.我想要一个 Oracle sql 查询,它只会在一行中列出我在每个状态中的行数.例如,如果我的桌子是

I have a table with status column. I want an Oracle sql query which will list me count of rows in each status in only one row. for eg if my table is

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函数:

If you are using Oracle 11g, then you can use the PIVOT function:

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语句的聚合函数:

If you are not using Oracle11g, then you can use an aggregate function with a CASE statement:

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计算单列中不同值的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

SQL to Generate Periodic Snapshots from Transactions Table(用于从事务表生成定期快照的SQL)
MyBatis support for multiple databases(MyBatis支持多个数据库)
Oracle 12c SQL: Missing column Headers in result(Oracle 12c SQL:结果中缺少列标题)
SQL query to find the number of customers who shopped for 3 consecutive days in month of January 2020(查询2020年1月连续购物3天的客户数量)
SQL Server 2016 - How to do a simple pivot(SQL Server 2016-如何进行简单的透视)
How to get top 10 data weekly (This week, Previous week, Last month, 2 months ago, 3 month ago)(如何每周获取前十大数据(本周、前一周、上个月、2个月前、3个月前))