我有以下查询按保险类型显示计数。这是查询:
;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
返回的邮政编码数据示例如下:
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
我想将显示限制为仅超过10的邮政编码。
因此,将显示邮政编码19522
,因为有12个但另一个不会显示。
如果我添加having
子句,则不会显示19522 zip,因为其中一个保险类别中只有9个。我需要将每个邮政编码的所有保险类别加起来。
我该怎么做?
答案 0 :(得分:5)
您可以使用窗口函数,但这需要另一级子查询:
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;
答案 1 :(得分:1)
body {
margin: 0;
}