Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove default order by from union Statement

I want to display data like this:

Column1        Column2
-----------------------
TotalAvg         60%

A1               50%

B1               70%

Z1               60%

My sql script is something like:

select 'Total Avg' as Column1,'60%' as Column2

union

select Column1,Column2 from tblAvg

and result I am getting is something like this:

Column1        Column2
------------------------

A1               50%

B1               70%

TotalAvg         60%

Z1               60%

Question: I want to remove default ordering and want result in the order we are doing union tables.

like image 248
yashpal Avatar asked Dec 26 '22 19:12

yashpal


2 Answers

You could add a column that specifies the result order:

select 'Total Avg' as Column1,'60%' as Column2, 1 as OrderCol
union
select Column1,Column2, 2 from tblAvg
order by OrderCol

Without an order by, the database is free to return rows in any order.

like image 197
Andomar Avatar answered Dec 30 '22 11:12

Andomar


SELECT
  *
FROM
(
  select 0 as pos, 'Total Avg' as Column1, '60%' as Column2
  union
  select 1 as pos,                Column1,          Column2 from tblAvg 
)
  AS data
ORDER BY
  pos, column1, column2
like image 29
MatBailie Avatar answered Dec 30 '22 11:12

MatBailie