Search code examples
sqlsql-serversubquerycorrelated-subquery

SQL Nested or Correlated Query


I am trying to calculate the number of servers I have against a subquery count that same number of servers with a specific variable. I can return my total count of assets for an entity but when I return my total count of assets that meet the criteria it gives me the total count not the count for my specific business.

SELECT DATEPART(week, GETDATE()) AS WEEK, bt.TranslatedParentBusiness AS [Parent Business], count(cars.ServerID) as [Count of Servers], 

(Select count(auth.serverID) from AuthTracking auth where [AUTH STATUS] like 'PASSED')
FROM     ASSETS.dbo._CARS AS cars INNER JOIN
              ASSETS.dbo.BU_Translation AS bt ON cars.CARS_SubBusiness = bt.[CARS Sub Business]

GROUP BY bt.TranslatedParentBusiness    

Solution

  • SELECT
        DATEPART(week, GETDATE()) AS WEEK,
        bt.TranslatedParentBusiness AS [Parent Business],
        count(cars.ServerID) as [Count of Servers], 
        count(CASE WHEN [AUTH STATUS] = 'PASSED' THEN auth.serverID END)
    FROM     ASSETS.dbo._CARS AS cars INNER JOIN
                  ASSETS.dbo.BU_Translation AS bt ON cars.CARS_SubBusiness = bt.[CARS Sub Business]
    GROUP BY bt.TranslatedParentBusiness