求个sql

lijian260 2013-10-18 08:25:19
表1

id itemname
1 i1
2 i2
3 i3

表2

id itemName iname
i1 a
i2 a
i2 b
得到:
i1 a
i2 a
i3 null
i1 null
i2 b
i3 null 不用存储过程用视图



...全文
117 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2013-10-18
  • 打赏
  • 举报
回复

create table 表1 
(id int,itemname varchar(10))

insert into 表1
 select 1,'i1' union all
 select 2,'i2' union all
 select 3,'i3'

create table 表2 
(id int,itemName varchar(10),iname varchar(10))

insert into 表2
 select 1,'i1','a' union all
 select 2,'i2','a' union all
 select 3,'i2','b'
 

select x.itemname,y.iname
from
(select a.itemname,
        row_number() over(partition by a.itemname order by getdate()) 'rn'
 from
 (select itemname from 表1 union all
  select itemname from 表1) a) x
left join
(select itemName,iname,row_number() over(partition by itemName order by getdate()) 'rn'
 from 表2) y on x.itemname=y.itemname and x.rn=y.rn
 
/*
itemname   iname
---------- ----------
i1         a
i1         NULL
i2         a
i2         b
i3         NULL
i3         NULL

(6 row(s) affected)
*/

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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