繁体   English   中英

SQL 查询查找记录属于两种状态

[英]SQL Query to find records belongs to two states

cust_id state
1 加州
2 伊利诺伊州
3 SC
1 功放
3 IA
4
5 弗吉尼亚州
4 纽约

任何人都可以请关于 SQL 查询返回属于以下两种状态的 cust_id:

output 应该是

cust_id state
1 加州
1 功放
3 SC
3 IA
4 纽约
4

尝试以下查询

解决方案 1

Select * From yourtable
Where Cust_Id In (Select cust_id From yourtable Group By cust_id Having 
Count(*) = 2) Order By cust_id,state

解决方案 2

With T1 As 
(Select cust_id From yourtable Group By cust_id Having Count(*) = 2) 
Select T2.* From yourtable T2 Join T1 On T1.cust_id = T2.cust_id O 
Order By T2.cust_id,T2.state
SELECT * FROM yourtable t1
JOIN
(SELECT cust_id,COUNT(DISTINCT state) AS cnt 
   FROM yourtable  GROUP BY cust_id HAVING cnt =2) t2
ON t1.cust_id=t2.cust_id
ORDER BY t1.cust_id,t2.state
SELECT tmp.*
   FROM tmp
 INNER JOIN (
    SELECT cust_id
        ,COUNT(STATE) s_count
    FROM tmp
    GROUP BY [cust_id]
) sub 
ON tmp.cust_id = sub.cust_id
 WHERE sub.s_count = 2
 ORDER BY cust_id
    ,STATE

一种简单的方法是使用COUNT window function,这将分配每个“ cust_id ”在您的表中出现的次数。 获得此值后,您可以过滤掉计数小于 2 的行。

WITH cte AS (
    SELECT *, COUNT(cust_id) OVER(PARTITION BY cust_id) AS cnt 
    FROM tab
)
SELECT cust_id,
       state
FROM cte 
WHERE cnt > 1

此处查看演示。

暂无
暂无

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

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