使用SQL转动数据

Los*_*Lin 0 sql plsql pivot

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

Col1 Col2 Col3
1     a    w
2     a    x 
1     b    y
2     b    z 
Run Code Online (Sandbox Code Playgroud)

Col1 a b
1    w y
2    x z
Run Code Online (Sandbox Code Playgroud)

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

Tar*_*ryn 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
Run Code Online (Sandbox Code Playgroud)

请参阅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')
) 
Run Code Online (Sandbox Code Playgroud)

请参阅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'
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

都给出了结果:

| COL1 | 'A' | 'B' |
--------------------
|    1 |   w |   y |
|    2 |   x |   z |
Run Code Online (Sandbox Code Playgroud)