我尝试进行查询,以显示所有工作时间,日期和人员。 我有那种奔跑。
我有一张名为uren的表:
rec_id | user_id | start (datetime) | eind (datetime)
我有一个名为users的表
user_id | name |
通过下面的查询,我几乎拥有了我想要的所有信息。
select users.name, sec_to_time(SUM(TIME_TO_SEC(TIMEDIFF(uren.eind, uren.start)))),count(distinct(date(start))) as dagen
from uren, users
where date(uren.start) between CAST('2017-10-04 00:00:00' as Date) and CAST('2017-11-04 00:00:00' as DATE) and
uren.user_id = users.user_id
group by uren.user_id
ORDER BY name
向我展示了这个
Piet (name) 230 (hours total) 24(days worked)
现在出现了真正的问题:
我希望每工作一天少于5小时减去30分钟。
我无能为力。 请帮助
答案 0 :(得分:0)
假设每个用户每天一行:
select users.name,
(sec_to_time(sum(time_to_sec(timediff(uren.eind, uren.start))) -
30 * 60 * sum(time_to_sec(timediff(uren.eind, uren.start)) < 5*60*60)
)
),
count(distinct(date(start))) as dagen
from uren join users
on uren.user_id = users.user_id
where date(uren.start) between '2017-10-04' and '2017-11-04'
group by uren.user_id
order by name;
如果有一天有多班,您需要先按天聚合:
select u.name,
(sec_to_time(sum(day_secs) -
30 * 60 * sum(day_secs < 5*60*60)
)
),
count(*) as dagen
from (select uren.user_id, uren.name, date(uren.start),
sum(time_to_sec(timediff(uren.eind, uren.start))) as day_secs
from uren join
users
on uren.user_id = users.user_id
where uren.start >= '2017-10-04' and uren.start < '2017-11-05'
group by uren.user_id, date(uren.start)
) u
group by name
order by name
答案 1 :(得分:0)
有一个很好的理由,你没有线索。这是因为你所要求的是相当复杂的。
你需要接受的第一件事(我的意思是绝望地接受)是你的功能取决于天和用户,因此,你需要两者一组,一开始,然后只有最终结果的用户。为此,您需要一个按天和用户分组的子查询,然后父母可以按用户进行分组。
这是我想出的......
SELECT
users.name,
sec_to_time(SUM(ur.timeWorked)) as tWorked,
SUM(ur.dagen) as Dagen
FROM users
INNER JOIN (
SELECT
user_id,
SUM(TIME_TO_SEC(TIMEDIFF(`eind`, `start`))) - (1800 *
IF(SUM(TIME_TO_SEC(TIMEDIFF(`eind`, `start`))) < 18000,1,0))
as `timeWorked`,
count(distinct(date(`start`))) as `dagen`
FROM uren
WHERE date(`start`)
BETWEEN CAST('2017-10-04 00:00:00' as Date)
AND CAST('2017-11-04 00:00:00' as DATE)
GROUP BY user_id, DAYOFYEAR(`start`)
) as ur ON ur.user_id = users.user_id
GROUP BY ur.user_id
ORDER BY name