sql查询一个具有自定义顺序的表
我有一个表,我希望在一个查询中按几个不同的条件/优先级排序 例如,名为“User”的表包含5列:sql查询一个具有自定义顺序的表,sql,phpmyadmin,Sql,Phpmyadmin,我有一个表,我希望在一个查询中按几个不同的条件/优先级排序 例如,名为“User”的表包含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 我通过IF查看
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
我通过IF查看了UNION、UNION ALL和ORDER,但没有取得结果(可能我问错了)
希望有人能帮我解决这个问题。谢谢。您的问题不清楚每个优先级需要满足哪些条件,但您可以从中了解到:
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
编辑:我想我看错了你的问题,因为没有格式,我把空和非空混在一起了,但你明白了…这是一个简单的顺序问题:
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
您正在使用MySQL、Oracle、SQL Server等吗?您好,“1”、“2”、“4”是什么意思?这是显示顺序吗?它实际上意味着1,2,3,4(第三个输入错误)。是的,这些是order by使用的值,因此第一个条件首先出现,依此类推。对于每种情况,如何按年龄降序排序?