2使用ORDER BY查询中的SELECT

时间:2019-06-26 00:40:29

标签: mysql multiple-select

我需要创建一个MYSQL查询,该查询将返回以下内容:

excel

这是我的查询

    SELECT  t1.fecha_salida,
        t1.agencia,
        t2.fecha_salida,
        t2.directa
FROM   (SELECT fecha_salida, COUNT(*) AS agencia 
        FROM   ventas 
        WHERE  ventas.eliminado = 0 AND ventas.cliente_id !=2
        GROUP BY fecha_salida) AS t1, 
       (SELECT fecha_salida, COUNT(*) AS directa 
        FROM   ventas
        WHERE  ventas.eliminado = 0 AND ventas.cliente_id =2
        GROUP BY fecha_salida) AS t2
        GROUP BY t1.fecha_salida

我的桌子是:

|------ |Columna|Tipo|Nulo|Predeterminado |------
   |//**venta_id**//|int(11)|No| |usuario_id|int(11)|No|
   |tour_id|int(11)|No| |cliente_id|int(11)|No| |vehiculo_id|int(11)|No|
   |cashflow_id|int(11)|No| |total_compra|int(6)|No|
   |total_pagado|int(6)|No| |total_iva|int(6)|No|
   |total_comision|int(11)|No| |a_pagar|int(11)|No|
   |fecha_venta|datetime|No| |fecha_salida|date|No|
   |concretada|tinyint(1)|No| |pasajeros|int(3)|No|
   |nombre|varchar(500)|Sí|NULL |direccion|varchar(500)|Sí|NULL
   |observaciones|varchar(500)|Sí|NULL |forma_pago|tinyint(2)|No|
   |eliminado|tinyint(1)|No|

你能帮我吗

1 个答案:

答案 0 :(得分:2)

您可以使用UNION组合两个结构相同的查询,也应从组合结果中进行选择,然后对其进行排序

SELECT * FROM (

    SELECT fecha_salida, COUNT(*) AS agencia 
    FROM ventas 
    WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00' 
    and ventas.eliminado = 0 
    AND ventas.cliente_id = 2 
    GROUP BY fecha_salida

    UNION

    SELECT fecha_salida, COUNT(*) AS agencia 
    FROM ventas 
    WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00' 
    and ventas.eliminado = 0 
    AND ventas.cliente_id != 2 
    GROUP BY fecha_salida

) RESULT 
ORDER BY agencia