How Can I Select needed information in SQL? - mysql

My BD:
I need to select the column with departament.nume which have <=3 records in tabel angajat.departament_id.
i tried:
SELECT departament.nume
FROM (angajat INNER JOIN
departament
ON angajat.departament_id=departament.id_dep
)
where count(angajat.id_dep)<=3;

Aggregate before joining:
SELECT d.nume
FROM departament d LEFT JOIN
(SELECT a.departament_id, COUNT(*) as cnt
FROM angajat a
GROUP BY a.departament_id
) a
ON a.departament_id = d.id_dep
WHERE COALESCE(cnt, 0) < 3 ;
Note the use of LEFT JOIN to be sure that departments with no rows in agnajat are included in the result set.

SELECT departament.nume
FROM angajat
INNER JOIN departament
ON angajat.departament_id=departament.id_dep
GROUP BY departament.nume
HAVING COUNT(*)<=3

Use Group By and Having
SELECT d.nume,
FROM angajat a JOIN departament d ON a.departament_id = d.id_dep
GROUP BY d.nume
HAVING COUNT (d.nume) <= 3;

No need for a subquery.
SELECT departament.nume
FROM departament
LEFT JOIN angajat ON angajat.departament_id=departament.id_dep
GROUP BY departament.id_dep
HAVING COUNT(*) <= 3
If you don't want departments with no angajat records, use an inner join instead.
If you want the counting to include together departments with the same nume but different id_dep, group on nume instead.
If you don't want that, but only want each nume returned only once, select DISTINCT departament.nume.

Related

MySQL use leftjoin with select

i have two tables:
1. movie
id, userid, movie_id, status, score
2. movie_data
id, name_de, name_en, description, url
When i use this query:
SELECT *
FROM `movie` LEFT JOIN
movie_data ON movie.movie_id = movie_data.id
ORDER BY movie.id
When i enter this query, i get all fields, but also two times id. But i don't manage to show only the first "id" or rename the second id. i hope someone can help me :)
Thanks for reading
You need to enumerate the columns in the SELECT clause and use aliases to disambiguate homonym columns:
SELECT
m.id,
m.user_id,
m.movie_id,
m.status,
m.score,
d.id data_id, --> column alias
d.name_de,
d.name_en,
d.description,
d.url
FROM movie m
LEFT JOIN movie_data d ON m.movie_id = d.id
ORDER BY m.id
Explicitly list the columns you want. Don't use select *:
SELECT m.id, m.userid, m.movie_id, m.status, m.score,
md.name_de, md.name_en, md.description, md.url
FROM `movie` m LEFT JOIN
movie_data md
ON m.movie_id = md.id
ORDER BY m.id
The query should be next:
SELECT
`movie`.`id`,
`movie`.`userid`,
`movie`.`movie_id`,
`movie`.`status`,
`movie`.`score`,
`movie_data`.`name_de`,
`movie_data`.`name_en`,
`movie_data`.`description`,
`movie_data`.`url`
FROM `movie`
LEFT JOIN `movie_data` ON `movie`.`movie_id` = `movie_data`.`id`
ORDER BY `movie`.`id`;
This way you can exactly select what you need
You can also do, for example
SELECT
`movie`.*, -- select all fields from one table
movie_data.id as movieId -- and some fields of another table
FROM `movie` LEFT JOIN
movie_data ON movie.movie_id = movie_data.id
ORDER BY movie.id

Combine and Display query result

I have 2 query:
SELECT CustomerID,count(b.BookingStatus) as 'NotComplete'
FROM Booking b, Customer c
WHERE c.CustomerID=b.BookingCustomerID
AND(b.BookingStatus='Pending'
OR b.BookingStatus='OTW')
GROUP BY c.CustomerID
SELECT c.CustomerID, r.*
FROM Customer c,Regular r
WHERE c.CustomerID=r.RegularCID
Result:
1st query
2nd query
How to combine these 2 result together?
also, display the zero(count) as well.
Thanks!
this is what I get after few hours of trying..obviously it's not what I want..
SELECT c.CustomerID,count(b.BookingStatus) as 'NotComplete',r.RegularID
FROM Booking b, Customer c
JOIN Regular r on r.RegularCID=c.CustomerID
WHERE c.CustomerID=b.BookingCustomerID
AND (b.BookingStatus='Pending'
or b.BookingStatus='OTW'
or b.BookingStatus='Started'
or b.BookingStatus='Unclaimed'
or b.BookingStatus='Confirmed')
GROUP by r.RegularID
You can JOIN to the Regular table and then LEFT JOIN to a derived table of counts in the Booking table. We do it this way to avoid having to GROUP BY all the columns in the Regular table:
SELECT c.CustomerID, r.*, b.NotComplete
FROM Customer c
JOIN Regular r ON r.RegularCID = c.CustomerID
LEFT JOIN (SELECT BookingCustomerID, COUNT(*) AS NotComplete
FROM Booking
WHERE BookingStatus IN ('Pending', 'OTW', 'Started', 'Unclaimed', 'Confirmed')
GROUP BY BookingCustomerID) b ON b.BookingCustomerID = c.CustomerID
Use join on regular table, and subquery on your first select
SELECT t1.*, r.RegularCID FROM (
SELECT CustomerID,count(b.BookingStatus) as 'NotComplete',
FROM Booking b
INNER JOIN Customer c ON c.CustomerID=b.BookingCustomerID
WHERE (b.BookingStatus='Pending' OR b.BookingStatus='OTW')
GROUP BY c.CustomerID) t1
LEFT JOIN Regular r on r.CustomerID = t1.CustomerID

