我在mysql5.7.x中有一个查询,例如
select CONCAT(YEAR(now()), '/', MONTH(now())) as yearmonth,
a.country
sum(sales)
from table1 as a
group by CONCAT(YEAR(now()), '/', MONTH(now())) as yearmonth, a.country
order by length(CONCAT(YEAR(now()), '/', MONTH(now())))
在此查询顺序中,按长度(组列)不允许。
数据应类似于
2018/12
2018/11
2018/10
2018/09.......etc
任何人都可以帮助我如何进行这种排序。谢谢
答案 0 :(得分:2)
Group by
不能具有列别名。同样没有必要使用NOW()
。我猜您的表格有日期列。
此外,这里不需要长度,因为2018/12
的长度是指定日期的字符长度,即7
select CONCAT(YEAR(your_date_column), '/', MONTH(your_date_column)) as yearmonth,
a.country
sum(sales)
from table1 as a
group by CONCAT(YEAR(your_date_column), '/', MONTH(your_date_column)), a.country
order by CONCAT(YEAR(your_date_column), '/', MONTH(your_date_column))
答案 1 :(得分:0)
我建议您将数字保留为用于分组和排序的数字,并在SELECT
内格式化它们:
SELECT CONCAT(yy, '/', IF(mm < 10, '0', ''), mm) AS yymm
, country
, sum_sales
FROM (
SELECT YEAR(a.date_column) AS yy
, MONTH(a.date_column) AS mm
, a.country
, SUM(sales) AS sum_sales
FROM table1 AS a
GROUP BY YEAR(a.date_column), MONTH(a.date_column), a.country
) AS x
ORDER BY yy DESC, mm DESC