使用SQL转动数据

时间:2013-01-28 20:44:57

标签: sql plsql pivot

我是SQL的新手,我想知道如何转动表格,如:

Col1 Col2 Col3
1     a    w
2     a    x 
1     b    y
2     b    z 

进入

Col1 a b
1    w y
2    x z

我正在玩GROUP BY,但我似乎无法将唯一的行转换为列

3 个答案:

答案 0 :(得分:5)

这可以使用具有CASE表达式的聚合函数来完成:

select col1,
  max(case when col2 = 'a' then col3 end) a,
  max(case when col2 = 'b' then col3 end) b
from yourtable
group by col1

请参阅SQL Fiddle with Demo

如果您使用的是具有PIVOT功能的RDBMS(SQL Server 2005+ / Oracle 11g +),那么您的查询将与此类似(注意:下面的Oracle语法):

select *
from
(
  select col1, col2, col3
  from yourtable
)
pivot
(
  max(col3)
  for col2 in ('a', 'b')
) 

请参阅SQL Fiddle with Demo

最后一种方法是在同一个表上使用多个连接:

select t1.col1, 
  t1.col3 a, 
  t2.col3 b
from yourtable t1
left join yourtable t2
  on t1.col1 = t2.col1
  and t2.col2 = 'b'
where t1.col2 = 'a'

请参阅SQL Fiddle with Demo

所有人都给出结果:

| COL1 | 'A' | 'B' |
--------------------
|    1 |   w |   y |
|    2 |   x |   z |

答案 1 :(得分:1)

如果您要求Col2中的不同值可以在不强制更改查询定义的情况下进行更改,那么您可能正在寻找OLAP之类的SQL Analysis Services结构。

答案 2 :(得分:0)

你应该尝试像

这样的东西
select * from
(select Col1, Col2, Col3 from TableName) 
pivot xml (max(Col3)
for Col2 in (any) )

我在手机上,所以我无法测试它是否正常工作。