我有兩個數據表
tab1。sql加入查詢不起作用
------------------------------------------------------------
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 |
----------------------------------------------------------------------------------------
如果你想記錄狀態'打開'爲什麼你使用'!='? – bernie 2012-03-03 05:51:02
那麼問題是什麼?你是否得到一個錯誤或只是不是預期的結果? – 2012-03-03 05:51:54
看起來您正在選擇compdate在當前日期前兩天的行。如果你想要compdate是'2012-03-02'的行,你必須等到週日才能運行它。 – 2012-03-03 05:55:23