I have a MySQL database with a table called "orders" containing all my orders. In this table I have different fields like:
id
userId
dateOrder
I would like to get ALL the orders grouped by users ONLY for users who did between 2 and 5 orders.
But my SQL queries don't work. Considering theses entries:
id userId dateOrder
1 138 2013-03-19
2 138 2013-03-19
3 222 2013-03-19
I would like a SQL request that only select orders who have been made by users who did at least 2 orders.
For this example, the SQL should return :
userId 138
I tried with GROUP BY, with DISTINCT, but none of these works. Can you help me please ?
Thanks !!
You should be able to use a HAVING clause to get the result:
select userid
from orders
group by userid
having COUNT(*) >= 2
and COUNT(*) <= 5
See SQL Fiddle with Demo
If you then want to return all of the details about each order, you can expand the query to:
select o1.id, o1.userid, o1.dateorder
from orders o1
where exists (select userid
from orders o2
where o1.userid = o2.userid
group by userid
having COUNT(*) >= 2
and COUNT(*) <= 5)
See SQL Fiddle with Demo
I think this should do it...
Select * from orders where userid in
(
Select userid from orders
group by userid having count(1) between 2 and 5
)
Related
I have a table for payments. It has a column named user_id, & payment_type. For every payment, a user can have multiple payment types.
I want to find the users that have used only one payment_type in their entire lifetime.
Let me make it clear through an example:
Let's say I have the following data:
user_id payment_type
1 UPI
1 NB
2 UPI
2 UPI
For the above, I only want user_id 2 as the output since for both the payments, it has used only 1 payment_type.
Can someone help?
A simple HAVING with COUNT should do the trick:
select user_id
from my_table
group by user_id
having count(distinct payment_type)=1;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=65f673a7df3ac0ee18c13105a2ec17ad
If you want to include payment_type in the result set , use:
select my.user_id,my.payment_type
from my_table my
inner join ( select user_id
from my_table
group by user_id
having count(distinct payment_type)=1
) as t1 on t1.user_id=my.user_id
group by my.user_id,my.payment_type ;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=cc4704c9e51d01e4e8fc087702edbe6e
I am trying to get users from mysql database if they have created a note with weather type = 'cloud','rain','clear' and not those who have missed even one out of these three.
eg.
id user_id weather_type
1 12 cloud
2 12 rain
3 12 clear
4 14 rain
5 15 clear
now here only user 12 have created notes with all three weather_type so only 12 should be fetched not 14 and 15.
Use group by and having:
select user_id
from mytable
where weather_type in ('cloud','rain','clear')
group by user_id
having count(distinct weather_type) = 3
You could use:
SELECT user_id
FROM tab
WHERE weather_type IN ('cloud','rain', 'clear')
GROUP BY user_id
HAVING SUM(weather_type='cloud') > 0
AND SUM(weather_type='rain') > 0
AND SUM(weather_type='clear') > 0;
SqlFiddleDemo
Output:
╔═════════╗
║ user_id ║
╠═════════╣
║ 12 ║
╚═════════╝
If you need all fields you could use:
SELECT *
FROM tab
WHERE user_id IN (prev_query);
Try this
SELECT user_id FROM tablex WHERE weather_type in ('cloud','rain','clear')
GROUP BY user_id
HAVING COUNT(DISTINCT weather_type) = 3
select user_id from table_name where weather_type in ('cloud','rain','clear')
group by user_id
having count(distinct weather_type) = 3
You can use group_concat function as below :
select user_id,weathers from
(select user_id, group_concat(weather_type)
weathers from tbl1 group by user_id
)t1
where find_in_set('cloud',weathers)>0 and
find_in_set('rain',weathers)>0 and
find_in_set('clear',weathers)>0 ;
I tested it and it works correctly.
More info :
A better and general solution for this kind of problem is :
Define another table named e.g. 'must_be' with two columns 'must_id' and 'weather' and fill it by favorite values like below:
must_id weather
1 cloud
2 rain
3 clear
Then use below query to fetch desired rows without hard code any value:
select user_id,count(*) cnt from
(select distinct user_id,weather_type from tbl1 join must_be on(weather_type=weather) ) t1
group by user_id having cnt=(select count(*) from must_be);
In the above query distinct keyword is necessary to get correct result in special situations.
After reading "trincot" response I decided to make my query better:
select user_id from tbl1 join must_be on(weather_type=weather)
group by user_id
having count(distinct weather_type)=(select count(*) from must_be);
I have a database with one table as shown below. Here I'm trying to write a query to display the names of medication manufactured by the company that manufactures the most number of medications.
By looking at the table we could say the medication names which belongs to the company id 1 and 2 - because those company manufactures the most medication according to this table, but I'm not sure how to write a query for selecting the same i said before.
ID | COMPANY_ID | MEDICATION_NAME
1 1 ASPIRIN
2 1 GLUCERNA
3 2 SIBUTRAMINE
4 1 IBUPROFEN
5 2 VENOFER
6 2 AVONEN
7 4 ACETAMINOPHEN
8 3 ACETAMINO
9 3 GLIPIZIDE
Please share your suggestions. Thanks!
Several ways to do this. Here's one which first uses a subquery to get the maximum count, then another subquery to get the companies with that count, and finally the outer query to return the results:
select *
from yourtable
where companyid in (
select companyid
from yourtable
group by companyid
having count(1) = (
select count(1) cnt
from yourtable
group by companyid
order by 1 desc
limit 1
)
)
SQL Fiddle Demo
This Query might work. I have not tested but the logic is correct
SELECT MEDICATION_NAME
FROM TABLE where
COMPANY_ID=(SELECT
MAX(counted)
FROM ( SELECT COUNT(*) AS counted FROM TABLE ) AS counts);
There is a small application that I've been tasked on, that deals with getting latest posts in a group. In this sample below, I have there is a MySQL table formatted as such:
groupid userid date_updated
1 1 [date]
1 2 [date]
2 1 [date]
2 2 [date]
2 3 [date]
...
How do I do an SQL statement as such as the results go out in this manner (assuming I give a userid with a value of 1 for example):
groupid userid date
1 2 [date]
2 2 [date]
2 3 [date]
These are all ordered by date. As you may have noticed, the results do not include the provided userid (as the requirement is only to get users other than the supplied user ID). In other words, show only users other than the specified user in groups where the specified user is part of.
Is it possible to do this in a single SQL statement?
Search select query with where
select * from table where userid != '1'
Try the following solution.
select
tbl.*
from
tbl INNER JOIN
(select groupid, userid, max(date_updated)
from tbl
group by groupid, userid) tbl2
USING(groupid, userid)
ORDER BY tbl.date_updated;
You can use this
SELECT tbl.* FROM (SELECT * FROM tablename ORDER BY date DESC) as tbl GROUP BY tbl.groupid
I managed to find a possible answer to my question here with this SQL statement:
SELECT a.groupid, a.userid, a.date_updated
FROM group_participants a
WHERE a.groupid IN (
SELECT DISTINCT b.groupid FROM group_participants b WHERE b.userid = 1
)
AND a.user_id <> 1
GROUP BY a.userid
ORDER by a.date_updated DESC
Thank you guys those SQL statements you posted, gave me an idea. I don't know if the SQL statement above can still be optimized, but this one above gave me the correct answer.
Could any one please help me with MySql database query:
I have one table with below data:
work_date ticket no category
------------------------------------
7/15/2013 111 a
7/15/2013 222 b
7/15/2013 333 c
7/16/2013 111 a
7/16/2013 555 e
7/16/2013 333 f
7/17/2013 111 H
I need help in writing a query which will read all table data, then create 2 columns one ticket no and second as category. Under ticket column it would show count of all distinct ticket number and value under category should be the last category assigned to that ticket.
i'm using the following query
SELECT category, count(distinct(ticket_no))
FROM master
group by category
order by 2 DESC`
the ticket which is present in 2 or more categories are being counted multiple times, I want it to be counted just once and that too the latest one
Expected Result:
Ticket No Category
--------------------
111 H
222 b
333 f
555 e
I don't get your sample query. It is grouping by category and not ticket, but the sample data is by ticket.
In any case, I think this does what you want:
select ticket,
substring_index(group_concat(category order by work_date desc), ',', 1)
from master m
group by ticket;
select * from
(select ticket_no,category from master order by work_date desc) abc
group by ticket_no;
fiddle
You can use the following SQL Query:
SELECT DISTINCT(ticket_no), category FROM table_name SORT BY DESC;
SELECT *
FROM distinct t1
WHERE NOT EXISTS (
SELECT *
FROM distinct t2
WHERE t2.ticket_no= t1.ticket_no
AND t2.work_date > t1.work_date
);
here work_date should be a formatted timestamp