Is it possible to select from the result of a subquery in a join

So I have a large subquery and I would like to join on that subquery while using the result of the subquery in the join.
For example, I have a table called patient and one called appointment, and I would like to get the number of appointments per patient with given criteria.
Right now I am doing something like this:
SELECT
t1.*
FROM
(
SELECT
patient.name,
patient.id,
appointment.date
FROM
patient
LEFT JOIN appointment ON appointment.patient_id = patient.id
WHERE
/* a **lot** of filters, additional joins, etc*/
) t1
LEFT JOIN (
SELECT
COUNT(*) number_of_appointments,
patient.id
FROM
patient
LEFT JOIN appointment ON appointment.patient_id = patient.id
GROUP BY
patient.id
) t2 ON t1.id = t2.id
The problem is that this returns the number of appointments for each patient independent from the subquery above it. I tried writing the join as this:
LEFT JOIN (
SELECT
COUNT(*) number_of_appointments,
patient.id
FROM
t1
GROUP BY
patient.id
)
But obviously I'm getting an error saying that table t1 doesn't exist. Is there any way for me to do this cleanly without having to repeat all of the filters from t1 in t2?
Thanks!
Why not use window functions?
SELECT p.name, p.id, a.date,
COUNT(a.patient_id) OVER (PARTITION BY p.id) as num_appointments
FROM patient p LEFT JOIN
appointment a
ON a.patient_id = p.id
WHERE . . .
This provides the count based on the WHERE filtering. If you wanted a count of all appointments, then do the calculation before applying the WHERE:
SELECT p.name, p.id, a.date,
COALESCE(a.cnt, 0) as num_total_appointments,
COUNT(a.patient_id) OVER (PARTITION BY p.id) as num_matching appointments
FROM patient p LEFT JOIN
(SELECT a.*,
COUNT(*) OVER (PARTITION BY a.patient_id) as cnt
FROM appointment a
) a
ON a.patient_id = p.id
WHERE . . .

SQL Server Join tables

I want each student's name, last payment date only. means only day.
I know i won't help you at all giving this code:
But you could try to learn something from it.
SELECT S.Id, S.Name, F.max_date, F.FeeAmt
FROM tbl_student As S
INNER JOIN (
SELECT t.Id, MAX(t.Date) As max_date, t.FeeAmt FROM tbl_fees As t GROUP BY t.Id
) As F ON F.Id=S.Id
First we selected all users from tbl_student, and then we are joining fees, selecting max date and grouping by user. The result is last (date) fee per user.
Please try this query. I hope this should give you the expected output:
SELECT S.Name, T1.LastPaymentDate
FROM
(SELECT Id, Max([Date]) AS LastPaymentDate from tbl_fees GROUP BY Id) AS T1
INNER JOIN
tbl_student AS S
ON T1.Id = S.Id
SELECT S.name,SUB.LAST_DATE
FROM tbl_student S
JOIN (SELECT f.id AS ID,MAX(f.Date) AS LAST_DATE
FROM tbl_fees f
GROUP BY f.id) SUB
ON SUB.id = S.id

MySQL query and count from other table

I would like to get the data from one table, and count all results from other table, depending on the first table data, here is what I tried:
SELECT
cars.*, (
SELECT
COUNT(*)
FROM
uploads
WHERE
uploads.cid = cars.customer
) AS `count`,
FROM
`cars`
WHERE
customer = 11;
I dont really have an idea why its not working, as I'm not a regular MySQL user/coder...
Could anyone direct me in the right direction with this one?
SELECT
c.*, COUNT(u.cid) AS count
FROM
cars c
LEFT JOIN
uploads u
ON
u.cid=c.customer
WHERE
u.customer = 11;
GROUP BY c.cid
Try it by joining both tables using LEFT JOIN
SELECT a.customer, COUNT(b.cid) totalCount
FROM cars a
LEFT JOIN uploads b
ON a.customer = b.cid
WHERE a.customer = 11
GROUP BY a.customer
using COUNT(*) in LEFT JOIN will have records to have a minimum count of 1.
SELECT cars.*,COUNT(uploads.*) as uplloaded
from cars
left outer join uploads on uploads.cid = cars.customer
where cars.customer = 11
group by uploads.cid;
Try this :
SELECT customer, COUNT(cid) totalCount
FROM cars
INNER JOIN uploads
ON (customer = cid)
WHERE customer = 11
GROUP BY customer