MySQL group by - union all

时间:2014-01-19 19:46:11

标签: mysql union-all

我有一个报告查询:

select @t := '' as 'Clave', @tf:='Inventario Físico' as 'Descripción', @t:= '' as 'Cantidad', @t:= '' as 'Precio Unitario' union all 
select @t:= '', @t:= '', @t:= '', @t:= '' union all 
(select cla, des, can, CAST(pl1*can as Decimal(10,2)) from inventario order by cla) union all 
select @t:= '', @t:='', @tnde := 'Número de Elementos: ', count(*) from inventario union all 
select @t:= '', @t:= '', @tne:= 'Suma total: $', sum(ppu) from inventario;

我需要第三个查询的“order by”。

select cla, des, can, CAST(pl1*can as Decimal(10,2)) from inventario order by cla

本身,这行代码完美地工作,但是,当它在工会之间时,所有的信息都没有被订购。我怎么解决这个问题?感谢。

1 个答案:

答案 0 :(得分:0)

union all 确保数据符合子查询指定的顺序。您需要明确order by才能获得该结果。

此方法添加了一个排序列以将组保持在一起。最后的order by子句首先按ordering排序,然后按用于排序第三个子查询的列排序:

(select @t := '' as Clave, @tf:='Inventario Físico' as Descripción,
        @t:= '' as "Cantida", @t:= '' as "Precio Unitario", 0 as ordering
) union all 
(select @t:= '', @t:= '', @t:= '', @t:= '', 1 as ordering) union all 
(select cla, des, can, CAST(pl1*can as Decimal(10,2)), 2 from inventario) union all 
(select @t:= '', @t:='', @tnde := 'Número de Elementos: ', count(*), 3 from inventario) union all 
(select @t:= '', @t:= '', @tne:= 'Suma total: $', sum(ppu), 4 from inventario)
order by ordering, clave;

我还将列别名上的单引号更改为双引号。我认为最好只使用单引号作为字符串常量。