我有兩個表reports
和holidays
。mysql中的複雜查詢
reports
:(username varchar(30),activity varchar(30),hours int(3),report_date date)
holidays
:(holiday_name varchar(30), holiday_date date)
select * from reports
給
+----------+-----------+---------+------------+
| username | activity | hours | date |
+----------+-----------+---------+------------+
| prasoon | testing | 3 | 2009-01-01 |
| prasoon | coding | 4 | 2009-01-03 |
| gautam | coding | 1 | 2009-01-05 |
| prasoon | coding | 4 | 2009-01-06 |
| prasoon | coding | 4 | 2009-01-10 |
| gautam | coding | 4 | 2009-01-10 |
+----------+-----------+---------+------------+
select * from holidays
給
+--------------+---------------+
| holiday_name | holiday_date |
+--------------+---------------+
| Diwali | 2009-01-02 |
| Holi | 2009-01-05 |
+--------------+---------------+
當我用下面的查詢
SELECT dates.date AS date,
CASE
WHEN holiday_name IS NULL THEN COALESCE(reports.activity, 'Absent')
WHEN holiday_name IS NOT NULL and reports.activity IS NOT NULL THEN reports.activity
ELSE ''
END
AS activity,
CASE WHEN holiday_name IS NULL THEN COALESCE(reports.hours, 'Absent')
WHEN holiday_name IS NOT NULL and reports.hours IS NOT NULL THEN reports.hours
ELSE ''
END
AS hours,
CASE
WHEN holiday_name IS NULL THEN COALESCE(holidays.holiday_name, '')
ELSE holidays.holiday_name
END
AS holiday_name
FROM dates
LEFT OUTER JOIN reports ON dates.date = reports.date
LEFT OUTER JOIN holidays ON dates.date = holidays.holiday_date
where reports.username='gautam' and dates.date>='2009-01-01' and dates.date<='2009-01-10';
我得到了以下輸出
+----------+-----------+---------+------------+
| date | activity | hours | holiday |
+----------+-----------+---------+------------+
|2009-01-05| coding | 1 | Holi |
+----------+-----------+---------+------------+
|2009-01-10| coding | 4 | |
+----------+-----------+---------+------------+
,但我預計今年
+----------+-----------+---------+------------+
| date | activity | hours | holiday |
+----------+-----------+---------+------------+
|2009-01-01| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-02| | | Diwali |
+----------+-----------+---------+------------+
|2009-01-03| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-04| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-05| Coding | 1 | Holi |
+----------+-----------+---------+------------+
|2009-01-06| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-07| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-08| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-09| Absent | Absent | |
+----------+-----------+---------+------------+
|2009-01-10| Coding | 4 | |
+----------+-----------+---------+------------+
如何修改上面的查詢以獲得所需的輸出(用於特定用戶(高塔姆在這種情況下))?
編輯
我也有一個表dates(date date)
包含所有2009-01-01
之間的日期2020-12-31
你也有第三個表'日期'。現在我可以猜測這個表的表格結構和內容,但爲了完整性,您可能應該將其添加到問題中。 – 2010-06-06 18:53:33
@mark:謝謝.....編輯:) – Satish 2010-06-06 18:57:02