枢轴不工作

时间:2014-03-13 15:49:30

标签: sql-server

这是我的输入数据:

model                            status_description Number
NULL                               ASSIGNED           1
CABLE CARD                         ASSIGNED           56
DCT1000                            ASSIGNED           1130
DCT1200                            ASSIGNED           134
DCT2000 Digital                    ASSIGNED           21401
DCT700 Digital                     ASSIGNED           22214
DCX3400 HD Digital Rec.            ASSIGNED           1183
DCX700 HD Digital              ASSIGNED           1086
CABLE CARD                     CHARGE/DISCONNECT      2
DCT1000                            CHARGE/DISCONNECT      43

继续使用相同的模型,最终获得9个状态。

我想以这样的方式呈现数据......左边的模型和顶部的9个状态,每个数字都有数字。我的查询以正确的格式显示数据,但所有计数都是NULL。我的查询在下面。有什么想法为什么?

Model         ASSIGNED  CHARGE/DISCONNECT DELETED HOLD  OFF ISLAND OUT OF CIRCULATION   
5 Port eMTA     NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
6381-DSL Modem  NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

透视SQL:

select Model, 'ASSIGNED' = [1], 'CHARGE/DISCONNECT' = [2], 'DELETED' = [3], 'HOLD' = [4], 'OFF ISLAND' = [5], 'OUT OF CIRCULATION' = [6], 
'PENDING' = [7], 'RETURNED/REJECTED BY CUSTOMER' = [8], 'UNASSIGNED' = [9]
from (select model, status_description, number from jed_convert_031314) as PivotInput
PIVOT
(SUM(number)
for status_description in ([1],[2],[3],[4],[5],[6],[7],[8],[9])) as PivotOutput

谢谢!

1 个答案:

答案 0 :(得分:0)

在你的情况下,我会选择动态SQL语句:

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

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

set @query = 'SELECT Model,' + @cols + '
             from 
             (
                SELECT *
                from jed_convert_031314
            ) x
            pivot 
            (
                SUM(Number)
                for status_description in (' + @cols + ')
            ) p '

execute(@query)

SQL Fiddle