0

这是实际的表。

Month   RCount  Cond_Id Cond_desc
Jan-13  52  -1  N/A
Jan-13  194 0   NORMAL
Jan-13  86  2   ABNORMAL
Feb-13  54  -1  N/A
Feb-13  158 0   NORMAL
Feb-13  110 2   ABNORMAL
Mar-13  14  -1  N/A
Mar-13  113 0   NORMAL
Mar-13  90  2   ABNORMAL
Apr-13  3   -1  N/A
Apr-13  259 0   NORMAL
Apr-13  144 2   ABNORMAL
May-13  10  -1  N/A
May-13  693 0   NORMAL
May-13  305 2   ABNORMAL
May-13  1   4   CRITICAL
Jun-13  169 0   NORMAL
Jun-13  36  2   ABNORMAL
Jun-13  1   4   CRITICAL

我需要以下结果。

R_id    Cond_Id Cond_desc   Jan-13  Feb-13  Mar-13  Apr-13  May-13  Jun-13
1   -1  N/A         51  54  14  3   10  169
2   0   NORMAL          194 158 113 259 693 36
3   2   ABNORMAL    86  110 90  144 305 1
4   0   CRITICAL    0   0   0   0   1   0
4

1 回答 1

0

假设你不会这样:

  • rcount 对按 分组的值求和month
  • 您的示例中的值COND_ID是错误的,例如对于CRITICAL的情况,值应该是4
  • 字段R_ID(行号)只是查询的计数。

以下查询可能会有用:

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

select @cols = STUFF((SELECT ',' + QUOTENAME([MONTH]) 
                    from MYTABLE
                    group by [MONTH]
                    order by [MONTH]
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ROW_NUMBER() over (order by COND_ID) AS R_ID,COND_ID,COND_DESC,' + @cols + ' 
            from 
            (
              SELECT 
                 COND_ID, 
                 COND_DESC,
                 rcount,
                 MONTH 
              FROM MYTABLE
            ) x
            pivot 
            (
                sum(rcount)
                for [MONTH] in (' + @cols + ')
            ) p '

execute sp_executesql @query;

在这里你试试这个sql fiddle。我从 bluefeet 的链接创建的这个查询。

于 2013-08-10T16:47:58.623 回答