我将以下查询作为存储过程的一部分。它返回一些国家的指标以及我们在每个国家/地区的位置。此查询工作正常。
但是,这将返回所有国家/地区的数据,包括我们没有位置的国家/地区。我想修改它,以便它只返回CenterCount>的记录。 0,但CenterCount只是子查询结果的别名,所以我不能只放WHERE CenterCount > 0
。
我知道我可以通过在WHERE
或HAVING
子句中复制子查询来做到这一点,但我不想在那里有两次子查询。有没有更好的方法呢?
SELECT
cn.Code as CountryCode,
cn.CountryName,
(
SELECT COUNT(DISTINCT(CenterID))
FROM Center.Center center
JOIN Organization.OrganizationAddress orgAddr
ON center.OrganizationID = orgAddr.OrganizationID
JOIN Common.Address ca
ON orgAddr.AddressID = ca.AddressID
AND ca.AddressTypeID = 1 --Physical
WHERE ca.CountryID = cn.CountryID
AND center.ActiveInd = 1
AND ( (center.CenterStatusTypeID = 1) OR (center.CenterStatusTypeID = 2 AND center.OpenUTCDate <= DATEADD(DAY, 14, GETUTCDATE())) )
AND ca.ActiveInd = 1
) as CenterCount,
(
SELECT COUNT(DISTINCT(SatelliteID))
FROM Center.Satellite sat
JOIN Common.Address ca
ON sat.AddressID = ca.AddressID
WHERE ca.CountryID = cn.CountryID
AND sat.ActiveInd = 1
AND sat.StatusTypeID = 2 --Approved
AND sat.PayerTypeID = 2 --Retail
AND sat.WebsitePresenceFlag = 1
AND sat.OpenUTCDate <= DATEADD(DAY, 14, GETUTCDATE())
) as SatelliteCount
FROM Core.Country cn
WHERE (@Country IS NULL OR cn.CountryID = @CountryID)
ORDER BY 1
答案 0 :(得分:1)
一种简单的方法就是将原始查询转换为公用表表达式,这样就可以让您按照自己的意愿使用WHERE CenterCount > 0
。
;WITH cte AS
(
SELECT
cn.Code as CountryCode,
cn.CountryName,
(
SELECT COUNT(DISTINCT(CenterID))
FROM Center.Center center
JOIN Organization.OrganizationAddress orgAddr
ON center.OrganizationID = orgAddr.OrganizationID
JOIN Common.Address ca
ON orgAddr.AddressID = ca.AddressID
AND ca.AddressTypeID = 1 --Physical
WHERE ca.CountryID = cn.CountryID
AND center.ActiveInd = 1
AND ( (center.CenterStatusTypeID = 1) OR (center.CenterStatusTypeID = 2 AND center.OpenUTCDate <= DATEADD(DAY, 14, GETUTCDATE())) )
AND ca.ActiveInd = 1
) as CenterCount,
(
SELECT COUNT(DISTINCT(SatelliteID))
FROM Center.Satellite sat
JOIN Common.Address ca
ON sat.AddressID = ca.AddressID
WHERE ca.CountryID = cn.CountryID
AND sat.ActiveInd = 1
AND sat.StatusTypeID = 2 --Approved
AND sat.PayerTypeID = 2 --Retail
AND sat.WebsitePresenceFlag = 1
AND sat.OpenUTCDate <= DATEADD(DAY, 14, GETUTCDATE())
) as SatelliteCount
FROM Core.Country cn
WHERE (@Country IS NULL OR cn.CountryID = @CountryID)
)
SELECT *
FROM cte
WHERE CenterCount > 0
ORDER BY 1