2014-03-27 73 views
0

我有以下查询作为存储过程的一部分。它返回关于一个国家的一些指标以及我们在每个国家/地区有多少个位置。这个查询工作正常。根据子查询结果筛选器查询

但是,这会返回所有国家/地区的数据,包括那些没有位置的国家/地区。我想修改它,以便它只返回CenterCount> 0的记录,但CenterCount只是子查询结果的别名,所以我不能只放WHERE CenterCount > 0

我知道我可以通过复制WHEREHAVING子句中的该子查询来完成此操作,但我不希望在那里有两次子查询。有没有更好的方法来做到这一点?

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

创建一个'变量'并存储'CenterCount'的结果并使用该变量! –

+0

将子查询移动到主查询的一部分。这样你就可以使用SQL的全部功能,而不会重复整个事情。 – Odi

回答

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 
+0

很好的回答!这将解决问题。当然,这是SQL Server的具体内容,但对我来说没问题。 – Jim