在单行中获取不同的列值

时间:2012-10-29 12:36:00

标签: sql oracle oracle10g pivot unpivot

这是数据:

id    name     period      data1    data2
===================================================
111   name1    monthly     aaaaa    bbbbb
111   name1    quaterly    ccccc    ddddd
111   name1    halfYearly  eeeee    fffff
111   name1    annually    ggggg    hhhhh

我想查询哪一个获取数据,如

id    name     monthlYdata1    monthlYdata2      quaterlydata1    quaterlydata2      halfYearlydata1    halfYearlydata2      annuallydata1    annuallydata2
==========================================================================================================================================================
111   name1    aaaaa           bbbbb             ccccc            ddddd              eeeee              fffff                ggggg            hhhhh

4 个答案:

答案 0 :(得分:7)

您没有指定您正在使用的RDBMS,但这将适用于所有这些:

select id,
  name,
  max(case when period = 'monthly' then data1 end) as MonthlyData1,
  max(case when period = 'monthly' then data2 end) as MonthlyData2,
  max(case when period = 'quaterly' then data1 end) as quarterlyData1,
  max(case when period = 'quaterly' then data2 end) as quarterlyData2,
  max(case when period = 'halfYearly' then data1 end) as halfYearlyData1,
  max(case when period = 'halfYearly' then data2 end) as halfYearlyData2,
  max(case when period = 'annually' then data1 end) as annuallyData1,
  max(case when period = 'annually' then data2 end) as annuallyData2
from yourtable
group by id, name

请参阅SQL Fiddle with Demo

如果您使用的是具有PIVOT功能的RDBMS,则可以执行以下操作,同时使用UNPIVOTPIVOT来生成结果。正如Andriy M指出UNPIVOT假设data1data2的数据类型是相同的类型,如果没有,那么转换需要发生在{{1}数据:

Oracle 11g:

UNPIVOT

请参阅SQL Fiddle with Demo

SQL Server:

select *
from
(
  select id, name, value, 
    period||data new_col
  from yourtable
  unpivot
  (
    value for data in (data1, data2)
  ) u
) x
pivot
(
  max(value)
  for new_col in ('monthlyDATA1', 'monthlyDATA2',
                  'quaterlyDATA1', 'quaterlyDATA2',
                  'halfYearlyDATA1', 'halfYearlyDATA2',
                  'annuallyDATA1', 'annuallyDATA2')
) p

答案 1 :(得分:0)

从查询本身获取数据。

从query1获取id和名称,并使用从query1获取的id

将该查询与月度,季度和年度数据连接起来

答案 2 :(得分:0)

答案 3 :(得分:0)

首先,您应该将所有不同的id检索到时态表中。

Select DISTINCT id
into #tmpIds
from Table

然后创建一个包含所需列的时态表(idnamemonthlYdata1monthlYdata2quaterlydata1quaterlydata2halfYearlydata1halfYearlydata2annuallydata1annuallydata2),并循环显示您的第一个临时表格以获取ID。

对于您应该执行的每个ID:

Insert into #tmpTable
   @id,
   '',
  (Select data1 from Table where id=@id and period='monthly') as monthlyData1
  ...

这是我想到的第一个解决方案。