【问题标题】:sql query one table with customizing ordersql用自定义顺序查询一张表
【发布时间】:2012-07-10 23:52:01
【问题描述】:

我有一张表,我希望在一个查询中使用几个不同的条件/优先级对它进行排序。

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

userID
userName
age
gender
birthday

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

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,但没有得到结果(可能我查询错误)。

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

【问题讨论】:

  • 您使用的是 MySQL、Oracle、SQL Server 等吗?

标签: sql phpmyadmin


【解决方案1】:

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

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 混在一起了,但你明白了......

【讨论】:

    【解决方案2】:

    这是一个简单的订单问题:

    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
    

    【讨论】:

    • 嗨,“1”、“2”、“4”是什么意思?是显示顺序吗?
    • 其实意思是1、2、3、4(第三个错字)。是的,这些都是 order by 使用的值,所以第一个条件在前,以此类推。
    • 我如何按年龄对每个案例按降序排序?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2018-11-11
    • 2016-08-28
    相关资源
    最近更新 更多