0

I have the following tables

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())
);

I want to get the doctor(s) with maximum number of patients.

I have created the query as follows.

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

But this returns all doctors. Can you help me to find the doctor with the largest number of patients?

2 Answers 2

2
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;
Sign up to request clarification or add additional context in comments.

1 Comment

@TimBiegeleisen Thanks for the suggestion.
1

Can you try this

SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

on your situation SELECT TOP 1

1 Comment

Or use TOP 1 WITH TIES to simulate rank.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.