按星期几和一天中的小时对 SQL 进行排序/分组
我有一个 SQL Server 2005 表,其中包含带有 UTC/GMT 日期字段的记录。 我需要按“星期几”和“一天中的小时”对记录进行分组和排序。给出7*24=168组。输出看起来像:
Sun 12am
Sun 1am
Sun 2am
.... etc
Mon 12am
Mon 1am
.... etc
.... etc
Sat 10pm
Sat 11pm
一切正常,直到我尝试将内容转换为我的本地时区。 在 SQL 中进行转换:
SELECT MIN(Key),MIN(SavedOn),
FROM MyTable
GROUP BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn) - (5.0/24.0)
ORDER BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn) - (5.0/24.0)
或者在排序/获取 UTC 中的记录后在我自己的代码中进行转换:
SELECT MIN(Key),MIN(SavedOn),
FROM MyTable
GROUP BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn)
ORDER BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn)
(my own math here)
无论哪种方式...... 5 条记录将显示为“乱序”。周末记录(周六下午) 出现在一周的开始......而不是结束......他们所属的地方。
知道我做错了什么吗?
I have a SQL Server 2005 table that contains records with a UTC/GMT date field.
I need to have the records GROUPed BY and ORDERed by the "day of the week" and "hour of the day". Giving 7*24=168 groups. The output would look like:
Sun 12am
Sun 1am
Sun 2am
.... etc
Mon 12am
Mon 1am
.... etc
.... etc
Sat 10pm
Sat 11pm
Everything works fine until I try to convert things to my local time zone.
Doing the conversion inside SQL:
SELECT MIN(Key),MIN(SavedOn),
FROM MyTable
GROUP BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn) - (5.0/24.0)
ORDER BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn) - (5.0/24.0)
Or doing the conversion in my own code AFTER sorting/getting the records in UTC:
SELECT MIN(Key),MIN(SavedOn),
FROM MyTable
GROUP BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn)
ORDER BY (DatePart(WEEKDAY, SavedOn)*24.0) + DatePart(HOUR, SavedOn)
(my own math here)
Either way... 5 records will appear "out of order". The end of the week records (Sat PM)
appear at the beginning of the week... not the end... where they belong.
Any idea on what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
浮点数学不精确。乘以
24.0
会导致边界错误。不是在两个字段上添加数字
排序:
Floating point math is imprecise. Multiplying by
24.0
invites border errors.Instead of adding the numbers
sort on two fields instead:
这就是我要做的。我不确定我完全理解你在尝试什么:
如果你的转换方法只是增加 5 小时,那么每次看到
SavedOn
时都这样做,如下所示:Here is what I would do. I am not sure I totally understand what you are trying though:
If your approach to converting is just to add 5 hours, then do it every time you see
SavedOn
, like this: