2016-10-12 93 views
0

我正在嘗試使用數據透視表來計算庫存和無庫存的數量。這可能與SQL Server 2008?使用PIVOT IN SQL進行計算計算

表:

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 

感謝

回答

1

無需透視的。使用以下查詢。

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

使用PIVOT:

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