Write advanced SQL Select

前端 未结 3 1364
春和景丽
春和景丽 2020-12-18 13:07

Item table:

|   Item    |   Qnty    |   ProdSched   |
|    a      |    1      |       1       |
|    b      |    2      |       1       |
|    c      |    3          


        
3条回答
  •  独厮守ぢ
    2020-12-18 14:10

    You can use PIVOT for this. If you have a known number of values to transform, then you can hard-code the values via a static pivot:

    select item, [1] as ProdSched_1, [2] as ProdSched_2
    from 
    (
      select item, qty, prodsched
      from yourtable
    ) x
    pivot
    (
      max(qty)
      for prodsched in ([1], [2])
    ) p
    

    see SQL Fiddle with Demo

    If the number of columns is unknown, then you can use a dynamic pivot:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(prodsched) 
                        from yourtable
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT item,' + @cols + ' from 
                 (
                  select item, qty, prodsched
                  from yourtable
                ) x
                pivot 
                (
                    max(qty)
                    for prodsched in (' + @cols + ')
                ) p '
    
    execute(@query)
    

    see SQL Fiddle with Demo

提交回复
热议问题