2014-09-01 45 views
1

我想在一個查詢中合併不同的計數語句,以便最終查詢只返回每個計數的一個數字(總計)。SQL Server:如何在一個查詢中合併不同的計數

以下查詢單獨工作,但我無法找到一種方法來組合它們而不重複相同的結果(嵌套表),並且不會丟失每個單獨的名稱(Union All)。

有人能告訴我如何實現這一目標嗎?

我的SQL(剛剛合併更容易查看這裏):

(
    SELECT  COUNT(*) OVER() AS countB 
    FROM  MOC_Log2 B 
    WHERE  B.modBy = @modBy 
    AND   B.lastUpdate = 'Added' 
    FOR XML PATH(''), ELEMENTS, TYPE 
), 
(
    SELECT  COALESCE(SUM(D.vote), '0') AS countC 
    FROM  MOC_Log3 C 
    LEFT JOIN MOC_Log3_Votes D 
    ON   D.itemID = C.itemID 
    WHERE  C.modBy = @modBy 
    AND   C.lastUpdate = 'Added' 
    FOR XML PATH(''), ELEMENTS, TYPE 
), 
(
    SELECT  COALESCE(SUM(F.vote), '0') AS countE 
    FROM  MOC_Log4 E 
    LEFT JOIN MOC_Log4_Votes F 
    ON   F.itemID = E.itemID 
    WHERE  E.modBy = @modBy 
    AND   E.lastUpdate = 'Added' 
    FOR XML PATH(''), ELEMENTS, TYPE 
) 

與此的任何幫助,蒂姆非常感謝。

回答

1

只需添加空列?

SELECT  COUNT(*) OVER() AS countB, 
      Null AS countC, 
      Null AS countE 
FROM  MOC_Log2 B 
WHERE  B.modBy = @modBy 
AND   B.lastUpdate = 'Added' 
FOR XML PATH(''), ELEMENTS, TYPE 
Union 
SELECT  null, 
      COALESCE(SUM(D.vote), '0'), 
      null 
FROM  MOC_Log3 C 
LEFT JOIN MOC_Log3_Votes D 
ON   D.itemID = C.itemID 
WHERE  C.modBy = @modBy 
AND   C.lastUpdate = 'Added' 
FOR XML PATH(''), ELEMENTS, TYPE 
Union 
SELECT  null, 
      null, 
      COALESCE(SUM(F.vote), '0') 
FROM  MOC_Log4 E 
LEFT JOIN MOC_Log4_Votes F 
ON   F.itemID = E.itemID 
WHERE  E.modBy = @modBy 
AND   E.lastUpdate = 'Added' 
FOR XML PATH(''), ELEMENTS, TYPE 

另請注意我使用Union over Union。很難判斷這是否適用於您,因爲我無法確定額外的空列是否會導致一些錯誤。

+0

這很好 - 非常感謝有趣的解決方法! :) – user2571510 2014-09-01 19:10:41

相關問題