我试图查询特定的时间范围:
即。 3/1/2014 - 09/31/2014 between 15:30 - 18:30 each day Tues/Wed/Thurs only
我已经看到您可以获取特定范围的数据,但仅限于开始结束,这是非常具体的。 DATEPART
只允许一个时间元素,我没有看到任何可以直接帮助我的SQL Server命令,所以其他人是否有任何想法如何形成这个?
谢谢!
SELECT *
FROM [Order]
WHERE CustomerId = [Customer].Id
AND BusinessDate BETWEEN '2014-03-01' AND '2014-09-31'
AND DATEPART(HOUR, FirstSendTime) >= 15
AND DATEPART(HOUR, FirstSendTime) <= 18
答案 0 :(得分:0)
SELECT * FROM [Order]
WHERE CustomerId = [Customer].Id
AND BusinessDate BETWEEN '2014-03-01' AND '2014-09-31'
AND (
DATEPART(HOUR, FirstSendTime) IN (16, 17)
OR (DATEPART(HOUR, FirstSendTime) = 15 AND DATEPART(MINUTE, FirstSendTime) >= 30)
OR (DATEPART(HOUR, FirstSendTime) = 18 AND DATEPART(MINUTE, FirstSendTime) <= 30)
)
AND DATEPART(WEEKDAY, FirstSendTime) BETWEEN 3 AND 5
答案 1 :(得分:0)
范围15:30 - 18:30
的几种方式:
DATEPART(HOUR, FirstSendTime)*60+DATEPART(MINUTE, FirstSendTime) between 15*60+30 and 18*60+30
LEFT(CONVERT(TIME, FirstSendTime, 114), 5) between '15:30' and '18:30'
CONVERT(CHAR(5), FirstSendTime, 114) between '15:30' and '18:30'
范围Tues/Wed/Thurs
的几种方式:
DATEPART(WEEKDAY, FirstSendTime) BETWEEN 3 AND 5
DATENAME(WEEKDAY, FirstSendTime) in ('Tuesday','Wednesday','Thursday')
答案 2 :(得分:0)
下面是一种方法,假设您的样本查询中没有包含Customer表。这可能比将函数应用于Orders表的datetime列要好。
WITH
t4 AS (SELECT n FROM (VALUES(0),(0),(0),(0)) t(n))
, t1k AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS num FROM t4 AS a CROSS JOIN t4 AS b CROSS JOIN t4 AS c CROSS JOIN t4 AS d CROSS JOIN t4 AS e)
, time_ranges AS (
SELECT
DATEADD(minute, (15*60)+30, DATEADD(day, num, '2014-03-01')) AS start_time
, DATEADD(minute, (18*60)+30, DATEADD(day, num, '2014-03-01')) AS end_time
FROM t1k
WHERE
num <= DATEDIFF(day, '2014-03-01', '2014-09-30')
AND DATENAME(weekday, DATEADD(day, num, '2014-03-01')) IN ('Tuesday', 'Wednesday', 'Thursday')
)
SELECT *
FROM dbo.[Order]
JOIN dbo.Customer ON Customer.Id = [Order].CustomerId
CROSS JOIN time_ranges
WHERE
[Order].BusinessDate BETWEEN start_time AND end_time;