联合两个不同查询时出错

时间:2018-02-05 11:03:31

标签: sql sql-server-2008-r2

当我使用此查询时,如何在SQL Server 2008中组合两个查询:

SELECT DATE,
       SHIFT,
       QTY,
       JUDUL
FROM
(
    SELECT B.BASEREF AS PO,
           A.DOCDATE AS DATE,
           A.U_SOL_SHIFT AS SHIFT,
           SUM(B.QUANTITY) AS QTY,
           'FG' AS JUMLAH
    FROM OIGN A
         INNER JOIN IGN1 B ON A.DOCENTRY = B.DOCENTRY
         INNER JOIN OWOR C ON B.BASEREF = C.DOCNUM
    WHERE A.DOCDATE >= [%0]
          AND A.DOCDATE <= [%1]
          AND B.ITEMCODE = C.ITEMCODE
    GROUP BY A.DOCDATE,
             A.U_SOL_SHIFT,
             B.BASEREF
    UNION ALL
    SELECT B.BASEREF AS PO,
           A.DOCDATE AS DATE,
           A.U_SOL_SHIFT AS SHIFT,
           SUM(B.QUANTITY) AS QTY,
           'WASTE' AS JUMLAH
    FROM OIGN A
         INNER JOIN IGN1 B ON A.DOCENTRY = B.DOCENTRY
         INNER JOIN OWOR C ON B.BASEREF = C.DOCNUM
    WHERE A.DOCDATE >= [%0]
          AND A.DOCDATE <= [%1]
          AND B.ITEMCODE <> C.ITEMCODE
    GROUP BY A.DOCDATE,
             A.U_SOL_SHIFT,
             B.BASEREF
) B;

我收到如下错误消息:

1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Incorrect syntax near the keyword 'AND'. 
2). [Microsoft][SQL Server Native Client 10.0][SQL Server]Incorrect syntax near the keyword 'AND'.

1 个答案:

答案 0 :(得分:2)

考虑使用以下方法。它不是等效查询,但它将所有信息显示为原始信息。但是,不是在单独的行中显示数量,而是将它们显示在一行中。

SELECT  
    B.BASEREF AS PO,
    A.DOCDATE AS DATE,
    A.U_SOL_SHIFT AS SHIFT,
    SUM(case when B.ITEMCODE=C.ITEMCODE then B.QUANTITY end) AS FG_QTY,
    SUM(case when B.ITEMCODE!=C.ITEMCODE then B.QUANTITY end) AS WASTE_QTY,
FROM    
    OIGN A 
    INNER JOIN IGN1 B ON A.DOCENTRY=B.DOCENTRY
    INNER JOIN OWOR C ON B.BASEREF=C.DOCNUM
WHERE   
    A.DOCDATE>= [%0] AND A.DOCDATE<=[%1] 
GROUP BY    
    A.DOCDATE,
    A.U_SOL_SHIFT,
    B.BASEREF

[%0] [%1]似乎很奇怪。技术上它被解释为对名为%0%1的对象的引用,这可能不是您想要的。您的意思是使用某些值或变量吗?