我有一个包含一列地址的表。要在报告中使用,我需要按位置对数据进行排序,即N,NW,S,SE,W和称为State的分隔符。这些并不总是在该领域的最后。
SELECT
Event.EventID,
Event.EventDateTime,
SUBSTRING(RIGHT(RTRIM(Event.Location),2), 1, 2) AS Loc,
Event.Location
FROM Event AS Event
WHERE Event.EventDateTime BETWEEN '12/11/2014' AND '12/12/2014'
AND Event.Location LIKE '% NW %'
ORDER BY Event.EventDateTime
这会给我
ALTIMONT DR NW& CASCADE DR NW
但我也需要
5765商业街道STE 170,地铁三明治
答案 0 :(得分:1)
根据您当前的条件,您只需OR
。
WHERE Event.EventDateTime BETWEEN '12/11/2014' AND '12/12/2014'
AND (Event.Location LIKE '% NW %'
OR Event.Location LIKE '% SE %'
OR Event.Location LIKE '% S %'
OR Event.Location LIKE '% W %')
ORDER BY Event.EventDateTime
注意括号将OR
子句分组为一个。
此外,一个简单的案例陈述可以为您提供方向,无论位置如何:
SELECT
Event.EventID,
Event.EventDateTime,
case when CHARINDEX (' NW ', event.location) > 0
then SUBSTRING(Event.Location, CHARINDEX (' NW ', event.location) + 1, 2)
when CHARINDEX (' SE ', event.location) > 0
then SUBSTRING(Event.Location, CHARINDEX (' SE ', event.location) + 1, 2)
when CHARINDEX (' S ', event.location) > 0
then SUBSTRING(Event.Location, CHARINDEX (' S ', event.location) + 1, 1)
when CHARINDEX (' W ', event.location) > 0
then SUBSTRING(Event.Location, CHARINDEX (' W ', event.location) + 1, 1)
end AS Loc,
Event.Location
FROM Event AS Event WHERE Event.EventDateTime BETWEEN '12/11/2014' AND '12/12/2014'
AND (Event.Location LIKE '% NW %'
OR Event.Location LIKE '% SE %'
OR Event.Location LIKE '% S %'
OR Event.Location LIKE '% W %')
ORDER BY Event.EventDateTime
SQL Server没有本机正则表达式分组,或者这可以简化。