gpt4 book ai didi

sql - 加入两个子查询或一个查询与一个子查询 SQL Server 2008

转载 作者:行者123 更新时间:2023-12-04 22:36:52 25 4
gpt4 key购买 nike

怪物编辑:查询现在将运行但返回不正确的答案。添加了一个粗略的架构。 PatientID 不是 tblPatientVisits 表中的主键,因为相同的患者 ID 可以出现多次。

列出了每个县名,但每个 count(s.countyName) 和 count(t.countyname) 都为 1

PatientVisits   
PatientID int
PatientState varchar(2)
patientCounty varchar(3)
visitNumber int - PK

tblStateCounties
CPK stateCode varchar(2)
CPK countyCode varchar(3)
countyName varchar(25)


SELECT t.countyName,
count(t.countyName) as reAdmits ,count(s.countyName) as totalVisits
FROM (
SELECT countyName,count(countyName) AS readmitCounts
FROM (
SELECT tblPatient.patientID
,tblStateCounties.countyName
FROM tblPatient
INNER JOIN tblPatientVisits
ON tblPatient.patientID = tblPatientVisits.patientID
INNER JOIN tblStateCounties
ON tblPatientVisits.patientState = tblStateCounties.stateCode
AND tblPatientVisits.patientCounty = tblStateCounties.countyCode
GROUP BY tblPatient.patientID
,tblStateCounties.stateCode
,tblStateCounties.countyName
HAVING (COUNT(tblPatient.patientID) > 1)
AND (tblStateCounties.stateCode = '21')
) t
GROUP BY countyname
) t
INNER JOIN (
SELECT countyName
FROM (
SELECT tblStateCounties.countyName
,COUNT(tblStateCounties.countyName) AS counts
FROM tblPatient
INNER JOIN tblPatientVisits
ON tblPatient.patientID = tblPatientVisits.patientID
INNER JOIN tblStateCounties
ON tblPatientVisits.patientState = tblStateCounties.stateCode
AND tblPatientVisits.patientCounty = tblStateCounties.countyCode
WHERE (tblStateCounties.stateCode = '21')
GROUP BY tblStateCounties.countyName
) z
) s
ON s.countyName = t.countyName
group by s.countyname, t.countyname

编辑:我有一个现在运行的查询,但它返回

最佳答案

没有样本数据和想要的结果很难说,但也许这就是你所追求的?

;WITH x AS 
(
SELECT c.CountyName, v.patientCounty, v.patientState, p.patientID
FROM dbo.tblPatient AS p
INNER JOIN dbo.tblPatientVisits AS v
ON p.patientID = v.patientID
INNER JOIN dbo.tblStateCounties AS c
ON v.patientState = c.stateCode
AND v.patientCounty = c.countyCode
WHERE c.stateCode = '21'
),
y AS (SELECT CountyName, c = COUNT(*) FROM x GROUP BY CountyName),
z AS (SELECT CountyName, c = COUNT(PatientID) FROM x
GROUP BY CountyName, patientState, PatientID HAVING COUNT(*)>1)
SELECT y.countyName, reAdmits = MAX(COALESCE(z.c, 0)), totalVisits = MAX(y.c)
FROM y LEFT OUTER JOIN z
ON y.CountyName = z.CountyName
GROUP BY y.CountyName;

关于sql - 加入两个子查询或一个查询与一个子查询 SQL Server 2008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com