我创建了2个临时表#ClientsCountForDoctor
和#DeathCount
:
CREATE TABLE #ClientsCountForDoctor (DoctorCode int, Clients int)
SELECT
Personal.[DoctorCode], Count(Clients.[ClientCode]) AS [Count-Код клиента]
FROM
Personal
INNER JOIN
(Clients INNER JOIN MedicalCard ON Clients.[ClientCode] = MedicalCard.[ClientCode]) ON Personal.[DoctorCode] = MedicalCard.[DoctorCode]
GROUP BY
Personal.[DoctorCode];
INSERT INTO #ClientsCountForDoctor
EXEC nothing
CREATE TABLE #DeathCount (DoctorCode int, Deaths int)
SELECT
Personal.[DoctorCode], Count(Clients.[ClientCode]) AS [Count-Код клиента]
FROM
Personal
INNER JOIN
(Clients INNER JOIN MedicalCard ON Clients.[ClientCode] = MedicalCard.[ClientCode]) ON Personal.[DoctorCode] = MedicalCard.[DoctorCode]
GROUP BY
Personal.[DoctorCode], MedicalCard.[TreatmentResult]
HAVING
(((MedicalCard.[TreatmentResult])='Смерть'));
INSERT INTO #DeathCount
EXEC nothing
然后我想用结果。我该怎么做?
SELECT
Personal.[DoctorName],
#DeathCount.Deaths/#ClientsCountForDoctor.Clients AS [DeathPercent]
FROM
(#ClientsCountForDoctor INNER JOIN Personal ON #ClientsCountForDoctor.[DoctorCode] = Personal.[DoctorCode])
INNER JOIN
#DeathCount ON Personal.[DoctorCode] = #DeathCount.[DoctorCode];
答案 0 :(得分:2)
我认为您需要的是Select Into
语法。 It will create the table for you with the selected data inserted at the same time
。然后从上一个查询中使用创建的表进行正常选择
<强>实施例强>
SELECT col1,col2,..
INTO #temp --Note: this temporary table will be created in the db
FROM yourTable
您的疑问
SELECT Personal.[DoctorCode],
Count(Clients.[ClientCode]) AS [Count-Код клиента]
INTO #ClientsCountForDoctor --NOTE
FROM Personal INNER JOIN
(Clients INNER JOIN MedicalCard ON Clients.[ClientCode] = MedicalCard.[ClientCode])
ON Personal.[DoctorCode] = MedicalCard.[DoctorCode]
GROUP BY Personal.[DoctorCode];
SELECT Personal.[DoctorCode],
Count(Clients.[ClientCode]) AS [Count-Код клиента]
#DeathCount --NOTE
FROM Personal INNER JOIN
(Clients INNER JOIN MedicalCard ON Clients.[ClientCode] = MedicalCard.[ClientCode])
ON Personal.[DoctorCode] = MedicalCard.[DoctorCode]
GROUP BY Personal.[DoctorCode], MedicalCard.[TreatmentResult]
HAVING (((MedicalCard.[TreatmentResult])='Смерть'));
SELECT p.[DoctorName], d.Deaths/c.Clients AS [DeathPercent]
FROM #ClientsCountForDoctor c INNER JOIN Personal p
ON c.[DoctorCode] = p.[DoctorCode]
INNER JOIN #DeathCount d
ON p.[DoctorCode] = d.[DoctorCode];