编写高级SQL选择

时间:2012-09-20 01:42:19

标签: sql sql-server tsql pivot

项目表:

|   Item    |   Qnty    |   ProdSched   |
|    a      |    1      |       1       |
|    b      |    2      |       1       |
|    c      |    3      |       1       |
|    a      |    4      |       2       |
|    b      |    5      |       2       |
|    c      |    6      |       2       |

有没有办法可以使用SQL SELECT输出它?

|   Item    |   ProdSched(1)(Qnty)  |   ProdSched(2)(Qnty)  |
|    a      |           1           |       4               |
|    b      |           2           |       5               |
|    c      |           3           |       6               |

3 个答案:

答案 0 :(得分:11)

您可以使用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

请参阅SQL Fiddle with Demo

如果列数未知,则可以使用动态数据透视:

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)

请参阅SQL Fiddle with Demo

答案 1 :(得分:4)

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;

答案 2 :(得分:0)

让我们分两个阶段来解决这个问题。首先,虽然这不是您想要的确切格式,但您可以按如下方式获取所要求的数据:

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

现在,要以您想要的格式获取数据,实现它的一种方法是PIVOT表。您可以按如下方式在SQL Server中制作数据透视表:

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