I have SQL UNION where second part of that statement is the row that represents TOTALS. How can I ORDER BY where TOTALS will ALWAYS will show up as the last row?
views:
88answers:
4
+1
A:
You could try adding an 'order' column to each query and then order by that column...
SELECT x.*
FROM
(
SELECT columns, 2 AS [Order]
UNION
SELECT totals, 1 AS [Order]
) x
ORDER BY x.[Order]
tt83
2009-12-09 20:31:56
+6
A:
Add an extra column to the queries being UNIONed, and make that column the first column in your ORDER BY clause.
So if I started with something like this:
SELECT product, price
FROM table
UNION
SELECT 'Total' AS product, SUM(price)
FROM table
I'd add a new column like this:
SELECT product, price
FROM (
SELECT product, price, 0 AS union_order
FROM table
UNION
SELECT 'Total' AS product, SUM(price), 1 AS union_order
FROM table
)
ORDER BY union_order
That way, regular products appear first, then the total appears at the end.
Welbog
2009-12-09 20:32:13
+1 - you beat me to it!
davek
2009-12-09 20:32:54
SQL Server doesn't seem to like the ORDER BY after the outer select.
John Dunagan
2010-06-21 18:33:56
+1
A:
select * from
(
select 1 as prio
, col1
, col2
...
from tableA
union
select 2 as prio
, totalCol1
, totalCol2
...
from tableB
) order by prio
davek
2009-12-09 20:32:28
+4
A:
Have you tried using GROUP BY ROLLUP
- it might be just want you want, although it's difficult to tell when you haven't posted your query.
Mark Byers
2009-12-09 20:33:03
Yes -- much more efficient in theory than unions. A half-way-between solution would be to use a subquery factoring clause to compute the detail then reference it in two queries unioned together, one to pass the detail through and the other to do the totals, but group by rollup is better.
David Aldridge
2009-12-10 08:46:48