时间范围-Sql
请帮助我解决我的问题。因此,我有一个名为“RATES”的表,其中包含以下列:
id (int)
rate (money)
start_time (datetime)
end_time(datetime)
示例数据:
1 150 8:00am 6:00pm
2 200 6:00pm 4:00am
3 250 8:00am 4:00am (the next day)
我要做的就是选择给定时间所在的所有 id。
例如给定时间:晚上 9:00,输出应该是 2,3
问题是我得到的时间范围是早上 8 点到第二天凌晨 4 点,我不知道该怎么办。请帮忙!预先感谢:D
please help me with my problem. So, I have a table named 'RATES' which contains these columns:
id (int)
rate (money)
start_time (datetime)
end_time(datetime)
example data:
1 150 8:00am 6:00pm
2 200 6:00pm 4:00am
3 250 8:00am 4:00am (the next day)
What I have to do is to select all the id(s) to where a given time would fall.
e.g given time: 9:00 pm, the output should be 2,3
The problem is I got this time range between 8am to 4am the next day and I don't know what to do. Help, please! thanks in advance :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设 @Andriy M 是正确的:
end_time
<=start_time
则数据的跨度不会超过 24 小时end_time
属于第二天then what you're looking for is this:
Assuming that @Andriy M is correct:
end_time
<=start_time
thenend_time
belongs to the next daythen what you're looking for is this:
我从来没有真正使用过 MS SQL,但这也许会有所帮助。
我本来打算建议这样的事情,但是按照你设置数据的方式,这会失败。
<代码>
从价格中选择 ID
其中 datepart(hh, start_time) <= 9 AND datepart(hh, end_time) >= 9;
如果您希望获得正确的数据,您将需要使用实际日期进行搜索。
<代码>
从价格中选择 ID
WHERE start_time <= '2011-1-1 9:00' AND end_time >= '2011-1-1 9:00';
这可能不完全正确,但它可能会帮助您寻找正确的方向。
I don't really ever use MS SQL, but maybe this will help.
I was going to suggest something like this, but by the way you have your data set up, this would fail.
SELECT id FROM RATES
WHERE datepart(hh, start_time) <= 9 AND datepart(hh, end_time) >= 9;
You'll have you search using the actual date if you expect to get the correct data back.
SELECT id FROM RATES
WHERE start_time <= '2011-1-1 9:00' AND end_time >= '2011-1-1 9:00';
This may not be exactly correct, but it may help you look in the right direction.
我想@gbn 不会帮助你。我将尝试填写。
给定一个名为 timedata 的表,其范围最多只超过一天。
这利用了 CTE 和截断日期时间值的技巧。要了解此技巧,请阅读以下问题和答案:在 SQL Server 中计算日期
以下是此查询的概述:
创建一个规范化表,其中每个时间跨度仅超过一天
。然后,对于跨越两天的每个条目,加入
选择
最后,您使用此标准化表上的小时指示器执行选择。
如果您的范围超过一天,您将需要使用递归 CTE 来获取相同的标准化表。
I guess @gbn is not going to help you. I will try and fill in.
Given -- a table called timedata that has ranges only going over at most one day
This makes use of a CTE and a trick to truncate datetime values. To understand this trick read this question and answer: Floor a date in SQL server
Here is an outline of what this query does:
Create a normalized table with each time span only going over one day by
Then for each entry that spans two days joining in
and
Finally you perform the select using the hour indicator on this normalized table.
If your ranges go over more than one day you would need to use a recursive CTE to get the same normalized table.