您能否建议我如何编写查询以检索以下内容?
我需要找到A中的值重复但B中的值不同的任何行
A B
4567 2
852125 9
444 8
2547 25
255 4
256 1
2547 25
2547 27
259 4
2547 25
应该返回
2547 27
2547 25
因为2547在B列中有两个不相同的值
感谢您的期待
P
答案 0 :(得分:2)
with cte1 as (
select distinct A, B from Table1
), cte2 as (
select A, B, count(*) over(partition by A) as cnt from cte1
)
select
A, B
from cte2
where cnt > 1
<强> sql fiddle demo 强>
或
with cte as (
select distinct
A, B, min(B) over(partition by A) as m1, max(B) over(partition by A) as m2
from Table1
)
select
A, B
from cte
where m1 <> m2
<强> sql fiddle demo 强>
答案 1 :(得分:2)
试试这个
With DemoTable AS
(
Select 4567 A,2 B
Union All Select 852125 ,9
Union All Select 444 ,8
Union All Select 2547 ,25
Union All Select 255 ,4
Union All Select 256 ,1
Union All Select 2547 ,25
Union All Select 2547 ,27
Union All Select 259 ,4
Union All Select 2547 ,25
)
Select Distinct A, B
From DemoTable
Where A In
(
Select A
From DemoTable
Group By A
Having Count (Distinct B) > 1
)
输出
A B
----------- -----------
2547 25
2547 27
(2 row(s) affected)
答案 2 :(得分:1)
只需使用嵌套选择语句,其中一个计数,分组且 声明。
select distinct tbl.A,tbl.B from table_name tbl
where tbl.A in (select A from (
select tb.A, count(tb.B)
from table_name tb group by tb.A having count(tb.B)>1))
order by tbl.A