简体   繁体   中英

Pivoting Data in SQL

What is proper syntax to convert from Table Table2Dimension to Table DesiredTable in MSSQL?

样表

Since you are using SQL Server you can get the result by using the PIVOT function:

select [row], [1], [2], [3]
from
(
  select [row], col, value
  from Table2Dimension
) d
pivot
(
  max(value)
  for col in ([1], [2], [3])
) piv;

See SQL Fiddle with Demo . This gives the result:

| ROW | 1 | 2 | 3 |
|-----|---|---|---|
|   1 | 1 | 2 | 3 |
|   2 | 4 | 5 | 6 |
|   3 | 7 | 8 | 9 |
select row,
       sum(case when col = 1 then value end) as [1],
       sum(case when col = 2 then value end) as [2],
       sum(case when col = 3 then value end) as [3]
from your_table
group by row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM