Get Max record from query SQL Server - sql

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?

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;

Can you try this
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
on your situation SELECT TOP 1

Related

What is the mistake in this SQL statement? - SQL

SQL query:
insert into Transaction_Details (Trans_Date, Trans_Type)
values (GetDate(), 'WITHDRWAL')
from Transaction_Details t
inner join Acc_Details a on t.UserID = a.UderId
where a.Card_No = '1234567890123456';
Transaction table columns:
Trans_ID int PRIMARY KEY IDENTITY(1,1),
Trans_Date datetime,
Trans_Type varchar(20),
UserID int foreign key references User_Details(UserID)
Card_Id varchar(16) foreign key references User_Card_Details,
Acc_No int foreign key references Acc_Details(Acc_No)
Acc_Details columns:
Acc_Id int,
Acc_No int PRIMARY KEY,
Card_No varchar(16) foreign key references User_Card_Details(Card_No),
UserId int foreign key references User_Details(UserID),
Balance int,
BankName varchar(15)
I get this error:
Incorrect syntax near the keyword 'from'
To insert based on a select it's this:
insert into Transaction_Details (Trans_Date, Trans_Type)
select GetDate(),
'WITHDRWAL'
from Transaction_Details t
inner join Acc_Details a on t.UserID = a.UderId
where a.Card_No = '1234567890123456';

sql not a group by expression, not able to join 3 tables

im trying to connect 3 tables together, it works just fine however when i try to group them by a certain column it shows me not a group by expression:
my tables:
create table userss (
username varchar2(25)not null ,
password varchar2(25) ,
userTypeID number(8) not null,
gender char(1),
dateCreated date,
lname varchar2(10),
fname varchar2(10),
constraint username1_pk primary key (username),
CONSTRAINT gender1_ck CHECK (gender='M' or gender='F'),
constraint userTypeID_fk foreign key(userTypeID) references userType (userTypeId)
);
create table doctor (
docID number(8) not null ,
docBioData varchar2(50),
username varchar2(25)not null ,
SpecID number(3),
post_id number(5) not null ,
constraint docID_pk primary key(docID),
constraint username4_fk foreign key (username) references userss(username),
constraint specID2_fk foreign key (specID) references speciality(specID),
constraint post_id_fk foreign key (post_id) references positions(post_id)
);
create table rating (
ratID number(10) not null ,
rat_date date,
rat_comment varchar2(100),
rat_rating number(1) not null,
docID number(8) not null ,
patID number(8) not null,
constraint ratID_pk primary key(ratID),
constraint docID_fk foreign key (docID) references doctor(docID),
constraint patID2_fk foreign key (patID) references patient(patID),
constraint rating_ck check (rat_rating between 1 and 5)
);
and my code is:
select d.docid, (fname|| ' '|| lname) "Doctor Name", count(r.rat_rating), avg(r.rat_rating)
from userss u, doctor d, rating r
where u.username = d.username and d.docid = r.docid and rat_date > TO_DATE('01-JAN-2020', 'DD-MON-YYYY')
group by d.docid
order by d.docid desc;
In your SELECT there is 2 columns before the COUNT and the AVG, therefore you have to GROUP BY those 2 columns.
Depending on your version, you cannot group by on an alias, you would need to encapsulate your first query.
select id, Doctor_Name, COUNT(rat_rating), AVG(rat_rating) from (
select d.docid AS id, (fname|| ' '|| lname) AS Doctor_Name, r.rat_rating, r.rat_rating
from userss u, doctor d, rating r
where u.username = d.username and d.docid = r.docid and rat_date > TO_DATE('01-JAN-2020', 'DD-MON-YYYY')
) A
group by id, Doctor_Name
order by id desc
You could on the other hand delete the "Doctor Name" column from your query, and it should work

ORA-00933: SQL Command not properly ended - (Error at Line 2)

I'm not sure where the error is,
(Error at Line 2)
(Help)
select last_name, first_name
from employee group by Employee_ID in
select Employee_ID from service group by Property_ID having count(*)>2;
employee table
create table EMPLOYEE(
Employee_ID int primary key,
Last_name char(30),
First_Name char(30),
CellPhone char(20),
ExperienceLevel char(30),
CONSTRAINT EX_EMPLOYEE_EXPERIENCELEVEL CHECK (ExperienceLevel IN('Master', 'Junior', 'Senior'))
);
service Table
create table SERVICE (
Property_ID int,
Employee_ID int,
Service_Date date,
Hours_worked int,
primary key(Property_ID, Employee_ID),
foreign key(Property_ID) references PROPERTY(Property_ID),
foreign key(Employee_ID) references EMPLOYEE(Employee_ID)
);
property table
create table PROPERTY(
Property_ID int primary key,
Owner_ID int,
Owner_Name char(30),
Owner_email char(30),
Owner_type char(30),
CONSTRAINT EX_PROPERTY_OWNERTYPE CHECK (Owner_type IN('Individual', 'Corporate', 'Partnership'))
);
Your query is not very clear. The in clause before the subquery is not a valid clause at that position. If you want to select the employes whose id are in the subquery, so you have to do something like this:
select last_name, first_name
from employee
WHERE Employee_ID in
(select Employee_ID from service
group by Property_ID having count(*)>2);

Join three tables based on a single common column and select max date value

I have SQL Server tables defined like this:
create table users
(
user_id int NOT NULL IDENTITY(1,1),
name varchar(200),
username varchar(200),
password varchar(50),
encrypted_password varchar(100),
email varchar(30),
phone_no int,
address varchar(200),
PRIMARY KEY(user_id)
)
create table electricity
(
table_name VARCHAR(50),
electricity_bill_id int NOT NULL IDENTITY(1,1),
billing_month_year varchar(50),
units_consumed int,
user_id int,
account_number varchar(100),
amount varchar(100),
due_date varchar(100),
PRIMARY KEY(electricity_bill_id),
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
insert into electricity (table_name, billing_month_year, units_consumed, user_id, account_number, amount, due_date)
values ('Electricity','2015-05-22',13,1,'acc01',2500,'2015-06-22');
create table water
(
table_name VARCHAR(10),
water_bill_id int NOT NULL IDENTITY(1,1),
billing_month_year_date varchar(50),
units_consumed int,
user_id int,
account_number varchar(100),
amount varchar(100),
due_date varchar(100),
PRIMARY KEY(water_bill_id),
FOREIGN KEY(user_id) REFERENCES users(user_id)
)
insert into water(table_name, billing_month_year_date, units_consumed, user_id, account_number, amount, due_date)
values ('Water','2015-04-22',17,1,'acc01',2500,'2015-05-14');
create table telephone
(
table_name VARCHAR(10),
telecom_bill_id int NOT NULL IDENTITY(1,1),
bill_Period varchar(100),
user_id int,
account_number varchar(100),
amount varchar(100),
issued_date varchar(50),
due_date varchar(50),
PRIMARY KEY(telecom_bill_id),
FOREIGN KEY(user_id) REFERENCES users(user_id)
)
insert into telephone(table_name, bill_Period, user_id, account_number, amount, issued_date, due_date)
values ('Telephone', '2015-04-22', 1, 'acc01', 2500, '2015-05-14', '2015-05-18');
The problem is that I want to join electricity, water and telephone tables based on the user id that I need to pass in to the query.
And also I want to pick the maximum due_date from the three tables. But, I've some issues with it.
Please can somebody help me.
One method is to use outer apply:
select u.*, e.*, w.*, t.*
from users u outer apply
(select top 1 e.*
from electricity e
where e.user_id = u.user_id
order by e.due_date desc
) e outer apply
(select top 1 w.*
from water w
where w.user_id = u.user_id
order by w.due_date desc
) w outer appy
(select top 1 t.*
from telephone t
where t.user_id = u.user_id
order by t.due_date desc
) t
where u.user_id = #user_id;
With indexes on (user_id, due_date) on all three tables, the query should have very good performance as well.
If I understand your question well, you want to do something like this:
SELECT MAX(e.due_date) AS ElectricityDueDate, MAX(w.due_date) AS WaterDueDate, MAX(t.due_date) AS TelephoneDueDate
FROM user u, electricity e, water w, telephone t
WHERE u.user_id=#user_id AND
e.user_id=u.user_id AND
w.user_id=u.user_id AND
t.user_id=u.user_id AND
GROUP BY u.user_id
However, to do so you should change the due_date type to DATE, in this way
you can compute the max value.

sql query details for a certain date

I have the following database:
create table Hotel (
HNo char(4),
Name varchar(20) not null,
Address varchar(50),
Constraint PK_Hotel Primary Key (HNo))
)
create table Room (
RNo char(4),
HNo char(4),
Type char(6) not null,
Price decimal (7,2),
Constraint PK_Room Primary Key (HNo, RNo),
Constraint FK_Room Foreign Key (HNo)
references Hotel (HNo)
)
create table Guest (
GNo char(4),
Name varchar(20) not null,
Address varchar(50),
Constraint PK_Guest Primary Key (GNo)
)
create table Booking (
HNo char(4),
GNo char(4),
DateFrom date,
DateTo date,
RNo char(4),
Constraint PK_Booking Primary Key (HNo, GNo, DateFrom),
Constraint FK_Booking Foreign Key (GNo)
references Guest (GNo),
Constraint FK_Booking_room Foreign Key (HNo, RNo)
references Room (HNo, RNo),
Constraint FK_Booking_hotel Foreign Key (HNo)
references Hotel (HNo)
)
What I am struggling with is using the dateto=> <=datefrom and getting it to work.
For the 26th march 1997, I need to list the details of all rooms in all hotels, including the name of any guests who were staying in the room. I'm not too bad with joining the tables etc, but am not sure how to do it as a whole on the specified date? Any ideas?
SELECT
h.Name,
h.Address,
r.RNo,
r.HNo,
r.Type,
r.Price,
G.Name,
G.Address,
...
FROM Hotel AS h
INNER JOIN Room AS r ON h.HNo = r.HNo
INNER JOIN Guest AS g ON r.RNo = g.RNo
INNER JOIN Booking AS b ON b.GNo = g.GNo
AND b.HNo = h.HNo
WHERE b.DateFrom <= #DateFrom
AND b.DateTo => #DateTo;
SELECT b.datefrom, b.dateto, h.name AS hotelname
, b.rno
, r.type
, g.name AS guestname
FROM booking b
JOIN hotel h ON b.hno = h.hno
JOIN guest g ON g.gno = b.gno
JOIN room r ON b.rno = r.rno
WHERE #yourDate BETWEEN b.datefrom AND b.dateto
EDIT :
Replace the #yourDate in the last line with a suitable expression supported by your DBMS.
E.g., in Oracle, there is a function TO_DATE which converts a given string to date, like TO_DATE('26-MAR-1997') BETWEEN b.datefrom AND b.dateto. In SQL Server there is CAST function.