tags:

views:

88

answers:

4

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?

+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
+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
+1 - you beat me to it!
davek
SQL Server doesn't seem to like the ORDER BY after the outer select.
John Dunagan
+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
+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
That's a neat little feature. +1
Welbog
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