Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put the Order BY in SQL UNION so TOTALS will show up always as last row?

Tags:

sql

oracle

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?

like image 733
Roman Kagan Avatar asked Dec 09 '09 20:12

Roman Kagan


People also ask

Does UNION all preserve order?

As per standard SQL UNION / UNION ALL do not guarantee any particular sort order without an outer ORDER BY clause - like there is hardly any place in SQL where sort order is guaranteed without ORDER BY .

How do you use ORDER BY clause in UNION all?

As the following query shows, when you include an ORDER BY clause, it must follow the final SELECT statement and use an integer, not an identifier, to refer to the ordering column. Ordering takes place after the set operation is complete.

Can we use ORDER BY in UNION all in SQL?

The UNION ALL operator can use the ORDER BY clause to order the results of the query in SQL Server (Transact-SQL).

How do you get the total count in UNION query?

Here is the query to count on the union query. mysql> select count(*) as UnionCount from -> ( -> select distinct UserId from union_Table1 -> union -> select distinct UserId from union_Table2 -> )tbl1; The following is the output displaying the count.


2 Answers

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.

like image 51
Welbog Avatar answered Sep 24 '22 13:09

Welbog


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.

like image 30
Mark Byers Avatar answered Sep 24 '22 13:09

Mark Byers