我正在使用下面的查询来生成报告。我需要生成报告,因此它仅适用于最大时间戳(例如直到昨天,2016-08-02)。为此,我需要修改查询的第二行,以便我不再获得eventsink.blueboxevent.created大于昨天限制的值。
例如,如果我在下面的示例数据上运行报告,要求只查看截至昨天 (2016-08-02) 的时间范围,我希望看到如下记录:
想要的结果
device1 | 2016-08-02
Run Code Online (Sandbox Code Playgroud)
样本数据
DeviceID | eventsink.blueboxevent.created
device1 | 2016-08-03
device1 | 2016-08-02
device1 | 2016-08-01
Run Code Online (Sandbox Code Playgroud)
要修改的当前查询
SELECT eventsink.blueboxevent.deviceid AS 'Device ID',
Max(eventsink.blueboxevent.created) AS 'Last Connection',
provisioned,
Max(softwareversion) AS 'S/W Ver.',
buildingname AS 'Name',
buildingaddr1 AS 'Address',
buildingcity AS 'City',
buildingstate AS 'State',
zipcode AS 'Zip Code',
countrycode AS 'Cnty'
FROM eventsink.blueboxevent
JOIN md.elevator
ON md.elevator.deviceid = eventsink.blueboxevent.deviceid
JOIN eventsink.blueboxmasterdataevent
ON eventsink.blueboxmasterdataevent.deviceid =
eventsink.blueboxevent.deviceid
JOIN (SELECT Min(eventenqueuedutctime) AS 'Provisioned',
deviceid
FROM eventsink.blueboxevent
WHERE id = '1'
GROUP BY deviceid) t
ON eventsink.blueboxevent.deviceid = t.deviceid
WHERE ( id = '9'
AND softwareversion LIKE '[1-2][.]%' )
GROUP BY eventsink.blueboxevent.deviceid,
provisioned,
buildingname,
buildingaddr1,
buildingcity,
buildingstate,
zipcode,
countrycode
ORDER BY provisioned DESC
Run Code Online (Sandbox Code Playgroud)
ype*_*eᵀᴹ 10
改变:
MAX(created)
Run Code Online (Sandbox Code Playgroud)
用一个CASE表达式:
MAX(CASE WHEN created <= '2015-12-31' THEN created ELSE NULL END)
Run Code Online (Sandbox Code Playgroud)
在ELSE NULL不需要,因为它是默认的。现在,如果您想返回,'2015-12-31以防在阈值日期之前没有日期,我们可以使用ISNULL()或COALESCE:
COALESCE( MAX(CASE WHEN created <= '2015-12-31' THEN created END), '2015-12-31' )
Run Code Online (Sandbox Code Playgroud)
或者,如果在这种情况下,您想要下一个可用日期,即使它大于阈值日期:
COALESCE( MAX(CASE WHEN created <= '2015-12-31' THEN created END), MIN(created) )
Run Code Online (Sandbox Code Playgroud)
注意:答案假定created是 a DATE(或DATETIME没有时间部分的 a)。如果它确实有时间部分,我建议你替换使用<=with <(即替换<= '2015-12-31'with < '2016-01-01')。在 Aaron Bertrand 的博客文章中查看对包含边界问题的详细解释:What do and the evil have inclusive ?BETWEEN