如何在查询mssql

时间:2017-03-06 06:54:48

标签: sql sql-server

SELECT 
     PO.ITEM_NO,
     PO_NO,
     PO.DESCRIPT,
     PO.REM1,
     QTY 
FROM PODSCRP PO ,PRODUCT P 
WHERE P.ITEM_NO=PO.ITEM_NO AND PO.PO_NO ='PO170010'

query result

我想得到结果:

if REM1=1 this will FOC1_QTY,
  REM1=2 FOC2_QTY,
  REM1=NULL is SALE_QTY
  and if not include REM1 VALUE 1 or 2, There is not FOC value so FOC1_QTY and FOC2_QTY must be 0.

我想提取下面的表格。

ITEM_NO  FOC1_QTY FOC2_QTY  SALE_QTY 
P00001   10       100           100
P00002   0        0             100
P00004   0        0             100

如何对上表进行sql查询..

1 个答案:

答案 0 :(得分:1)

试试这个,

DECLARE @T TABLE(ITEM_NO VARCHAR(10),REM1 INT,QTY INT)
INSERT INTO @T VALUES ('P00001',NULL,100),
                      ('P00001',1,10),
                      ('P00001',2,100)

SELECT  ITEM_NO
        ,[1] FOC1_QTY
        ,[2] FOC2_QTY
        ,[0] SALE_QTY
FROM    (
        SELECT ITEM_NO,ISNULL(REM1,0)REM1,QTY FROM @T
        )A
PIVOT(
     MAX(QTY) FOR REM1 IN([1],[2],[0] ) 
     )PVT