在SQL和ESRI定义查询中选择比两个日期/时间之一更近的记录

时间:2013-11-12 23:05:28

标签: sql sql-server esri

我是ESRI SQL用户 - 所以我的查询 开头:SELECT * FROM tablename WHERE

我有基于GPS的车辆记录(扫雪机)和日期/时间字段(称为时间日期),我需要A.)选择基于一个整数字段在前几个小时内发生的记录单独的表或B.)根据单独表中的日期/时间字段选择比日期/时间更新的记录。如果是案例A,则案例B中的字段将为空。如果是案例B,那么案例A中的字段将为0。

这是我为案例A撰写的内容。

SELECT * FROM myDataTable
WHERE(DATEDIFF(hh, TimeDate, GETDATE()) <= (select NumberofHours from myHoursControlTable where District = 2)
AND Fleet = 'District 2'
AND NOT [Speed] = 0
AND ([AssetDesc] LIKE  'Sander/Plow%' AND Input2On = 'On' AND Input1On = 'On')) 

这就是我为案例B所写的内容。

SELECT * FROM myDataTable
WHERE(TimeDate <= (select StartTime from myHoursControlTable where District = 2)
AND Fleet = 'District 2'
AND NOT [Speed] = 0
AND([AssetDesc] LIKE  'Sander/Plow%' AND Input2On = 'On' AND Input1On = 'On')) 

他们都工作,但有人可以帮我把它放在一起吗?当我尝试使用case语句时,我不断收到错误:“当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。”我也有限制必须以“Select *”开头,因为我在ESRI定义查询中这样做。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

很快就想到了。可能不是最优化的,但为什么不简单地使用OR?和

来和两个WHERE语句
SELECT * FROM myDataTable
WHERE(
(
(DATEDIFF(hh, TimeDate, GETDATE()) <= (select NumberofHours from myHoursControlTable where District = 2)
AND Fleet = 'District 2'
AND NOT [Speed] = 0
AND ([AssetDesc] LIKE  'Sander/Plow%' AND Input2On = 'On' AND Input1On = 'On')) 
)
OR
(
(TimeDate <= (select StartTime from myHoursControlTable where District = 2)
AND Fleet = 'District 2'
AND NOT [Speed] = 0
AND([AssetDesc] LIKE  'Sander/Plow%' AND Input2On = 'On' AND Input1On = 'On')) 
)

更新

由于A)和B)共享大量条件,您可以如下组合。这是理所当然的,你想要捕获符合A)或B)条件的行。

SELECT * FROM myDataTable
WHERE
  (    
    DATEDIFF(hh, TimeDate, GETDATE()) <= 
    (select NumberofHours from myHoursControlTable where District = 2)
  OR 
    TimeDate <= (select StartTime from myHoursControlTable where District = 2)
  )
AND Fleet = 'District 2'
AND NOT [Speed] = 0
AND ([AssetDesc] LIKE  'Sander/Plow%' AND Input2On = 'On' AND Input1On = 'On');