0

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

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

我需要像这样旋转它

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

2 回答 2

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

如果您的值是已知的,那么您可以对它们进行硬编码,类似于上面的查询。但是如果您有未知数量的值,那么您可以使用动态 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

两个查询的结果是:

|  A |  B | TXT |
-----------------
| 22 | 34 | ddd |
|  0 | 24 | fff |
于 2013-01-17T17:27:34.303 回答
0

甲骨文查询:

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
于 2013-01-17T19:07:25.103 回答