选择一列中相åŒä½†åœ¨å¦ä¸€åˆ—中ä¸åŒçš„è¡Œ

时间:2012-03-07 19:48:07

标签: sql sql-server-2008

X    Y    DATE
1    20   20120101
1    21   20120101
2    30   20120201
3    40   20120201
3    41   20120301

我想选择任何行,其中X是相åŒçš„å¦ä¸€è¡Œï¼Œä½†æ—¥æœŸä¸åŒï¼Œå³ç­”案是

3    40   20120201
3    41   20120301

3 个答案:

答案 0 :(得分:22)

试试这个......

SELECT *
FROM YourTable
WHERE X IN (
  SELECT T1.X
  FROM YourTable T1 INNER JOIN
       YourTable T2 ON T1.X = T2.X
  WHERE T1.DATE <> T2.DATE
);

这应该适用于大多数符åˆANSI标准的数æ®åº“产å“。

答案 1 :(得分:2)

select distinct t1.*
  from table t1
  join table t2
    on (t1.X = t2.X and t1.date <> t2.date);

答案 2 :(得分:0)

declare @t table(X int, Y int, DATE CHAR(8))
insert @t values
(1, 20, '20120101' ),
(1, 21, '20120101' ),
(2, 30, '20120201'),
(3, 40, '20120201'),
(3, 41, '20120301')

select x,y, date, maxy, miny from
(
  select *, max(date) over (partition by x) maxdate, 
  min(date) over (partition by x) mindate
  from @t
) a
where mindate <> maxdate