将行值赋予列

时间:2015-02-25 11:07:05

标签: sql sql-server

我下面有这张表,

Branch     Item No    Month    Qty_Sold
  A          XX        JAN        5
  A          XX        FEB       13   
  A          YY        JAN       11
  A          YY        FEB       37
  B          XX        JAN        8
  B          XX        FEB       16
  B          XX        MAR        3
  B          YY        FEB       20
  B          YY        MAR       19
  B          ZZ        MAR       31

我希望它看起来像

Branch     Item No     JAN      FEB      MAR
  A          XX          5       13        -
  A          YY         11       37        -
  B          XX          8       16        3
  B          YY          -       20       19
  B          ZZ          -        -       31

我该怎么做......

任何想法?

感谢

2 个答案:

答案 0 :(得分:0)

您可以查看以下答案:Using PIVOT in SQL Server 2008

和这一个:MSSQL dynamic pivot column values to column header

从MSDN获取灵感:PIVOT

你可能会这样说:

-- Temporary table...
create table ##myTable (
        Branch      varchar(5)
        ,ItemNo     varchar(10)
        ,Mth        varchar(3)
        ,Qty_Sold   int
        )

-- ... with sample data
insert into ##myTable
        select  'A',          'XX',        'JAN',        5
union   select  'A',          'XX',        'FEB',       13   
union   select  'A',          'YY',        'JAN',       11
union   select  'A',          'YY',        'FEB',       37
union   select  'B',          'XX',        'JAN',        8
union   select  'B',          'XX',        'FEB',       16
union   select  'B',          'XX',        'MAR',        3
union   select  'B',          'YY',        'FEB',       20
union   select  'B',          'YY',        'MAR',       19
union   select  'B',          'ZZ',        'MAR',       31

-- So we have :
DECLARE @cols  AS NVARCHAR(MAX)
        ,@query AS NVARCHAR(MAX)

select @cols = STUFF((
                        SELECT  DISTINCT
                                ',' + QUOTENAME(Mth) 
                        FROM    ##myTable
                        FOR XML PATH(''), TYPE
                        ).value('.', 'NVARCHAR(MAX)') 
                    ,1,1,'')

set @query = '
    SELECT  Branch, ItemNo, ' + @cols + ' 
    FROM    (
              select Branch, ItemNo, Mth, Qty_Sold
              from ##myTable
            ) x
            pivot 
            (
                Sum(Qty_Sold)
                for Mth in (' + @cols + ')
            ) p'

execute sp_executesql @query

-- Remove temporary table
drop table ##myTable

答案 1 :(得分:0)

试试这个

DECLARE @Mytable TABLE(Branch char(1),ItemNo char(2),Month char(3),Qty_Sold int)

insert into @Mytable

values 
('A','XX','JAN','5'),
('A','XX','FEB','13'),
('A','YY','JAN','11'),
('A','YY','FEB','37'),
('B','XX','JAN','8'),
('B','XX','FEB','16'),
('B','XX','MAR','3'),
('B','YY','FEB','20'),
('B','YY','MAR','19'),
('B','ZZ','MAR','31')

SELECT *FROM @MYTABLE
PIVOT(MAX(QTY_SOLD) FOR MONTH IN ([JAN],[FEB],[MAR]))T
ORDER BY Branch