使用PIVOT IN SQL计算计数

时间:2016-10-12 10:33:15

标签: sql sql-server

我正在尝试使用pivot来计算库存和无库存的数量。这可能与SQL Server 2008一起使用吗?

表:

DECLARE @MYTABLE TABLE
(
    ID INT, 
    PRODUCT VARCHAR (35),
    SKU INT,
    NEWPRICE DECIMAL(10,5),
    OLDPRICEEX DECIMAL(10,5),
    REMARKS VARCHAR (35)
)

INSERT @MYTABLE
    SELECT 438, 'RESISTOR', 43822,  12.66,  11.13,  'STOCK' UNION ALL
    SELECT 438, 'RESISTOR', 43870,  11.99,  12.30,  'OUTS-STOCK' UNION ALL
    SELECT 719, 'INDUCTOR', 71911,  666.66, 764.16, 'OUTS-STOCK' UNION ALL
    SELECT 101, 'CAPACITOR',10159,  22.66,  19.12,  'STOCK' UNION ALL
    SELECT 101, 'CAPACITOR',10159,  19.32,  18.19,  'STOCK'

预期输出

ID  | PRODUCT   | STOCK | OUT-STOCK
----+-----------+-------+----------
438 | RESISTOR  |   1   |     1
719 | INDUCTOR  |   0   |     1
101 | CAPACITOR |   2   |     0

由于

2 个答案:

答案 0 :(得分:1)

不需要Pivot。使用以下查询。

 SELECT ID,Product, SUM(case when REMARKS ='STOCK' then 1 else 0 end) as STOCK,
            SUM(case when REMARKS ='OUTS-STOCK' then 1 else 0 end) as [OUT-STOCK]
 FROM @MYTABLE
 GROUP BY ID,Product

答案 1 :(得分:1)

使用PIVOT:

Select * from
(Select ID As ForCnt, ID, PRODUCT, REMARKS  from @MYTABLE) a
PIVOT
(
COUNT(ForCnt) FOR REMARKS IN ([STOCK], [OUTS-STOCK])
) x