2

物品表:

|   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               |
4

3 回答 3

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

于 2012-09-20T01:49:23.107 回答
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;
于 2012-09-20T01:45:53.660 回答
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
于 2012-09-20T01:52:21.097 回答