我有一张这样的表:
UserID Customer ID status
1 1 1
1 2 1
1 3 1
1 4 2
1 5 1
1 6 3
1 7 2
2 8 1
2 9 2
........
我想总结一下这个表:
UserID count(status 1) count(status 2) count(status 3)
1 4 2 1
2 1 2 3
.........
我怎样才能在PL / SQL中这样做?
提前感谢
答案 0 :(得分:10)
您可以对UserId进行分组并总结不同的状态代码。
类似的东西:
select
UserId,
sum(case status when 1 then 1 else 0 end) as Status1,
sum(case status when 2 then 1 else 0 end) as Status2,
sum(case status when 3 then 1 else 0 end) as Status3
from SomeTable
group by UserId
order by UserId
您也可以考虑简单地对UserId和状态进行分组,尽管结果当然不同:
select UserId, status, count(*)
from SomeTable
group by UserId, status
order by UserId, status
答案 1 :(得分:1)
select userid,
count(decode(status, 1, 1, null)),
count(decode(status, 2, 1, null)),
count(decode(status, 3, 1, null)),
from table
group by userid
答案 2 :(得分:1)
SELECT *
FROM ( SELECT UserID,
status,
COUNT(status)
FROM <table>
GROUP BY UserID,
status
)
PIVOT(COUNT(status) FOR status IN (1,2,3))
答案 3 :(得分:0)
只是跟进@ Vimvq1987和@Guffa评论: SQL 的正确语法是case ... end
,但对于 PL / SQL ,它应该是{{ 1}},所以您提供的链接信息是正确的。
因此,在SQL查询中(要么在SQL-Plus中执行,要么在PL / SQL中用DML执行),您应该使用case ... end case
,但在PL / SQL例程中需要case ... end
。< / p>