I have the following data
123 Amy Sleep
234 Bob Sleep
987 Helen Sleep
123 Amy Awake
123 Amy Awake
678 Fay Awake
765 Jay Awake
876 Irene Awake
987 Helen Awake
from running
SELECT t1.sid, name, status
FROM t2
JOIN Apply ON t2.sid=t1.sid
WHERE status='Awake' OR status='Sleep'
What would I do so that I can filter and have a unique tuples of the people who is both sleep and Awake? Eg: Amy and Helen.
How would I get the tuples of the people that is only asleep/awake?
Aggregation is one way to find people who are both awake and asleep:
SELECT sid, name
FROM yourTable
WHERE status IN ('Sleep', 'Awake')
GROUP BY sid, name
HAVING MIN(status) <> MAX(status);
We can try something similar to find persons with only one status:
SELECT sid, name
FROM yourTable
GROUP BY sid, name
HAVING MIN(status) = MAX(status);
Use GROUP BY
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
You can try below -
SELECT sid, name
FROM yourTable
WHERE status IN ('Sleep', 'Awake')
GROUP BY sid, name
having(distinct status)=2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.