我正在尝试根据预定义的日期(截止日期)生成报告。我有两个表,进出表和加班表。
IN和OUT表
加班表
预期结果
使用UNION,它会使日期加倍,但这可以通过group by解决,但是组似乎不能在UNION中工作。
最棘手的部分是展示BLANK 6月1日和1月5日。我需要向他们展示一份时间表报告。
非常感谢任何帮助或线索
CODE:
SELECT emp_id,in,out,null
FROM normal
WHERE date >= '1-Jan'
AND date <= '10-Jan'
AND emp_id = '10001'
UNION
SELECT emp_id,null,null,minutes
FROM overtime
WHERE date >= '1-Jan'
AND date <= '10-Jan'
AND emp_id = '10001'
答案 0 :(得分:1)
这样的事情应该做你想要的(如果我理解这个问题):
SELECT n.date, n.emp_id, n.in, n.out, o.minutes
FROM normal n
JOIN overtime o USING(emp_id)
WHERE n.date BETWEEN '2012-01-01' AND '2012-01-10'
请记住,如果您想显示没有匹配的日期,您必须创建一个包含此日期列表的表格:
+------------+
| timestamp |
|------------+
| 2012-01-01 |
| 2012-01-02 |
| .... |
然后您可以通过这种方式更改查询以获得所需的结果集:
SELECT d.timestamp AS date, b.emp_id, b.in, b.out, b.minutes
FROM dates d
LEFT JOIN
(SELECT n.date AS timestamp, n.emp_id AS emp_id, n.in AS in, n.out AS out, o.minutes AS minutes
FROM normal n
JOIN overtime o USING(emp_id)
) b
USING(timestamp)
WHERE d.timestamp BETWEEN '2012-01-01' AND '2012-01-10'
如果你想避免使用这个更复杂的查询的日期表,应该给你相同的结果,而不需要存储日期范围的第三个表:
SELECT d.timestamp AS date, b.emp_id, b.in, b.out, b.minutes
FROM (
SELECT '2012-01-01' + INTERVAL a + b DAY AS timestamp
FROM
(SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9 ) d,
(SELECT 0 b UNION SELECT 10 UNION SELECT 20
UNION SELECT 30 UNION SELECT 40) m
WHERE '2012-01-01' + INTERVAL a + b DAY < '2012-01-11'
ORDER BY a + b
) d
LEFT JOIN
(SELECT n.date AS timestamp, n.emp_id AS emp_id, n.in AS in, n.out AS out, o.minutes AS minutes
FROM normal n
JOIN overtime o USING(emp_id)
) b
USING(timestamp)