2016-09-15 45 views
2

我在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 

結果應該是的(的val2)將行僅作爲價值val1中的至少一次變爲y。但val2.b的行應該在結果中被忽略,因爲它在val1中的值不會改變。

val1 | val2 
------+------ 
x  | a 
x  | a 
y  | a 

回答

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

這是做你想做的嗎?

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) 
       ); 
+0

它返回所有的行。 – bill

+0

將min(t2.val1)<> max(t2.val2)更改爲min(t2.val1)<> max(t2.val1)和= to in工作。 – bill

+0

@bill。 。 。是的,那是對的。這是一個錯字。 –

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 
) 
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) 
    ) 
相關問題