tags:

views:

44

answers:

2

I have two tables reports and holidays.

reports: (username varchar(30),activity varchar(30),hours int(3),report_date date)

holidays: (holiday_name varchar(30), holiday_date date)

select * from reports gives

+----------+-----------+---------+------------+  
| username |  activity |  hours  |   date     |
+----------+-----------+---------+------------+  
| prasoon  |   testing |    3    | 2009-01-01 |
| prasoon  |   coding  |    4    | 2009-01-03 |  
| prasoon  |  designing|    2    | 2009-01-04 |
| prasoon  |   coding  |    4    | 2009-01-06 |
+----------+-----------+---------+------------+

select * from holidays gives

+--------------+---------------+  
| holiday_name |  holiday_date |
+--------------+---------------+ 
| Diwali       |   2009-01-02  |
| Holi         |   2009-01-05  |  
+--------------+---------------+

Is there any way by which I can output the following?

+-------------+-----------+---------+-------------------+  
| date        |  activity |  hours  |  holiday_name     |
+-------------+-----------+---------+-------------------+  
| 2009-01-01  |  testing  |    3    |                   |
| 2009-01-02  |           |         |     Diwali        |  
| 2009-01-03  |  coding   |    4    |                   |
| 2009-01-04  |  designing|    2    |                   |
| 2009-01-05  |           |         |      Holi         |
| 2009-01-06  |  coding   |    4    |                   |
+-------------+-----------+---------+-------------------+
+1  A: 
select * from 
     (select h.holdiday_date as date from holiday h 
      union 
      select r.date as date from reports r) dates 
left join holiday h1 on (h1.holiday_date = dates.date) 
left join reports r1 on (r1.date = dates.date) 
order by dates.date

In short you union the dates you have in a subquery, than left join to the two tables.

Anatoly Fayngelerin
+4  A: 
SELECT date,
       activity,
       hours,
       '' AS holiday_name
FROM   reports
WHERE  date >= '2008-12-1'
       AND date < '2009-1-4'
UNION
(SELECT holiday_date,
        '',
        '',
        holiday_name
 FROM   holidays
 WHERE  holiday_date >= '2008-12-1'
        AND holiday_date < '2009-1-4')
ORDER  BY date  
unutbu
Ahhh... I had half of it written... beat me to it! Nice job!
Senseful
@~unutbu: I tried to check the query between two specific dates but failed.... is there any way for it just by modifying the above query?
Radhe
@Radhe, yes, but you'd have to restrict both the `reports.date` and `holidays.holiday_date`. I'll edit my post to show what I mean.
unutbu