从查询SQL Server获取最大记录

时间:2018-03-30 07:19:36

标签: sql sql-server

我有以下表格

CREATE TABLE Staff
(
    staffID int,
    fullName varchar(100) NOT NULL,
    s_category varchar(25),
    s_email varchar(50),
    s_contactNo int,
    speciality varchar(100),
    qualifications varchar(250),
    pre_employment varchar(200),
    salary numeric(8,2),
    staff_gender char(1),
    staff_joined_date datetime,
    branch_allocated int,

    CONSTRAINT PK_Staff 
        PRIMARY KEY (staffID),
    CONSTRAINT FK_Staff_Branch 
        FOREIGN KEY (branch_allocated) REFERENCES Branch(branchID) 
                ON DELETE CASCADE,
    CONSTRAINT CHK_StaffGender CHECK (staff_gender='M' OR staff_gender='F'),
    CONSTRAINT CHK_FullName CHECK (fullName NOT LIKE '%[^A-Za-z ]%'),
    CONSTRAINT CHK_SALARY CHECK (salary>0 AND salary<=150000)
);

CREATE TABLE Appointment
(
    appID int,
    patientId int,
    staffId int,
    appDateTime DateTime,

    CONSTRAINT PK_Appointment PRIMARY KEY (appID),
    CONSTRAINT FK_Appointment_Patient 
        FOREIGN KEY (patientId) REFERENCES Patient(patientID) 
                ON DELETE CASCADE,
    CONSTRAINT FK_Appointment_Staff 
        FOREIGN KEY (staffId) REFERENCES Staff(staffID) 
                ON DELETE CASCADE,
    CONSTRAINT CHK_AppointmentDate CHECK (appDateTime>=GETDATE())
);

我希望得到最多患者的医生。

我创建了如下查询。

SELECT 
    s.staffID AS 'ID',s.fullName AS 'Name', COUNT(a.appID) AS 'Number of Patients'
FROM 
    Staff s 
INNER JOIN 
    Appointment a ON s.staffID = a.staffId
GROUP BY 
    s.staffID, s.fullName
ORDER BY 
    'Number of Patients' DESC

但这会让所有医生回归。你能帮我找一个病人数最多的医生吗?

2 个答案:

答案 0 :(得分:3)

WITH cte AS (
    SELECT
        s.staffID AS ID,
        s.fullName AS Name,
        COUNT(a.appID) AS [Number of Patients],
        DENSE_RANK() OVER (ORDER BY COUNT(a.appID) DESC) AS rank
    FROM Staff s
    LEFT JOIN Appointment a
        ON s.staffID = a.staffId
    GROUP BY s.staffID, s.fullName
)

SELECT
    ID, Name, [Number of Patients]
FROM cte
WHERE rank = 1;

答案 1 :(得分:0)

你能试试吗

SELECT TOP 1

根据您的情况<script src="path/to/mylibrary" crossorigin="anonymous"></script>