I have a SQL Report driven by a query that sorts it in ascending order of some numerical value. But the user wants two particular rows of data, which happen to appear at different ordinal positions in the query results, to be juxtaposed. Is there a way to do this, either through the report's driving SQL or the .rdl file itself?
A:
It sounds like you're asking for this:
select * from table where col1 = first_val or col1 = second_val;
where first_val and second_val are the values for the rows that the user wants returned.
If that's not what you're looking for, please clarify your question.
David Oneill
2009-12-18 16:48:59
+3
A:
Just add another calculated expression as the first order by Expression, which puts those two values ahead of all others...
Select [Other stuff]
From Table
Order By Case colName
When first_val then 0
When second_val then 0
else 1 End,
colName
or, EDIT (to include @astander's suggestion)
Select [Other stuff]
From Table
Order By Case
When colName In (first_Val, second_Val)
Then 0 else 1 End,
colName
and another Edit, to put second_val immediately after first_Val...
Select [Other stuff]
From Table
Order By Case
When colName < first_Val And colName <> secondVal Then 0
When colName = first_Val Then 1
When colName = secondVal Then 2
Else 3 End,
colName
Charles Bretana
2009-12-18 16:55:24
You can shorten that by using **CASE WHEN colName IN(first_val, second_val) then 0**
astander
2009-12-18 16:57:43
I didn't know you could use CASE in the context of ORDER BY.
JonathanWolfson
2009-12-18 17:07:26
@Jonathan, Sure, you can use Case just about anywhere.@astander, good one.. I wasn't sure you could use In (List) syntax inside a Case...
Charles Bretana
2009-12-18 17:12:40
Actually, the problem here is that it places the rows where colName is first_val or second_val atop all other rows, which is not correct. I want, as soon as first_val is discovered, for second_val's row to appear right beneath it.
JonathanWolfson
2009-12-18 17:16:51
@Jonathan, then you need an expression which represents this. It sounds like all rows are sorted by colName except the one with value = second_val, which needs to be sorted immediately after the row(s) with first_val. so see my edit..
Charles Bretana
2009-12-18 17:19:51
A:
Also, CURSORs are a good tool for fine-grained control. I'm using that, but I will see if it can be stripped of iterative code by using the ORDER BY CASE suggestion.
JonathanWolfson
2009-12-18 17:08:46