查询处理表的2个或更多记录的比较

时间:2016-04-18 07:19:01

标签: sql

我想在sql中比较2行或更多行。

我有一张桌子id。它有主键列id2。它还有2列,startdateid

我想找到startdateid2的{​​{1}}不同的所有id2id只是id的扩展。

例如:如果123id2,则123-1为{{1}}。

更新:根据OP的评论示例

如果表有

id      id2   startdate 
123-1   123   0408 
123           0408 
124           0508 
124-1   124   0608 

查询应显示

id      id2   startdate 
124           0508 
124-1   124   0608 

其中startdate不同。

1 个答案:

答案 0 :(得分:0)

您正在查找存在其他记录的记录,其中包含不同的startdate:

select *
from mytable
where exists
(
  select *
  from mytable other
  where (other.id = mytable.id2 or other.id2 = mytable.id)
  and other.startdate <> mytable.startdate
);
相关问题