有人可以帮我设计查询以获得低于o / p。
我有数据:
Table X:
Count Name Amount Days
5 ABC 500 Day1
10 ABC 1000 Day2
3 BCD 100 Day1
4 BDC 200 Day2
我需要的结果:
Name Count AmountDay1 Count AmountDay2
ABC 5 500 10 1000
BCD 3 100 4 200
等
这可能吗?
我尝试了以下查询,但未获得所需的o / p
select * from X
pivot
(sum(amount) for days in ('Day1', 'Day2'))
请帮忙 我正在使用Oracle 11 G
答案 0 :(得分:0)
由于您希望在两列Count
和Amount
上进行数据透视,因此可能更容易使用带有CASE表达式的聚合函数来获取结果:
select name,
sum(case when days = 'Day1' then "count" else 0 end) CountDay1,
sum(case when days = 'Day1' then amount else 0 end) AmountDay1,
sum(case when days = 'Day2' then "count" else 0 end) CountDay2,
sum(case when days = 'Day2' then amount else 0 end) AmountDay2
from tableX
group by name;
如果您想使用PIVOT功能,那么您首先需要取消Amount
和Count
这两列:
select name, CountDay1, AmountDay1, CountDay2, AmountDay2
from
(
select name, col||days as col, value
from tableX
unpivot
(
value
for col in ("Count", Amount)
) u
) d
pivot
(
sum(value)
for col in ('CountDay1' as CountDay1, 'AMOUNTDay1' as AmountDay1,
'CountDay2' as CountDay2, 'AMOUNTDay2' as AmountDay2)
) piv;
答案 1 :(得分:0)
你需要在两列数量和数量上进行调整:
从x中选择* 枢 (分(计)作为计数,('Day1','Day2')中的天数(金额))