有没有办法从SQL查询中获取总数?

时间:2017-09-21 14:23:38

标签: sql sql-server

以下是我的查询:

SELECT CG.Id, CG.Name, CG.IsToggled, COUNT(*) AS TotalWordCount
FROM CategoryGroup AS CG
JOIN Category AS C ON CG.Id = C.GroupId
JOIN Phrase AS P ON C.Id = P.CategoryId
GROUP BY CG.Id
ORDER BY CG.Name

我需要做的是总计TotalWordCount列其中CG.IsToggled = 1

这可能在同一个查询中,或者我可以用两个查询来做到这一点。如果两个SQL语句确实提供了与所有TotalWordCount一起添加的相同值,那么它们就可以了。

2 个答案:

答案 0 :(得分:2)

您可以使用window function

解决此问题
SELECT CG.Id, CG.Name, CG.IsToggled, COUNT(*) AS TotalWordCount,
    COUNT(*) OVER (PARTITION BY CG.id) as TotalTotalWordCount
FROM CategoryGroup AS CG
JOIN Category AS C ON CG.Id = C.GroupId
JOIN Phrase AS P ON C.Id = P.CategoryId
GROUP BY CG.Id
ORDER BY CG.Name

假设这实际上是Microsoft SQL Server(这意味着发布的原始查询会出错,因为它在GROUP BY中没有CG.Name

答案 1 :(得分:1)

  

我需要做的是获得总计TotalWordCount列,其中CG.IsToggled = 1

您不能在同一查询中总计(总计聚合)。但是,您可以在这样的子查询中执行此操作:

SELECT CG.Id, CG.Name, CG.IsToggled, SUM(c2.TotalWordCount) AS TotalWordCount
FROM CategoryGroup AS CG
INNER JOIN
( 
   SELECT Id, Name, COUNT(*) AS TotalWordCount
   FROM CategoryGroup
   WHERE IsToggled = 1
   GROUP BY Id, Name
) AS c2 ON c2.Id = CG.Id AND c2.Name = CG.Name
JOIN Category AS C ON CG.Id = C.GroupId
JOIN Phrase AS P ON C.Id = P.CategoryId
GROUP BY CG.Id, CG.Name, CG.IsToggled
ORDER BY CG.Name

请注意:您可能需要使用LEFT JOIN在查询中包含IsToggled = 0的人:

SELECT CG.Id, CG.Name, CG.IsToggled, SUM(COALESCE(c2.TotalWordCount, 0)) AS TotalWordCount
FROM CategoryGroup AS CG
JOIN Category AS C ON CG.Id = C.GroupId
JOIN Phrase AS P ON C.Id = P.CategoryId
LEFT JOIN
( 
   SELECT Id, Name, COUNT(*) AS TotalWordCount
   FROM CategoryGroup
   WHERE IsToggled = 1
   GROUP BY Id, Name
) AS c2 ON c2.Id = CG.Id AND c2.Name = CG.Name
GROUP BY CG.Id, CG.Name, CG.IsToggled
ORDER BY CG.Name