简体   繁体   中英

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. 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)

  • isSpecial
  • 3A (All isA are true)
  • 2A (Two of isA are true)
  • 1A (only one of isA is true)
  • 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.

You need three terms in the order by clause - isSpecial, the number of "isA" truths and the name. Assuming your database treats false and true as 0 and 1, I'd do something like this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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