Reputation: 1621
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:
OrderBy
clause on the same property (DESC/ASC difference)?Upvotes: 0
Views: 211
Reputation: 1
You can add 2 expressions for ORDER BY:
CASE WHEN sortType = "ASC" THEN n.value ELSE null END ASC,
CASE WHEN sortType = "ASC" THEN null ELSE n.value END DESC
They will be both applied, but the first one won't do anything when sortType is not "ASC" and the second won't do anything when the sortType is "ASC".
Upvotes: 0
Reputation: 5385
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.
Upvotes: 1