2013-10-11 26 views
0

我正在第三次嘗試解決這個問題!交叉連接以計算日期的值

試圖顯示有多少假期是每個日曆日期「活」。

目前,我有日曆日期表,另一個節日。我已經加入他們使用外部,因爲沒有什麼可以加入兩個表。那就是4000個日期x 200,000個假期,哎!

以下運行的年齡時選擇,以排名前10位是不是前進的方向......(SQL Server)的

SELECT top 10 

C.CalendarDate, 

Case when B.Depart <= C.CalendarDate and vwR.ReturnDate > C.CalendarDate then Count (B.ID) end as 'count' 

FROM Calendar C 
CROSS JOIN Booking B -- my issue!! 
LEFT join vwReturnDate vwR on vwR.ID=B.ID -- bring in the return date 
AND C.CalendarDate > '2013-10-01' 
AND C.CalendarDate < '2013-10-30' -- narrow to October only 

Group by C.CalendarDate, B.ID, B.depart, vwR.ReturnDate 

order by c.CalendarDate 

回答

1

像這樣的事情?

select 
    calendarDate, COUNT(distinct bookings.id) 
from calendarDate 
    left join 
     (
      select 
      booking.id, 
      booking.depart, 
      vwReturnDate.returndate 
      from booking 
      left join vwReturnDate on booking.id = vwReturnDate.id 
     ) bookings 
      on calendarDate.calendarDate between bookings.depart and bookings.returndate 
where calendarDate between '2013-10-01' and '2013-10-31' 
group by calendarDate 
+0

天才!真的很感謝這@podiluska – Mike