Question

I have this query for a report:

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;

I need an "order by" for the 3rd query.

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

By itself, that line of code works perfectly, but, when it's between the unions, all the info it is not ordered. How can I solve this? Thanks.

Was it helpful?

Solution

union all does not guarantee that the data is in the order specified by the subqueries. You need to do an explicit order by to get that result.

This approach adds an ordering column to keep the groups together. The final order by clause first orders by ordering and then by the column used for ordering the third subquery:

(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;

I also changed the single quotes on the column aliases to double quotes. I think it is good practice to only use single quotes for string constants.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top