我有类似于以下情况的东西,可能不是最好的例子,但有点类似于我的真实情况。假设我有4张桌子,由于某些情况我无法改变。
CREATE TABLE [Hospital] (
[HospitalID] INT IDENTITY NOT NULL,
[HospitalName] VARCHAR(MAX) NOT NULL
);
CREATE TABLE [Doctors] (
[DoctorID] INT IDENTITY NOT NULL ,
[HospitalID] INT NOT NULL,
[DoctorName] VARCHAR(MAX) NOT NULL
);
CREATE TABLE [Patient] (
[PatientID] INT IDENTITY NOT NULL ,
[DoctorID] INT NOT NULL
);
CREATE TABLE [PatientAppointment] (
[PatientID] INT IDENTITY NOT NULL,
[Date] DATETIME NOT NULL
);
我想编写一个存储过程,将一年零一个月作为参数,并且应该返回[HospitalName],[DoctorsName]和该时间段的患者预约数。 这就是我现在所拥有的,而且我被困住了
CREATE PROCEDURE [dbo].[Procedure]
@year INT ,
@month INT
AS
SELECT COUNT([Date]) AS NumberOfAppointments FROM [PatientAppointment]
WHERE MONTH([Date]) = @month AND YEAR([Date]) = @year
SELECT [Hospital].HospitalName , [Doctors].DoctorName FROM [Doctors]
INNER JOIN [Hospital] ON [Hospital].HospitalID = [Doctors].DoctorID
RETURN 0
我无法弄清楚如何提取我需要的信息,我只能使用一个存储过程。
答案 0 :(得分:1)
试试这个:
CREATE PROCEDURE [dbo].[Procedure]
@year INT ,
@month INT
AS
BEGIN
SELECT h.HospitalId, d.DoctorName, count(p.PatientId) as NumberOfAppointments
FROM Hospital h
INNER JOIN Doctors d
ON h.HospitalId = d.HospitalId
INNER JOIN Patient p
ON d.DoctorId = p.DoctorId
INNER JOIN PatientAppointment ap
ON p.PatientId = ap.PatientId
AND MONTH(ap.[Date]) = @month
AND YEAR(ap.[Date]) = @year
GROUP BY h.HospitalId, d.DoctorName
END
答案 1 :(得分:1)
我的答案与Joachim发布的答案非常相似,但有一个非常显着的差异。此代码是SARGable,其中原始查询和已发布的优秀示例不是。既然你说你不能改变表格结构,我会避免建议改变....虽然你可以大大改善这些结构。
Create Procedure dbo.SomeBetterName
(
@Date date
) AS
select h.HospitalName
, d.DoctorName
, COUNT(pa.[Date]) as NumAppointments
from Hospital h
join Doctors d on h.HospitalID = d.HospitalID
join Patient p on p.DoctorID = d.DoctorID
join PatientAppointment pa on pa.PatientID = p.PatientID
where pa.Date >= dateadd(month, datediff(month, 0, @Date), 0)
and pa.Date < dateadd(month, datediff(month, 0, @Date) + 1, 0)
group by h.HospitalName
, d.DoctorName