简体   繁体   中英

Cypher Conditional `ORDER BY` clause (same property, differ ASC/DESC)

I have two queries:

MATCH (n:Node) 
RETURN n.value
ORDER BY n.value DESC
LIMIT 5
MATCH (n:Node) 
RETURN n.value
ORDER BY n.value ASC
LIMIT 5

I would like to combine them both by adding an additional parameter. I tried different approaches with CASE statement, but it looks like the CASE statement allows me to change the property of the sort, not the type of the sort...

This is a pseudo-code that does what I'm trying to achieve (But this one obviously doesn't work):

WITH "ASC" AS sortType
MATCH (n:Node) 
RETURN n.value
ORDER BY n.value (CASE WHEN sortType = "ASC" THEN ASC ELSE DESC END)
LIMIT 5

So the final question is:

  • How can I perform a conditional OrderBy clause on the same property (DESC/ASC difference)?

You can add a column with a sortValue like this

RETURN  n.value,
        CASE WHEN sortType = ‘DESC’ THEN n.value * -1 ELSE n.value END AS sortValue
ORDER BY sortValue

Adding the sortValue in your RETURN statement makes that you get either

| value | sortValue |
|     1 |          1|
|     2 |          2|
|     3 |          3|

OR

| value | sortValue |
|     3 |         -3|
|     2 |         -2|
|     1 |         -1|

You can use this mechanism also in case you want to have flexibility with regard to which column you want to sort, as long as you make sure that you put the right value in the sortValue column.

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