获取正确的SQL顺序

时间:2016-08-10 22:01:38

标签: sql sql-server

我有一个查询,按城市选择旅行,并希望首先按城市1,然后城市4的顺序排序。许多旅行存在于2个城市,因此数据库有2个字段,StartCity& StartCity2。此SQL生成错误的顺序: -

SELECT * FROM qryZZ WHERE (StartCity = 1 OR StartCity2 = 1 OR StartCity = 4
 OR StartCity2 = 4) Order By Case StartCity When 1 Then 1 When 4 Then 2 End

目前的结果是: -

 Trip  |StartCity|StartCity2
 Trip1 |    3   |    4
 Trip2 |    3   |    4
 Trip3 |    1   |  NULL
 Trip4 |    1   |  NULL
 Trip5 |    4   |  NULL
 Trip6 |    4   |    3

我想要的是首先使用StartCity或StartCity2 = 1的那些行程,然后使用StartCity或StartCity2 = 4.那么这一切都可能吗?

1 个答案:

答案 0 :(得分:4)

您需要在order by逻辑中包含这两列:

select *
from qryZZ
where StartCity in (1, 4) or StartCity2 in (1, 4)
order by (case when StartCity = 1 or StartCity2 = 1 then 1
               else 2
          end);

您可能还想将这两个城市分开:

order by (case when StartCity = 1 then 1
               when StartCity2 = 1 then 2
               when StartCity = 4 then 3
               when StartCity2 = 4 then 4
               else 10  -- should never happen but put them at the end anyway
          end);

结果中的陌生感是因为NULL值首先出现在order by中。没有where子句," 3"的排序值是NULL