简体   繁体   中英

Filtering queries with same PK but different value keys

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'
  1. 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.

  2. 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);

在此处输入图片说明

Demo

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);

在此处输入图片说明

Demo

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.

https://www.w3schools.com/sql/sql_groupby.asp

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM