简体   繁体   English

SQL中两级如何按列排序?

[英]How to order by column with two level in SQL?

I need to write a SQL statement to select and sort data ordered by priority of value and name.我需要将 SQL 语句写入 select 并按值和名称的优先级排序数据。 Please see the criteria below.请参阅以下标准。

Database schema:数据库架构:

    name : string
    isSpecial : boolean
    isA1 : boolean
    isA2 : boolean
    isA3 : boolean

Order Priority (The priority of isA1, isA2, isA3 are equal, I want to order from the number of true of isAx) Order Priority(isA1、isA2、isA3的优先级相等,我想从isAx为真的个数开始排序)

  • isSpecial很特别
  • 3A (All isA are true) 3A(所有isA都为真)
  • 2A (Two of isA are true) 2A(有两个isA为真)
  • 1A (only one of isA is true) 1A(isA只有一个为真)
  • Second level ordered by: name二级排序:名称

example例子

id, name, isSpecial, isA1, isA2, isA3
1, aaa, false, true, true, true
2, bbb, true, true, true, true
3, ccc, false, false, false, true
4, hhh, false, true, false, true
5, ddd, false, true, true, false

expected order is预期顺序是

2 (isSpecial = true)
1 (3A)
5 (2A, name = ddd)
4 (2A, name = hhh)
3 (1A)

Do you have any idea or any suggestion?你有什么想法或建议吗?

Update Please see the SQL statement from the comment below.更新请参阅下面评论中的 SQL 声明。

You need three terms in the order by clause - isSpecial, the number of "isA" truths and the name.您在 order by 子句中需要三个术语 - isSpecial、“isA”真理的数量和名称。 Assuming your database treats false and true as 0 and 1, I'd do something like this:假设您的数据库将 false 和 true 视为 0 和 1,我会这样做:

SELECT   *
FROM     docs
ORDER BY isSpecial DESC,
         isA1 + isA2 + isA3 DESC,
         name ASC

If your database can't implicitly convert booleans to ints like this, you'll have to replace the isA columns with case expressions that perform this logic before summing them.如果您的数据库不能像这样将布尔值隐式转换为整数,则必须在对它们求和之前将 isA 列替换为执行此逻辑的 case 表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM