Glo*_*tin 1 sql-server having-clause
我有以下查询按保险类型显示计数.这是查询:
;WITH CTE
AS
(
SELECT DISTINCT ROW_NUMBER() OVER (Partition by PatInfo.PatientProfileID Order By E.Visit desc) AS RowNumber,
PatInfo.PatientProfileID, E.Visit, PatInfo.Zip, E.CarrierTypeDesc, E.FinancialClassDescription, IG.UDSInsuranceGroupName,IG.UDSInsuranceID
FROM Encounter E JOIN CHCEncounterType ET ON E.CHCEncounterTypeID = ET.CHCEncounterTypeID
JOIN PatientInfo PatInfo ON PatInfo.PatientProfileID = E.PatientProfileID
LEFT JOIN dbo.UDSInsuranceMapping ON ISNULL(dbo.UDSInsuranceMapping.InsuranceName,'') = ISNULL(E.FinancialClassDescription,'')
LEFT JOIN dbo.UDSInsuranceGroups IG ON IG.UDSInsuranceID = dbo.UDSInsuranceMapping.UDSInsuranceID
WHERE E.EncounterCounted = 1
)
SELECT Zip AS ZipCode,
Count(PatientProfileID) as Total, UDSInsuranceGroupName, UDSInsuranceID
from CTE
where RowNumber = 1 AND ZIP IS NOT NULL
group by Zip, UDSInsuranceGroupName, UDSInsuranceID
Run Code Online (Sandbox Code Playgroud)
返回的邮政编码数据示例如下:
Zip Code Total InsuranceGroup InsuranceID
19522 9 Medicaid/CHIP/Other/Public 2
19522 1 Medicare 3
19522 1 None/Uninsured 1
19522 1 Private 4
19512 2 Medicaid/CHIP/Other/Public 2
19512 1 None/Uninsured 1
19518 1 Medicaid/CHIP/Other/Public 2
19518 1 Medicare 3
Run Code Online (Sandbox Code Playgroud)
我想将显示限制为仅包含总数超过10的邮政编码.因此,19522将显示邮政编码,因为有12个,但另一个不会显示.如果我添加一个having条款,则不会显示19522 zip,因为其中一个保险类别中只有9个.我需要将每个邮政编码的所有保险类别加起来.
我怎样才能做到这一点?
您可以使用窗口函数,但这需要另一级子查询:
with . ..
select *
from (select Zip AS ZipCode,
Count(*) as Total, UDSInsuranceGroupName,
UDSInsuranceID,
sum(count(*)) over (partition by zip) as zipTotal
from CTE
where RowNumber = 1 AND ZIP IS NOT NULL
group by Zip, UDSInsuranceGroupName, UDSInsuranceID
) z
where zipTotal > 10;
Run Code Online (Sandbox Code Playgroud)