简体   繁体   中英

: Select query with sum() as subquery

I have a query that I need to add a column to. I can find many similar examples but nothing quite works right for this situation. There could be infinite CategoryIDs and I need to add the Sum(IsOutage) grouped by CategoryID. This is some sample data:

在此处输入图片说明

and here is the closest I have to getting it to work:

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

Am I close? Please advise and thanx in advance

EDIT : This is a mock up of what the result should look like:

在此处输入图片说明

If i correctly understand your needs this query should give you desired result:

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

You can use conditional aggregation. Also, you shouldn't 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

You don't need another subquery for this count. Just count the rows that you're interested in:

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

In the context of your query:

SELECT     
  c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
, COUNT(CASE WHEN CONVERT(INT, i.IsOutage) = 1 THEN 1 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM