SQL Server 2008根据列值选择表的所有列+同一表中的列

时间:2017-03-20 06:45:28

标签: sql sql-server sql-server-2008

我有一个带有复合键docId的表VERSION,verId:

docId   verId   apprvDt      old_verId   
------  ------  -----------  ----------
A       3       03/20/2017   2
A       2       03/18/2017   1
A       1       03/16/2017   null
B       1       03/18/2017   null
C       2       03/20/2017   1
C       1       03/16/2017   null

假设我选择docId = A,verId = 3,查询应返回

docId   verId   apprvDt      old_verId   old_apprvDt
------  ------  -----------  ----------  ------------
A       3       03/20/2017   2           03/18/2017

即检索old_verId的apprvDt。

我试过这个

select a.docId, a.verId, a.apprvDt, a.old_verId, b.old_apprvDt  
from VERSION as a left join 
   (select x.docId, x.verId, x.apprvDt as old_apprvDt from REVISN as x 
    where x.docId = 'A' and x.verId = a.old_verId) as b
on b.docId = a.docId and b.verId = a.old_verId

但是我遇到了多部分绑定错误。

我想从VERSION中选择一行,包括old_verId的apprvDt(old_apprvDt)

2 个答案:

答案 0 :(得分:0)

select t1.*,
      b.apprvdt as old_apprvdt
from table1 t1
cross apply
(
select apprvdt from table1 t2 where t1.docid=t2.docid  
and t2.old_verid =t1.verid ) b

答案 1 :(得分:0)

您的问题的解决方案如下:

DECLARE @tbl TABLE(docId varchar(100),  verId int,  apprvDt datetime,  old_verId int)
insert into @tbl values('A',       3 ,      '03/20/2017',   2)
insert into @tbl values('A',       2 ,      '03/18/2017',   1)
insert into @tbl values('A',       1 ,      '03/16/2017',   NULL)
insert into @tbl values('B',       1 ,      '03/18/2017',   NULL)
insert into @tbl values('C',       2 ,      '03/20/2017',   1)
insert into @tbl values('C',       1 ,      '03/16/2017',   NULL)
select * from @tbl

;with data_table
as
(
select docId,verId,apprvDt,old_verId,
(select apprvDt from @tbl T2 where T2.docId=t1.docid and     T2.verId=t1.old_verId) 
old_apprvDt from @tbl t1
)
select * from data_table where docId='A' and verId=3

结果如下:

-------------------------------------------------------------------------------------
docId       verId   apprvDt                     old_verId       old_apprvDt
-------------------------------------------------------------------------------------
    A       3       2017-03-20 00:00:00.000     2                2017-03-18    00:00:00.000