SQL Server:如何在一个查询中组合不同的计数

时间:2014-09-01 17:41:08

标签: sql sql-server select count union-all

我想在一个查询中组合不同的Count语句,以便最终查询只返回每个Count的一个数字(总数)。

以下查询单独工作,但我找不到一种方法来组合它们而不重复相同的结果(嵌套表),并且不会丢失每个查询的单独名称(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 个答案:

答案 0 :(得分: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 all。很难说这是否适合你,因为我无法判断额外的空列是否会导致一些错误。