我有一个timestamp变量作为输入,我想按周对数据进行分组,其中周定义为星期六21:00:00和星期六20:59:59之间。我正在从雪花数据库查询。
我的数据如下:
employee_id | shift_started_at | hours_worked
1 | '2018-09-12 08:00:00' | 2
2 | '2018-09-10 22:00:00' | 8
1 | '2018-09-18 08:00:00' | 3
我正在尝试这样的事情:
alter session set week_start = 6;
SELECT dateadd('hour',21,date_trunc('week',shift_started_at)) as week_starts_at,
min(shift_started_at) as first_shift_of_week,
max(shift_started_at) as last_shift_of_week,
sum(hours_worked)
FROM table
group by 1;
尽管该查询为我提供了Week_starts_at的正确日期,但min和max select语句显示group by语句忽略了dateadd函数。简而言之,我的周数是从星期六的午夜到午夜。关于如何更改date_trunc使用的默认时间戳的任何建议?谢谢!
答案 0 :(得分:0)
问题是您在按小时调整时间之前应用date_trunc(week..)
。一种解决方案是:
这是一个例子:
alter session set week_start = 7, timestamp_output_format='YYYY-MM-DD HH24:MI:SS DY';
create or replace table x(t timestamp);
insert into x values('2018-09-14 08:00:00'),('2018-09-15 20:59:59'),('2018-09-15 21:00:00'),('2018-09-16 23:00:00'), ('2018-09-22 20:59:59'),('2018-09-22 21:00:00');
select t, dateadd(hour, 3, t), date_trunc(week, dateadd(hour, 3, t)), dateadd(hour, -3, date_trunc(week, dateadd(hour, 3, t))) from x;
-------------------------+-------------------------+---------------------------------------+----------------------------------------------------------+
T | DATEADD(HOUR, 3, T) | DATE_TRUNC(WEEK, DATEADD(HOUR, 3, T)) | DATEADD(HOUR, -3, DATE_TRUNC(WEEK, DATEADD(HOUR, 3, T))) |
-------------------------+-------------------------+---------------------------------------+----------------------------------------------------------+
2018-09-14 08:00:00 Fri | 2018-09-14 11:00:00 Fri | 2018-09-09 00:00:00 Sun | 2018-09-08 21:00:00 Sat |
2018-09-15 20:59:59 Sat | 2018-09-15 23:59:59 Sat | 2018-09-09 00:00:00 Sun | 2018-09-08 21:00:00 Sat |
2018-09-15 21:00:00 Sat | 2018-09-16 00:00:00 Sun | 2018-09-16 00:00:00 Sun | 2018-09-15 21:00:00 Sat |
2018-09-16 23:00:00 Sun | 2018-09-17 02:00:00 Mon | 2018-09-16 00:00:00 Sun | 2018-09-15 21:00:00 Sat |
2018-09-22 20:59:59 Sat | 2018-09-22 23:59:59 Sat | 2018-09-16 00:00:00 Sun | 2018-09-15 21:00:00 Sat |
2018-09-22 21:00:00 Sat | 2018-09-23 00:00:00 Sun | 2018-09-23 00:00:00 Sun | 2018-09-22 21:00:00 Sat |
-------------------------+-------------------------+---------------------------------------+----------------------------------------------------------+
您可以用于分组的最后一列,并且一切正常。