2014-07-26 34 views
0

喜的朋友,我有小疑問在SQL Server 在這裏,我根據病情需要數據 相同的ID和status等於當時的那個日期值是 如何寫的查詢在SQL Server如何與檢查日期記錄FDATE和tdate範圍在SQL Server

表:EMP

id |status  |date(mm-dd-yy) |fdate(mm-dd-yy) |tdate(mm-dd-yy) 
1 | S   |03-16-11  |     | 
1 | b   |    | 03-15-11  |03-18-11 
1 | s   |03-17-11  |     | 
1 | b   |    | 04-20-12  |04-30-12 
1 | S   |04-20-12  |     | 
1 | s   |04-10-12  |     | 
1 | s   |10-01-14  |     | 
1 | b   |    |10-02-14   |10-25-14 
2 | s   |01-18-12  |     | 
2 | b   |    |01-18-12   |01-28-12 
2 | b   |    |03-10-13   |03-24-13 
2 | s   |03-16-13  |     | 
2 | s   |03-10-13  |     | 
2 | s   |03-23-13  |     | 
2 | b   |    |04-20-13   |04-27-13 
2 | s   |07-01-14  |     | 

表(狀態= S,ID,日期),狀態= b,相同的ID號和日期(從狀態的約會值)進行比較日期範圍爲日期和時間。 如果在範圍內,那麼計費是其他明智的賬單沒有

輸出像

id |status  |date(mm-dd-yy) |fdate(mm-dd-yy) |tdate(mm-dd-yy) |Billing 
1 | S   |03-16-11  |     |     |yes 
1 | s   |03-17-11  |     |     |yes 
1 | S   |04-20-12  |     |     |yes 
1 | s   |04-10-12  |     |     |no 
1 | s   |10-01-14  |     |     |no 
2 | s   |01-18-12  |     |     |yes 
2 | s   |03-16-13  |     |     |yes 
2 | s   |03-10-13  |     |     |yes 
2 | s   |03-23-13  |     |     |yes 
2 | s   |07-01-14  |     |     |no 

數據我試圖像下面

select * 
from (select * from emp a where status ='s') a 
inner join (select * from emp b where status='b') b 
    on a.pn=b.pn 
where a.date<=b.date1 and a.date>=b.date2 

它不是給exactely結果查詢。 請告訴我如何在sql server中編寫查詢。

回答

0

嘗試

select a.Id, 
     a.status, 
     a.date, 
     a.fdate, 
     a.tdate, 
     max(IsNull(case when a.date between b.fDate and b.tDate 
     then 'yes' 
     else 'no' 
     end, 'no')) Billing 
from emp a 
left join emp b 
    on a.Id=b.Id 
where a.status ='s' 
    and b.status = 'b' 
group by a.Id, 
     a.status, 
     a.date, 
     a.fdate, 
     a.tdate 

一些問題/評論:

  • 哪些字段:pndate1date2
  • date1在您的查詢中,我猜大於date2