我有sql查询,用于计算开始和结束时的分配小时数。
这是我的sqlfiddle
http://sqlfiddle.com/#!2/9f7634/1
SELECT `Nickname`, `taxemployee_id`, `taxemployee`.`id`, `taxemployee`.`Position`, COALESCE((datediff (`end`, `start`) + 1), 0) * `assigned_hours` as assigned_hours, start,end
FROM (`taxemployee`)
LEFT JOIN `project_staff_assignment` ON `project_staff_assignment`.`taxemployee_id` = `taxemployee`.`id`
AND start >= '2014-09-01' AND end <= '2014-09-15'
AND end <= '2014-09-15' AND start >= '2014-09-01'
GROUP BY `taxemployee`.`id`
ORDER BY `Nickname` ASC
查询显示2014-09-01至2014-09-15之间的所有记录。
如果我的记录显示Start值是2014-09-01 End是2014-09-30我不能在这些日期之间得到任何结果。
这是我的插入记录。
(7, 5, 'Senior2', 12, '7', '2014-09-01', '2014-09-30', 'active')
我需要在上面的查询中返回值。也许我的查询错了
答案 0 :(得分:0)
如果我理解正确的话,我想你想要与时期重叠。如果是这样,试试这个:
SELECT `Nickname`, sa.taxemployee_id, e.`id`, e.`Position`,
sum(datediff(least(end, date('2014-09-15')), greatest(start, date('2014-09-01'))) * assigned_hours) as assigned_hours,
start, end
FROM taxemployee e JOIN
project_staff_assignment sa
ON sa.`taxemployee_id` = e.`id` AND start <= '2014-09-15' AND end >= '2014-09-01'
GROUP BY e.`id`
ORDER BY `Nickname` ASC;
Here是SQL小提琴。
答案 1 :(得分:0)
让我们从这开始...
SELECT t.Nickname
, psa.taxemployee_id
, t.id
, t.Position
, psa.start
, psa.end
FROM taxemployee t
LEFT
JOIN project_staff_assignment psa
ON psa.taxemployee_id = t.id;
+----------+----------------+----+-----------------+------------+------------+
| Nickname | taxemployee_id | id | Position | start | end |
+----------+----------------+----+-----------------+------------+------------+
| Walter | NULL | 1 | Partner | NULL | NULL |
| Eric | NULL | 2 | Partner | NULL | NULL |
| Richard | NULL | 3 | Partner | NULL | NULL |
| Elaine | 4 | 4 | Senior Manager | 2014-08-18 | 2014-08-22 |
| Tan-tan | NULL | 5 | Senior Manager | NULL | NULL |
| Alvin | 6 | 6 | Senior Manager | 2014-08-01 | 2014-08-15 |
| Alvin | 6 | 6 | Senior Manager | 2014-08-18 | 2014-08-22 |
| | NULL | 7 | Senior Manager | NULL | NULL |
| Jackie | NULL | 8 | Manager 2 | NULL | NULL |
| Ayee | 9 | 9 | Manager 2 | 2014-08-01 | 2014-08-01 |
| Dan | 10 | 10 | Manager 2 | 2014-08-11 | 2014-08-15 |
| Acel | NULL | 11 | Manager 1 | NULL | NULL |
| Nim | 12 | 12 | Manager 1 | 2014-09-01 | 2014-09-30 |
| Joem | NULL | 13 | Asst. Manager 2 | NULL | NULL |
| Jen | NULL | 14 | Asst. Manager 2 | NULL | NULL |
| Joanne | 15 | 15 | Asst. Manager 2 | 2014-08-25 | 2014-08-29 |
| Berenice | NULL | 16 | Asst. Manager 1 | NULL | NULL |
+----------+----------------+----+-----------------+------------+------------+
现在,鉴于这个中间结果,期望的结果是什么样的?