2014-01-19 74 views
0

我有这个疑问的报告:MySQL的GROUP BY - 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; 

我需要一个 “排序依据” 为第三查询。

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

就其本身而言,该代码行完美工作,但是,当它在工会之间时,所有信息都没有排序。我该如何解决这个问题?谢谢。

回答

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; 

我也改变了列别名双引号单引号。我认为对于字符串常量只使用单引号是一种很好的做法。