我在SQL Server中有一个如下表:
DECLARE @tbl TABLE (val1 VARCHAR(10), val2 VARCHAR(10) )
INSERT INTO @tbl
VALUES ('x', 'a'), ('x', 'a'), ('p', 'b'), ('y', 'a'), ('p', 'b');
val1 | val2
------+-------
x | a
x | a
p | b
y | a
p | b
结果应该是a(val2)的行,因为val1中a的值至少变为y一次。但是val2.b的行应该在结果中被忽略,因为它在val1中的值不会改变。
val1 | val2
------+------
x | a
x | a
y | a
答案 0 :(得分:2)
试试这个,
select t.*
from @tbl t
INNER JOIN ( select t2.val2
from @tbl t2
group by t2.val2
having min(t2.val1) <> max(t2.val1)
) AS tt ON tt.val2 = t.val2
答案 1 :(得分:2)
我终于使用如下所示了。
SELECT t.*
FROM @tbl t
WHERE EXISTS (
SELECT t2.val2
FROM @tbl t2
WHERE t.val2 = t2.val2
GROUP BY t2.val2
HAVING min(t2.val1) <> max(t2.val1)
)
答案 2 :(得分:1)
这样做你想要的吗?
select t.*
from @tbl t
where t.val2 = (select t2.val2
from @tbl t2
group by t2.val2
having min(t2.val1) <> max(t2.val1)
);
答案 3 :(得分:1)
SELECT
*
FROM @tbl
WHERE val2 IN
(
SELECT
Z.val2
FROM
(
SELECT
*,ROW_NUMBER() OVER(Partition BY val2 Order BY Val2) AS PartNo
FROM
(
SELECT
*
FROM @tbl
GROUP BY val1,val2
)X
)Z WHERE Z.PartNo>1
)