每周查询和总计
Query and total for each week
user, timeon, timeoff, hours
Monday -
1510, 2021-10-25 05:00:00, 2021-10-25 09:00:00 -
1510, 2021-10-25 14:00:00, 2021-10-25 17:00:00 -
总数应该是 4 + 3 = 7
Tuesday -
1510, 2021-10-25 05:00:00, 2021-10-25 09:00:00 -
1510, 2021-10-25 14:00:00, 2021-10-25 17:00:00 -
总数应为 4 + 3 = 7,然后在本周末总数
我每天都有一个用户、timeon、timeoff,因为它们可能不止一次打开和关闭。我的总数在底部datediff(minute, timeon, timeoff)
。我正在使用 Firebird 3.
我有一个虚拟机table
with M as
(
select user, timeon, timeoff, hours
from (select userid, timeon, timeoff,
datediff(minute,timeon, timeoff)/60.00 as hours
from sessions s
where extract(weekday from timeon)=1
and userID=1
and cast(logon as date)='2021-10-28')
)
select * from M
union all
select '','','',sum(hours) from M
现在,我需要重复上面的内容,但星期二,然后是星期三,依此类推。我不能从另一个 v table 或联合开始。我做错了什么?
正如请求评论中提到的,我们通常会使用ROLLUP
或GROUPING SETS
,但Firebird不支持这些。
改用 WITH
子句是个好主意。这是包含小计和最终总计的查询:
with s as
(
select
extract(weekday from timeon) as day,
userid, timeon, timeoff,
datediff(minute, timeon, timeoff) / 60.00 as hours
from sessions
-- where userid = 1
)
select * from s
union all
select day, userid, null, null, sum(hours) from s group by day, userid
union all
select day, null, null, null, sum(hours) from s group by day
union all
select null, null, null , null, sum(hours) from s
order by day nulls last, userid nulls last, timeon nulls last;
这并不准确,因为我们将从晚上 10 点到凌晨 2 点的会话计为开始日的四个小时,而不是开始日的 2 小时和第二天的 2 小时。但是你在查询中做了同样的事情,所以我想这对你来说没问题。
user, timeon, timeoff, hours
Monday -
1510, 2021-10-25 05:00:00, 2021-10-25 09:00:00 -
1510, 2021-10-25 14:00:00, 2021-10-25 17:00:00 -
总数应该是 4 + 3 = 7
Tuesday -
1510, 2021-10-25 05:00:00, 2021-10-25 09:00:00 -
1510, 2021-10-25 14:00:00, 2021-10-25 17:00:00 -
总数应为 4 + 3 = 7,然后在本周末总数
我每天都有一个用户、timeon、timeoff,因为它们可能不止一次打开和关闭。我的总数在底部datediff(minute, timeon, timeoff)
。我正在使用 Firebird 3.
我有一个虚拟机table
with M as
(
select user, timeon, timeoff, hours
from (select userid, timeon, timeoff,
datediff(minute,timeon, timeoff)/60.00 as hours
from sessions s
where extract(weekday from timeon)=1
and userID=1
and cast(logon as date)='2021-10-28')
)
select * from M
union all
select '','','',sum(hours) from M
现在,我需要重复上面的内容,但星期二,然后是星期三,依此类推。我不能从另一个 v table 或联合开始。我做错了什么?
正如请求评论中提到的,我们通常会使用ROLLUP
或GROUPING SETS
,但Firebird不支持这些。
改用 WITH
子句是个好主意。这是包含小计和最终总计的查询:
with s as
(
select
extract(weekday from timeon) as day,
userid, timeon, timeoff,
datediff(minute, timeon, timeoff) / 60.00 as hours
from sessions
-- where userid = 1
)
select * from s
union all
select day, userid, null, null, sum(hours) from s group by day, userid
union all
select day, null, null, null, sum(hours) from s group by day
union all
select null, null, null , null, sum(hours) from s
order by day nulls last, userid nulls last, timeon nulls last;
这并不准确,因为我们将从晚上 10 点到凌晨 2 点的会话计为开始日的四个小时,而不是开始日的 2 小时和第二天的 2 小时。但是你在查询中做了同样的事情,所以我想这对你来说没问题。