我有一张有两张不同邮票的桌子。我们称之为oristamp和tarstamp。我只需要找到相同oristamp有不同tarstamps的记录。用简单的查询可以做到这一点吗?我认为应该使用光标,但我不熟悉它。有什么帮助吗?
答案 0 :(得分:2)
我希望我理解这个问题。我假设您希望每个oristamp存在tarstamp超过1个不同值的所有行。
DECLARE @t table(tarstamp int, oristamp int)
INSERT @t values
(1,1),
(1,1),
(1,2),
(2,2)
;WITH CTE as
(
SELECT *,
max(tarstamp) over (partition by oristamp) mx,
min(tarstamp) over (partition by oristamp) mn
FROM @t
)
SELECT *
FROM CTE
WHERE mx <> mn
答案 1 :(得分:1)
使用子查询查找具有至少两个不同tarstamp值的值。加入该子查询:
select t1.*
from tablename t1
join (select oristamp from tablename
group by oristamp
having count(distinct tarstamp) >= 2) t2 on t1.oristamp = t2.oristamp
答案 2 :(得分:0)
您可以计算每oristamp
个不同tarstamp
个的数量,并选择tarstamp
个多行oristamp
的行,例如:
SELECT *
FROM mytable
WHERE tarstamp IN (SELECT tarstamp
FROM mytable
GROUP BY tarstamp
HAVING COUNT(DISTINCT oristamp) > 1)
答案 3 :(得分:0)
尝试此查询,该查询将返回包含不同oristamp的所有组合。
select distinct z.*
from
( select oristamp, count(*) ct
from mytable
Group by oristamp
)z,
( Select oristamp, tarstamp, count(*) ct
from mytable
Group by oristamp, tarstamp
)y
Where z.oristamp =y.oristamp
And z.ct != y.ct
答案 4 :(得分:0)
在您的情况下,使用MIN和MAX聚合函数将更好地执行COUNT(DISTINCT oristamp)&gt; 1增加了执行计划的复杂性:
SELECT tarstamp
FROM mytable
GROUP BY tarstamp
HAVING MIN(oristamp) != MAX(oristamp)
答案 5 :(得分:0)
尝试使用简单的连接:
DECLARE @t table(tarstamp int, oristamp int)
INSERT @t values
(1,1),
(1,1),
(1,2),
(2,2)
SELECT t1.*
FROM @t t1
INNER JOIN @t t2
ON t1.oristamp = t2.oristamp
WHERE t1.tarstamp <> t2.tarstamp