problem
Two requirements:
①The calculated total sales of the field retain two decimal places;
②When sorting, the summary does not participate in the sorting, and it is placed at the bottom.
Requirements①Realize one
case when add summary, but orderby sorting sorts all rows, and the total sales amount is always at the top
SELECT case when grouping(店铺名称)=1 then "汇总" else 店铺名称 end 店铺名称,
round(sum(交易金额),2) as 销售额求和
FROM test
group by 店铺名称 with rollup
order by 销售额求和 desc ;
Requirement ① Realization two
COALESCE plus summary, the effect is similar to the case when in the first plan, all use with rollup for summary
SELECT COALESCE ( `店铺名称`, '汇总' ) AS 店铺,
round(sum(交易金额),2) AS 销售总额
FROM test
GROUP BY `店铺名称` WITH ROLLUP
ORDER BY 销售总额 DESC
Requirement ②Realize one
If is equivalent to adding a hidden column with conditional judgment, order by first sorts the stores and then sorts the sales, so that the summary row goes to the bottom, because the index of the summary row is 1, and the indexes of other store names are all 0
SELECT COALESCE ( `店铺名称`, '汇总' ) AS 店铺,
round(sum(交易金额),2) AS 销售总额
FROM test
GROUP BY `店铺名称` WITH ROLLUP
ORDER BY if (店铺 = '汇总',1,0),销售总额 DESC
Requirement ②Realization two
Sql1 union sql2
union is equivalent to append query, splicing two query results together
(select `店铺名称` ,round(sum(交易金额),2) AS 销售总额
from test group by `店铺名称`
order by 销售总额 desc)
union
(select '汇总',round(sum(交易金额),2) AS 销售总额
from test)
Friendship link: Mysql data grouping & conditional sorting