我有两个数据表 TAB1。
------------------------------------------------------------
compid | user_id | compdate | description |
------------------------------------------------------------
C0001 | U000001 | 2012-02-29 | desc1 |
C0002 | U000002 | 2012-02-29 | desc1 |
C0003 | U000001 | 2012-03-01 | desc1 |
C0004 | U000003 | 2012-03-01 | desc1 |
C0005 | U000001 | 2012-03-02 | desc1 |
C0006 | U000008 | 2012-03-02 | desc1 |
C0007 | U000212 | 2012-03-02 | desc1 |
C0008 | U010222 | 2012-03-02 | desc1 |
C0009 | U000091 | 2012-03-02 | desc1 |
C0010 | U010222 | 2012-03-02 | desc1 |
------------------------------------------------------------
TAB2。
------------------------------------------------------------
compid | assigned_to| assignedon | status |
------------------------------------------------------------
C0001 | U000101 | 2012-02-29 | Closed |
C0002 | U000101 | 2012-02-29 | Open |
C0003 | U000102 | 2012-03-02 | Closed |
C0004 | U000102 | 2012-03-02 | Closed |
C0005 | U000101 | 2012-03-02 | Open |
C0006 | U000101 | 2012-03-02 | Closed |
C0008 | U000101 | 2012-03-02 | Closed |
------------------------------------------------------------
现在我想要的是:
所有记录的Status = 'Open'
以及来自tab1
的记录的记录均不在tab2
。
查询应该获取compdate = '2012-03-02'
。
我尝试的是:
select
from tab1 a
left join dbo.tab2 b
on a.CompId = b.CompId
where b.StatusFlag = 'Open'
and a.CompDate = CONVERT(nvarchar(30),Dateadd(day,-1,getdate()),106)
预期结果:
---------------------------------------------------------------------------------------
compid | user_id | compdate |description |assigned_to | assignedon |status|
---------------------------------------------------------------------------------------
C0005 | U000001 | 2012-03-02 | desc1 | U000101 | 2012-03-02 | open |
C0009 | U000001 | 2012-03-02 | desc1 | Null | NULL | null |
C0010 | U000001 | 2012-03-02 | desc1 | null | null | null |
----------------------------------------------------------------------------------------
答案 0 :(得分:3)
Select *
From
Tab1
Left Join
Tab2
on
Tab1.CompID = Tab2.CompID
Where
(Tab2.Status = 'open' or
Tab2.Status is null) and
Tab1.CompDate = '2012-03-02'
答案 1 :(得分:0)
这是你想要选择的吗?
select * from tab2 t2
left join tab1 t1 on t1.compid = t2.compid
where t2.[status] = 'Open' and
t1.compdate in ( select compdate from tab1 except
select assignedon from tab2)
and t1.compdate = '20120302'
答案 2 :(得分:0)
我理解您正在寻找数据的联合:所有状态记录都是tab1中不存在的tab1中的Open union
记录。这将是该查询:
select * from (
select t1.compid, t1.user_id, t1.compdate from tab1 t1
left join tab2 t2 on t1.compid = t2.compid
where t2.compid is null
union
select compid, assigned_to, assignedon from tab2
where statusflag = 'Open'
) t
where compdate = '2012-03-02'