0

我的桌子看起来像这样

Year  S.Person Orange Mango 
2001   BOB       10    12    
2001   JOY       1     25    
2001   KENT      2      5     
2002   BOB       6      3     
2002   JOY       4      7     
2002   KENT      5      4     

我的要求是产生这样的输出:

Year   BOB-Orange BOB-MANGO  JOY-ORANGE JOY-MANGO KENT-ORANGE KENT-MANGO
2001    10         12         1          25        2           5
2002    6           3          4         7         5           4

注意 S.Person 是动态的和橙色的,芒果是固定的

4

1 回答 1

0

由于您想动态执行此操作,请尝试以下操作:

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

WITH Unpivoted
AS
(
  SELECT 
  Year, 
  SPerson + '-' + ITem AS SPersonItem, 
  value
  FROM
  (
    SELECT * FROM Table1
  ) AS t
  UNPIVOT 
  (
    Value FOR ITem IN(Orange, Mango)
  ) AS u
)
select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(SPersonItem)
                      FROM Unpivoted
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');

SELECT @query = 
  'WITH Unpivoted 
   AS  
   ( 
      SELECT 
        Year, 
        SPerson + ''-'' + ITem AS SPersonItem, 
        value 
      FROM ( SELECT * FROM Table1  ) AS t 
      UNPIVOT 
      ( 
        Value FOR ITem IN( Orange, Mango) 
       ) AS u  
    ) 
    SELECT *  FROM Unpivoted AS u 
    PIVOT 
    ( 
      SUM(value) 
      FOR SPersonItem IN ( ' + @cols + ' ) 
     ) AS p ';

 execute(@query);

SQL 小提琴演示

这会给你:

| YEAR | BOB-MANGO | BOB-ORANGE | JOY-MANGO | JOY-ORANGE | KENT-MANGO | KENT-ORANGE |
-------------------------------------------------------------------------------------
| 2001 |        12 |         10 |        25 |          1 |          5 |           2 |
| 2002 |         3 |          6 |         7 |          4 |          4 |           5 |
于 2013-02-10T11:16:34.600 回答