The error indicates that your ORDER BY
is ambiguous, you need to parenthesize your SELECT
statements to indicate to MySQL how it is to be applied.
From the MySQL Docs:
To use an ORDER BY or LIMIT clause to
sort or limit the entire UNION result,
parenthesize the individual SELECT
statements and place the ORDER BY or
LIMIT after the last one.
So, given your query, put each query inside parentheses and place the ORDER BY
outside them:
SELECT date , month , Sum(fact_1) , ( 2 / Sum(fact_2) ) , 2
FROM(
(SELECT time.date, time.month, time.year,
MAX(sales_fact.sell_out_value) as fact_1, 0 as fact_2
FROM sales_fact, time_dim as time
WHERE time.id=sales_fact.time_id AND time.date="2008-01-01"
GROUP BY time.date)
UNION
(SELECT time.date, time.month, time.year, 0 as fact_1,
MAX(sales_target_fact.sell_out_target) as fact_2
FROM sales_target_fact, time_dim as time
WHERE time.id=sales_target_fact.time_id AND time.date="2008-01-01"
GROUP BY time.date)
ORDER BY time.year
) as Combined_Table GROUP BY date ORDER BY year
Alternatively, if you wanted the ORDER BY
to apply to each statement individually before the UNION
, put the ORDER BY
within the parentheses for each of the two SELECT
statements.
SELECT date , month , Sum(fact_1) , ( 2 / Sum(fact_2) ) , 2
FROM(
(SELECT time.date, time.month, time.year,
MAX(sales_fact.sell_out_value) as fact_1, 0 as fact_2
FROM sales_fact, time_dim as time
WHERE time.id=sales_fact.time_id AND time.date="2008-01-01"
GROUP BY time.date
ORDER BY time.year)
UNION
(SELECT time.date, time.month, time.year, 0 as fact_1,
MAX(sales_target_fact.sell_out_target) as fact_2
FROM sales_target_fact, time_dim as time
WHERE time.id=sales_target_fact.time_id AND time.date="2008-01-01"
GROUP BY time.date
ORDER BY time.year)
) as Combined_Table GROUP BY date ORDER BY year