如何从SQL查询转置行和列

时间:2016-04-05 21:31:28

标签: sql dynamic transpose

如何从SQL查询转置行和列,如下所示。使用SQL Server 2012编写一个即使将数据添加到数据库表也可以工作的查询

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT * FROM t_TableName GROUP BY Month

答案 1 :(得分:0)

尝试

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE yourtable
    ( 
       [mon] varchar(3), [to] float, [aapl] float,
       [msft] float, [ko] float
    )
;

INSERT INTO yourtable
([mon],[to],[aapl],[msft],[ko])
VALUES
    ('jan', 12.25,112.25,56.52,45 ),
    ('feb', 12.52,125.25,56.87,46),
    ('mar', 12.65,126,56.94,47),
    ('apr', 12.95,127,56.99,45),
    ('may', 12.85,129,57.25,44)
;

查询1

select * from yourtable

<强> Results

| mon |    to |   aapl |  msft | ko |
|-----|-------|--------|-------|----|
| jan | 12.25 | 112.25 | 56.52 | 45 |
| feb | 12.52 | 125.25 | 56.87 | 46 |
| mar | 12.65 |    126 | 56.94 | 47 |
| apr | 12.95 |    127 | 56.99 | 45 |
| may | 12.85 |    129 | 57.25 | 44 |

查询2

select *
from
(
  select *
  from yourtable
  unpivot
  (
    value
    for month in ([to],[aapl],[msft],[ko])
  ) unpiv
) src
pivot
(
  max(value)
  for mon in (jan, feb, mar, apr, may)
) piv 

<强> Results

| month |    jan |    feb |   mar |   apr |   may |
|-------|--------|--------|-------|-------|-------|
|  aapl | 112.25 | 125.25 |   126 |   127 |   129 |
|    ko |     45 |     46 |    47 |    45 |    44 |
|  msft |  56.52 |  56.87 | 56.94 | 56.99 | 57.25 |
|    to |  12.25 |  12.52 | 12.65 | 12.95 | 12.85 |