:选择sum()作为子查询的查询

时间:2015-09-29 13:10:25

标签: sql sql-server-2008

我有一个查询需要添加一列。我可以找到许多类似的例子,但没有什么能适合这种情况。可能存在无限的CategoryID,我需要添加按CategoryID分组的Sum(IsOutage)。这是一些示例数据:

enter image description here

这是我最接近工作的地方:

SELECT     c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
,(Select COUNT(h.IssueID) From dbo.hdIssues AS h Where h.CategoryID = i.CategoryID AND IsOutage = 1 ) AS TotalOutages

FROM         dbo.hdCategories AS c INNER JOIN
                  dbo.hdIssues AS i ON c.CategoryID = i.CategoryID
WHERE     (i.StatusID = 3)
GROUP BY c.CategoryID, c.Name, TotalOutages

我关门了吗?请提前告知和thanx

编辑:这是模拟结果的样子:

enter image description here

3 个答案:

答案 0 :(得分:1)

如果我正确理解您的需求,此查询应该为您提供所需的结果:

SELECT  x.* ,
        y.SumIsOutage

FROM    (SELECT c.CategoryID ,
                c.Name ,
                COUNT(i.IssueID) AS TotalIssues ,
                AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
        FROM    dbo.hdCategories AS c 
                INNER JOIN  dbo.hdIssues AS i ON c.CategoryID = i.CategoryID
        WHERE     (i.StatusID = 3)
        GROUP BY c.CategoryID, c.Name ) x
        LEFT JOIN   (SELECT DISTINCT i.CategoryId,
                    SUM(CONVERT(INT,i.isOutage)) OVER (PARTITION BY i.CategoryId) AS SumIsOutage
                    FROM dbo.hdIssues AS i ) y
        ON x.CategoryId = y.CategoryId

答案 1 :(得分:0)

您可以使用条件聚合。此外,您不应该group by totaloutages

SELECT    
c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
,sum(case when IsOutage = 1 then 1 else 0 end) AS TotalOutages
FROM dbo.hdCategories AS c INNER JOIN
dbo.hdIssues AS i ON c.CategoryID = i.CategoryID
WHERE i.StatusID = 3
GROUP BY c.CategoryID, c.Name

答案 2 :(得分:0)

此计数不需要其他子查询。只计算您感兴趣的行:

std::move

在查询的上下文中:

COUNT(CASE WHEN i.IsOutage = 1 THEN 1 END)