SQL Server Order by multiple values from sub query [closed]

fjaof16o  于 2023-06-04  发布在  其他
关注(0)|答案(1)|浏览(207)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 4 days ago.
The community is reviewing whether to reopen this question as of 4 days ago.
Improve this question

I have table Estates: [Id, Title] and Results: [EstateId, Type (nvarchar), A (int), B (decimal)] and a query similar to this:

select *
from Estates
order by (
    select A
    from Results
    where Type = 'some dynamic value'
    and EstateId = Id
) ASC, (
    select B
    from Results
    where Type = 'some dynamic value'
    and EstateId = Id
) DESC

The query plan says that both subqueries are run, and I would like to know if there's a way to rewrite it to order by multiple result values from a single subquery.

I have tried concatenating to a string (with leading zeroes for natural sorting), but the ascending/descending part is hard. I have also tried hierarchyid, but it does not support zeroes after the dot (the fractional part of the decimal).

Any good ideas?

This is a dynamically built query, and though I could refactor it to make it join the Results table, it will make the code quite weird in other places because I already join the Results table but with another value of Type. Therefore I hoped for a sub-query solution.

a11xaf1n

a11xaf1n1#

If the values A and B are numeric and you already tried to get from, say, 12 and 125 to '0001200125' for a sortkey, then getting a descending order key is not that difficult. In my example you would calculate 99999 - 00125 and end up with '0001299874'.

In below query I use a 20-digit sortkey composed of two 10-digit parts:

select *
from estates
order by (
    select format(a, 'd10') + format(9999999999 - b, 'd10')
    from results
    where type = 'some dynamic value'
    and estateid = id
);

相关问题