简体   繁体   English

使用相同的PK但值键不同的查询

[英]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 使用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. GROUP BY语句通常与聚合函数(COUNT,MAX,MIN,SUM,AVG)一起使用,以将结果集按一列或多列分组。

https://www.w3schools.com/sql/sql_groupby.asp 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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