关于SQL行记录之间的匹配

izbox 2009-12-31 10:32:29
假如我有一个数据表
create table tb(a int,b int,c int)
insert into tb
select 1,2,3 union all
select 1,3,4

2条记录里面 我如何匹配这2行记录
找到第一行的b,c 2列与 第二行的 b,c 2列的内容不一样!
(紧急求助SOS)
...全文
130 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
izbox 2009-12-31
  • 打赏
  • 举报
回复
- - 是不是我表达不够清晰?

额,我的意思是,我有一个表,里面字段可能有20-30个。
我现在举个例子就是
假如有一张A表。
里面有记录为 1,2,3
现在我插入一条记录为B表。
这时候插入 1,3,4
然后我将A表主键为1的行与B表主键为1的行之间的列做个对比。
得出来结果是,B表的第二个字段修改前是2,修改后是3,第三个字段修改前是3,修改后是4
dawugui 2009-12-31
  • 打赏
  • 举报
回复
create table tb(a int,b int,c int) 
insert into tb
select 1,2,3 union all
select 1,3,4

select m.a ,m.b,m.c, n.b,n.c from
(
select * , px = (select count(1) from tb where a = t.a and (b<t.b or (b=t.b and c<t.c))) + 1 from tb t
) m ,
(
select * , px = (select count(1) from tb where a = t.a and (b<t.b or (b=t.b and c<t.c))) + 1 from tb t
) n
where m.a = n.a and m.px =1 and n.px = 2

drop table tb

/*
a b c b c
----------- ----------- ----------- ----------- -----------
1 2 3 3 4

(所影响的行数为 1 行)

*/
s_111111 2009-12-31
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 izbox 的回复:]
这样说吧,我就是表里有条记录。
如果我修改它了,我就记录那个字段被修改了。
[/Quote]
增加一個datetime時間類型字段,修改的時候把原先的數據UPDATE上時間,新增加一條沒有時間的記錄
只要查找沒有
izbox 2009-12-31
  • 打赏
  • 举报
回复
这样说吧,我就是表里有条记录。
如果我修改它了,我就记录那个字段被修改了。
s_111111 2009-12-31
  • 打赏
  • 举报
回复

select * from tb t
where exists(select 1 from tb where a=t.a and (b!=t.b and c!=t.c))
order by t.a

and 更接近意思吧
nianran520 2009-12-31
  • 打赏
  • 举报
回复
试试5楼[Quote=引用 6 楼 izbox 的回复:]
因为我这个表不止这3个字段。。。
或者有30个字段。或者有20个字段。

我要找个每个字段之间不一样的出来 就是
a b c
1 2 3
1 3 4
那我要的就是告诉你 第二行的,3,4做过改变。。。改变之间的值是2,3
[/Quote]
izbox 2009-12-31
  • 打赏
  • 举报
回复
实现的效果其实就是这样

select
case when a.a=b.a then 0 else b.a end,
case when a.b=b.b then 0 else b.b end,
case when a.c=b.c then 0 else b.c end
from tb as a,tb as b
where a.a=1 and b.b=2

但是这样的代码看上去可维护性太差了
izbox 2009-12-31
  • 打赏
  • 举报
回复
因为我这个表不止这3个字段。。。
或者有30个字段。或者有20个字段。

我要找个每个字段之间不一样的出来 就是
a b c
1 2 3
1 3 4
那我要的就是告诉你 第二行的,3,4做过改变。。。改变之间的值是2,3
nianran520 2009-12-31
  • 打赏
  • 举报
回复
select * from tb 
where a in
(select a from tb group by a having count(1) >= 2)
--小F-- 2009-12-31
  • 打赏
  • 举报
回复
select
*
from
tb t
where
exists(select 1 from tb where (a=t.a and b<>t.b) or (a=t.a and b<>t.b and c<>t.c))
izbox 2009-12-31
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wufeng4552 的回复:]
SQL codeselect*from tb twhereexists(select1from tbwhere a=t.aand (b!=t.bor c!=t.c))
[/Quote]

不是这个意思。。。
Mr_Nice 2009-12-31
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wufeng4552 的回复:]
SQL codeselect*from tb twhereexists(select1from tbwhere a=t.aand (b!=t.bor c!=t.c))
[/Quote]

楼上真快啊!
水族杰纶 2009-12-31
  • 打赏
  • 举报
回复
select * from tb t 
where exists(select 1 from tb where a=t.a and (b!=t.b or c!=t.c))

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