1

我有一张表,我希望在一个查询中按几个不同的条件/优先级排序。

例如,一个名为“用户”的表带有 5 列:

userID
userName
age
gender
birthday

在年龄,性别和生日可能为空的情况下,我希望查询将按优先顺序返回表行:

1. Age, gender and birthday is not null,
2. Age, gender is not null,
3. Age is not null,
4. Then the rest of the rows

我查看了 UNION、UNION ALL 和 ORDER BY IF,但没有达到结果(可能我查询错误)。

希望有人可以帮助我解决这个问题。谢谢你。

4

2 回答 2

3

你的问题不清楚每个优先级需要满足的条件,但你会从中得到这个想法:

select   *
from     mytable
order by 
         case when age is null and gender is null and birthday is null then 1
              when age is null and gender is null and birthday is not null then 2
              when age is null and gender is not null and birthday is not null then 3
              when age is not null and gender is not null and birthday is not null then 4
              else 5
         end

编辑:我想我读错了你的问题,因为缺少格式,我把 NULL 和 NOT NULL 混在一起了,但你明白了......

于 2012-07-10T15:14:20.270 回答
0

这是一个简单的命令问题:

order by (case when age is not null and birthday is not null and gender is not null then 1
               when age is not null and birthday is not null then 2
               when age is not null then 3
               else 4
          end)

您也可以在之后添加其他排序条件(例如名称或其他)。

例如,在每种情况下按年龄降序排序:

order by (case when age is not null and birthday is not null and gender is not null then 1
               when age is not null and birthday is not null then 2
               when age is not null then 3
               else 4
          end),
         age desc
于 2012-07-10T15:16:31.023 回答