我正在尝试编写一个SQL查询来执行以下操作:
给出下表:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>Z:/maven/repository</localRepository>
<pluginGroups>
</pluginGroups>
<proxies>
</proxies>
<servers>
<server>
<id>nexus</id>
<username>user</username>
<password>password</password>
</server>
</servers>
<mirrors>
</mirrors>
<profiles>
</profiles>
</settings>
选择* 价值互不相同 按group_id分组
对于此示例,输出应为:
+----+----------+-----------+
| id | group_id | value |
+----+----------+-----------+
| 1 | 1 | 0 |
+----+----------+-----------+
| 2 | 1 | 0 |
+----+----------+-----------+
| 3 | 2 | null |
+----+----------+-----------+
| 4 | 3 | -1 |
+----+----------+-----------+
| 5 | 3 | 1 |
+----+----------+-----------+
| 6 | 4 | something |
+----+----------+-----------+
| 7 | 5 | something |
+----+----------+-----------+
有人知道这是否可能吗?
答案 0 :(得分:1)
如果您只想查找具有不同.detach()
的{{1}}值,则可以使用以下查询:
require_grad=True
输出您的样本数据:
group_id
如果要获取与该value
关联的行,请使用上述查询作为SELECT group_id
FROM data
GROUP BY group_id
HAVING MIN(value) != MAX(value)
表达式的子查询:
group_id
3
输出
group_id
答案 1 :(得分:1)
您可以使用exists
来获取不具有相同值的group_id。这是demo。
select
distinct group_id
from data d1
where exists
(
select
group_id
from data d2
where d1.group_id = d2.group_id
and d1.value <> d2.value
)
输出
*--------*
|group_id|
*--------*
| 3 |
*--------*
如果要同时使用group_id和值,请尝试以下操作
select
group_id,
value
from data d1
where exists
(
select
group_id
from data d2
where d1.group_id = d2.group_id
and d1.value <> d2.value
)
输出:
*------------------*
|group_id | value |
*------------------*
| 3 | -1 |
| 3 | 1 |
*------------------*
答案 2 :(得分:0)
此查询:
select group_id
from tablename
group by group_id
having count(distinct value) > 1 and count(distinct value) = count(value)
返回所需的group_id
,因此将其与运算符IN
一起使用:
select * from tablename
where group_id in (
select group_id
from tablename
group by group_id
having count(distinct value) > 1 and count(distinct value) = count(value)
)
请参见demo。
结果:
| id | group_id | value |
| --- | -------- | ----- |
| 4 | 3 | -1 |
| 5 | 3 | 1 |