gpt4 book ai didi

sql - 使用复合主键查询表

转载 作者:行者123 更新时间:2023-12-02 16:02:40 27 4
gpt4 key购买 nike

我有一个带有复合主键的表。这是一个交叉引用表,看起来像这样

Table 
ID Relationship ID2
1 Spouse 10
2 Employee 20
2 Former Employee 20
3 Former Employee 30
4 Child 40

我正在尝试编写一个 ID2 匹配的查询,您有相同 ID 的员工和前员工

ID    Relationship             ID2
2 Employee 20
2 Former Employee 20

感谢任何帮助!!

最佳答案

OracleSQL ServerPostgreSQL 中:

SELECT  *
FROM (
SELECT t.*,
COUNT(*) OVER (PARTITION BY id, id2) AS cnt
FROM mytable t
WHERE relationship IN ('Employee', 'Former Employee')
) q
WHERE cnt = 2

跨平台版本:

SELECT  t.*
FROM (
SELECT id, id2
FROM mytable
WHERE relationship IN ('Employee', 'Former Employee')
GROUP BY
id, id2
HAVING COUNT(*) = 2
) q
JOIN mytable t
ON t.id = q.id
AND t.id2 = q.id2
AND t.relationship IN ('Employee', 'Former Employee')

关于sql - 使用复合主键查询表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com