Select element from table Where something in Select - mysql

I have this query
SELECT
equipe_id
FROM
user
GROUP BY
equipe_id
HAVING
COUNT(*) >= 5
and it returns 1 and 3.
I want to use this next query using the previous query
SELECT
name,
location
FROM
equipe
WHERE
equipe_id IN ??? previous query result (1,3) ???
I hope that makes sense. Thank you

SELECT name
, location
FROM equipe
WHERE equipe_id in (SELECT equipe_id FROM user GROUP BY equipe_id HAVING COUNT(*) >= 5);

We can also try doing this via joining to a subquery:
SELECT e1.name, e1.location
FROM equipe e1
INNER JOIN
(
SELECT equipe_id
FROM user
GROUP BY equipe_id
HAVING COUNT(*) >= 5
) e2
ON e1.equipe_id = e2.equipe_id;

As an alternative, this can be done also without the inner subquery, like this:
SELECT
e.name,
e.location
FROM
equipe AS e
INNER JOIN
user AS u ON u.equipe_id = e.equipe_id
GROUP BY
e.equipe_id, e.name, e.location
HAVING
COUNT(*) >= 5

Related

How Can I Select needed information in SQL?

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.

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

Decrease find duplicate record query execution time

I have 3 lac of records. I need to count duplicate records and return all duplicate records (Ex. if example#example.com are 10 times then returns all 10 records with duplicate of 10)
I have created query for that but it takes 15 seconds of time. Any suggestion to decrease time?
SELECT g.guest_name, g.email, b.totalCount AS duplicate_guest
FROM guest g
INNER JOIN (SELECT email, COUNT(Id) AS totalCount FROM guest GROUP BY email ) b ON g.email = b.email
Need to decrease the data for join condition by adding having condition like below query.
Also make sure that there should be an index on email column to optimize it
SELECT g.guest_name, g.email, b.count as duplicate_guests
FROM guest g
INNER JOIN
(
SELECT email, COUNT(Id) AS count
FROM guest
GROUP BY email
HAVING count(*) > 1
) b ON g.email = b.email
Just add HAVING count(*) > 1 to the inner select
SELECT g.guest_name, g.email, b.totalCount AS duplicate_guest
FROM guest g
INNER JOIN
(
SELECT email, COUNT(Id) AS totalCount
FROM guest
GROUP BY email
HAVING count(*) > 1
) b ON g.email = b.email

Using JOINs and group by together in single sql query

I'm not able to use JOINS and group-by together:
I searched for this...but I didn't find the solution..Problem is as below:
I have two tables, first is main_table with fields eid, name, status
Second table is followups with fields fid, eid, last_date, remarks, and next_date
Second table is used to store followup details of clients (client details stored in main_table) and i want to get last followup record for each client with selected date period (from_date to to_date) and sort by next_date in descending order.
i used the below query but not working
SELECT *
FROM main_table as MT
JOIN followups as MF on MT.eid=MF.eid
WHERE MT.status='open' AND MF.NDate<='2012-12-07'
GROUP BY MF.eid
ORDER BY MF.next_date DESC
thanks in advance...guys
Try This
SELECT * FROM main_table AS MT
LEFT JOIN (SELECT * FROM (SELECT * FROM followups ORDER BY next_date DESC) AS A GROUP BY eid) AS MF ON MT.eid=MF.eid
WHERE MT.status='open'
AND MF.NDate<='2012-12-07';
You can try something like this:
select m.eid,
m.name,
m.status,
f1.last_date,
f1.remarks,
f1.next_date
from maintable m
left join
(
select max(last_date) maxLast, eid
from followups
where last_date between from_date and to_date
group by eid
) f
on m.eid = f.eid
left join followups f1
on f.maxLast = f1.last_date
and f.eid = f1.eid
where m.status='open'
and f1.next_date<='2012-12-07'
order by f1.next_date desc
Try this:
SELECT * FROM main_table AS MT
LEFT JOIN (SELECT * FROM (SELECT * FROM followups WHERE NDate<='2012-12-07' ORDER BY next_date DESC) AS A GROUP BY eid) AS MF ON MT.eid=MF.eid
WHERE MT.status='open';

MySQL Query not displaying correctly

I am having to set up a query that retrieves the last comment made on a customer, if no one has commented on them for more than 4 weeks. I can make it work using the query below, but for some reason the comment column won't display the latest record. Instead it displays the oldest, however the date shows the newest. It may just be because I'm a noob at SQL, but what exactly am I doing wrong here?
SELECT DISTINCT
customerid, id, customername, user, MAX(date) AS 'maxdate', comment
FROM comments
WHERE customerid IN
(SELECT DISTINCT id FROM customers WHERE pastdue='1' AND hubarea='1')
AND customerid NOT IN
(SELECT DISTINCT customerid FROM comments WHERE DATEDIFF(NOW(), date) <= 27)
GROUP BY customerid
ORDER BY maxdate
The first "WHERE" clause is just ensuring that it shows only customers from a specific area, and that they are "past due enabled". The second makes sure that the customer has not been commented on within the last 27 days. It's grouped by customerid, because that is the number that is associated with each individual customer. When I get the results, everything is right except for the comment column...any ideas?
Join much better to nested query so you use the join instead of nested query
Join increase your speed
this query resolve your problem.
SELECT DISTINCT
customerid,id, customername, user, MAX(date) AS 'maxdate', comment
FROM comments inner join customers on comments.customerid = customers.id
WHERE comments.pastdue='1' AND comments.hubarea='1' AND DATEDIFF(NOW(), comments.date) <= 27
GROUP BY customerid
ORDER BY maxdate
I think this might probably do what you are trying to achieve. If you can execute it and maybe report back if it does or not, i can probably tweak it if needed. Logically, it ' should' work - IF i have understood ur problem correctly :)
SELECT X.customerid, X.maxdate, co.id, c.customername, co.user, co.comment
FROM
(SELECT customerid, MAX(date) AS 'maxdate'
FROM comments cm
INNER JOIN customers cu ON cu.id = cm.customerid
WHERE cu.pastdue='1'
AND cu.hubarea='1'
AND DATEDIFF(NOW(), cm.date) <= 27)
GROUP BY customerid) X
INNER JOIN comments co ON X.customerid = co.customerid and X.maxdate = co.date
INNER JOIN customer c ON X.customerid = c.id
ORDER BY X.maxdate
You need to have subquery for each case.
SELECT a.*
FROM comments a
INNER JOIN
(
SELECT customerID, max(`date`) maxDate
FROM comments
GROUP BY customerID
) b ON a.customerID = b.customerID AND
a.`date` = b.maxDate
INNER JOIN
(
SELECT DISTINCT ID
FROM customers
WHERE pastdue = 1 AND hubarea = 1
) c ON c.ID = a.customerID
LEFT JOIN
(
SELECT DISTINCT customerid
FROM comments
WHERE DATEDIFF(NOW(), date) <= 27
) d ON a.customerID = d.customerID
WHERE d.customerID IS NULL
The first join gets the latest record for each customer.
The second join shows only customers from a specific area, and that they are "past due enabled".
The third join, which uses LEFT JOIN, select all customers that has not been commented on within the last 27 days. In this case,only records without on the list are selected because of the condition d.customerID IS NULL.
But tomake your query shorter, if the customers table has already unique records for customer, then you don't need to have subquery on it.Directly join the table and put the condition on the WHERE clause.
SELECT a.*
FROM comments a
INNER JOIN
(
SELECT customerID, max(`date`) maxDate
FROM comments
GROUP BY customerID
) b ON a.customerID = b.customerID AND
a.`date` = b.maxDate
INNER JOIN customers c
ON c.ID = a.customerID
LEFT JOIN
(
SELECT DISTINCT customerid
FROM comments
WHERE DATEDIFF(NOW(), date) <= 27
) d ON a.customerID = d.customerID
WHERE d.customerID IS NULL AND
c.pastdue = 1 AND
c.hubarea = 1
Two of your table columns are not contained in either an aggregate function or the GROUP BY clause. for example suppose that you have two data rows with the same customer id and same date, but with different comment data. how SQL should aggregate these two rows? :( it will generate an error...
try this
select customerid, id, customername, user,date, comment from(
select customerid, id, customername, user,date, comment,
#rank := IF(#current_customer = id, #rank+ 1, 1),
#current_customer := id
from comments
where customerid IN
(SELECT DISTINCT id FROM customers WHERE pastdue='1' AND hubarea='1')
AND customerid NOT IN
(SELECT DISTINCT customerid FROM comments WHERE DATEDIFF(NOW(), date) <= 27)
order by customerid, maxdate desc
) where rank <= 1