2016-01-26 38 views
0

我有2個表所示:SQL服務器機箱 - 當 - ELSE

  • CTNumberCtIDDateCTIE
  • VTNumberVtIDQuantities

而我的代碼:

SELECT 
    MAX(CT.Date), MAX(CT.CtID), VT.VtID, 
    SUM(VT.Quantities) AS SumVT, 
    CASE 
     WHEN CT.CTIE = 0 THEN SUM(VT.Quantities) 
     ELSE 0 
    END AS IMPORT, 
    CASE 
     WHEN CT.CTIE = 1 THEN SUM(VT.Quantities) 
     ELSE 0 
    END AS EXPORT 
FROM 
    CT 
INNER JOIN 
    VT ON CT.Number = VT.Number 
GROUP BY 
    VT.VtID, CT.CTIE 
ORDER BY 
    VT.VtID 

此代碼工作正常,但結果不是我想要的。對於某些VtID同時具有CTIE = 1CTIE = 1,SQL現在返回與相同VtID 2個獨立的行,一個用於CTIE = 0,一個用於CTIE = 1。但我需要它爲每個VtID只顯示1行,而不是2

回答

0

在組中刪除CT.CTIE,把你的case語句的聚合函數

SElECT 
    MAX(CT.Date), MAX(CT.CtID), VT.VtID, SUM(VT.Quantities) AS SumVT, 
    SUM(CASE WHEN CT.CTIE = 0 THEN VT.Quantities ELSE 0 END) AS IMPORT, 
    SUM(CASE WHEN CT.CTIE = 1 THEN VT.Quantities ELSE 0 END) AS EXPORT 
FROM CT INNER JOIN VT ON CT.Number=VT.Number 
GROUP BY VT.VtID 
ORDER by VT.VtID 
+0

哇感謝你的幫助內。順便說一句,我有這個代碼的另一個版本,如果有人想了解:d '選擇Temp.VTID,SUM(Temp.Import)進口, \t SUM(Temp.Export)由於出口 \t FROM(SELECT VTID,數量, CASE WHEN CT.CTIE = 0 THEN數量ELSE 0 END AS導入, CASE WHEN CT.CTIE = 1 THEN數量ELSE 0 END AS導出 從VT INNER JOIN CT ON CT.Number = VT。數字)AS溫度 \t GROUP BY Temp.VTID.' –