Write advanced SQL Select

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

Item table:

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


        
相关标签:
3条回答
  • 2020-12-18 13:55

    Let's hit this in two phases. First, although this is not the exact format you wanted, you can get the data you asked for as follows:

    Select item, ProdSched, max(qty)
      from Item1
     group by item,ProdSched
    

    Now, to get the data in the format you desired, one way of accomplishing it is a PIVOT table. You can cook up a pivot table in SQL Server as follows:

    Select item, [1] as ProdSched1, [2] as ProdSched2
    from ( Select Item, Qty, ProdSched
             from item1 ) x
    Pivot ( Max(qty) for ProdSched in ([1],[2]))  y
    
    0 讨论(0)
  • 2020-12-18 13:59
    SELECT Item, 
      [ProdSched(1)(Qnty)] = MAX(CASE WHEN ProdSched = 1 THEN Qnty END),
      [ProdSched(2)(Qnty)] = MAX(CASE WHEN ProdSched = 2 THEN Qnty END)
    FROM dbo.tablename
    GROUP BY Item
    ORDER BY Item;
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题