该错误表明您的ORDER BY 不明确,您需要将您的SELECT 语句括起来以向MySQL 表明它是如何应用的。
来自MySQL Docs:
使用 ORDER BY 或 LIMIT 子句
排序或限制整个 UNION 结果,
将单个 SELECT 括起来
声明并放置 ORDER BY 或
LIMIT 在最后一个之后。
因此,根据您的查询,将每个查询放在括号内,并将 ORDER BY 放在括号外:
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
或者,如果您希望ORDER BY 在UNION 之前单独应用于每个语句,请将ORDER BY 放在两个SELECT 语句中的每一个的括号内。
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