1

有人可以帮我设计查询以低于 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

ETC

这可能吗?

我尝试了以下查询,但没有得到所需的 o/p

select * from X
pivot
(sum(amount) for days in ('Day1', 'Day2'))

请帮助我正在使用 Oracle 11 G

4

2 回答 2

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;

请参阅带有演示的 SQL Fiddle

如果您想使用 PIVOT 函数,那么您将需要取消旋转两列AmountCount,首先:

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;

请参阅带有演示的 SQL Fiddle

于 2013-10-21T21:51:07.780 回答
0

您需要以两列计数和数量为中心:

select * from x PIVOT ( min(count) as count , sum(amount)for days in ('Day1', 'Day2'))

于 2013-10-23T09:15:33.323 回答