基于多列旋转数据

时间:2013-01-17 17:18:22

标签: sql sql-server tsql pivot

我想知道是否可以转动下表:

10  A  ddd
24  B  fff
34  B  ddd
12  A  ddd

我需要像这样转动它

A  B  text
-- -- ----
22 34 ddd
0  24 fff

2 个答案:

答案 0 :(得分:1)

您可以使用PIVOT功能:

select IsNull(A, 0) A, 
  IsNull(B, 0) B, 
  txt
from
(
  select num, let, txt
  from yourtable
) src
pivot
(
  sum(num)
  for let in (A, B)
) piv

请参阅SQL Fiddle with Demo

如果您的值已知,那么您可以对它们进行硬编码,类似于上面的查询。但是,如果您具有未知数量的值,则可以使用动态sql来创建查询字符串。您的动态SQL代码如下所示:

DECLARE @cols AS NVARCHAR(MAX),
    @colsNull AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Let) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsNull = STUFF((SELECT distinct ',IsNull(' + QUOTENAME(Let)+', 0) as '+QUOTENAME(Let) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @colsNull + ', txt from 
             (
                select num, let, txt
                from yourtable
            ) x
            pivot 
            (
                sum(num)
                for let in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo

两个查询的结果是:

|  A |  B | TXT |
-----------------
| 22 | 34 | ddd |
|  0 | 24 | fff |

答案 1 :(得分:0)

Oracle查询:

SELECT NVL(DECODE(area, 'A', total), 0) A
     , NVL(DECODE(area, 'B', total), 0) B
     , val
FROM
 (
  SELECT area, SUM(id) total, val
    FROM stack_test
  GROUP BY area, val
 )
 /
A   B   VAL
--  --  --
0   24  fff
22  0   ddd
0   34  ddd