2

I am having a table structure like this

id             int
checkinttime   datetime
checkouttime   datetime
roomid         int

I have recorded checkin and checkout time in this table. My question is how to generate a datewise report that generate whether room occupied or not in that date range like this.

room  3/1/2016 3/2/2016 3/3/2016 6/4/2016
r1      P         V       V        P
r2      v          p      p        p

where p means Occupied, and V means vacant. How to write SQL for this.?

Thanks in advance.

This is the structure. customer select start date and end date. With that parameters, room and date wise details are needed.

siyadkk
  • 21
  • 3
  • you have another table for rooms, haven't you ? – Wajih Feb 27 '16 at 06:20
  • yes, there is a room table. roomid is foreign key.. – siyadkk Feb 27 '16 at 06:25
  • I think instead of making the date range as dynamic, use room id as columns and date tange as rows. – Utsav Feb 27 '16 at 06:26
  • you can refer to this link http://stackoverflow.com/questions/2157282/generate-days-from-date-range?lq=1 – Wajih Feb 27 '16 at 06:35
  • I'd suggest to 1) populate persistent table `calendar` 2) link `calendar` filtered by period range with `rooms` via cross join 3) `left join` checkin-checkout table 4) build pivoted table (with separate column per date) on client-side/frontend – Ivan Starostin Feb 27 '16 at 08:57

1 Answers1

2

A solution is to use a static query over rooms as columns like this:

;WITH dates(date) AS (
    SELECT @startDate
    UNION ALL
    SELECT DATEADD(DAY, 1, date)
    FROM dates
    WHERE date < @endDate
), occupied AS (
SELECT date, c.booking_id
FROM dates d
    LEFT JOIN  -- You can use `JOIN` only also to remove free dates
    CheckStatus c ON d.date BETWEEN c.checkin_time AND c.checkout_time
)
SELECT date
    , MIN(CASE WHEN id = 1 THEN 'P' ELSE 'V' END) AS 'r1'
    , MIN(CASE WHEN id = 2 THEN 'P' ELSE 'V' END) AS 'r2'
FROM occupied
GROUP BY date;

The result will be like this:

date       | r1 | r2 |
-----------+----+----+
2016-03-01 | P  | V  |
2016-03-02 | V  | P  |
2016-03-03 | V  | P  |
2016-03-04 | V  | P  |
shA.t
  • 16,580
  • 5
  • 54
  • 111