按日期加入查询

时间:2016-05-15 18:17:10

标签: mysql sql join

请有人帮助我。

我需要加入这两个查询并按小时分组。查询结果可能有很多天。

结果:Query1

SELECT DATE_FORMAT( Venta.fechaImpresion,  "%h" ) AS fechaImpresion2, COUNT( * ) AS total
FROM  `Venta` 
WHERE Venta.fechaImpresion LIKE  "2016-05-02 %"
GROUP BY HOUR( Venta.fechaImpresion ) , DAY( Venta.fechaImpresion ) 
LIMIT 0 , 30

结果:Query2

SELECT DATE_FORMAT(Venta.fechaImpresion,"%h") as fechaImpresion FROM `Venta`
where Venta.fechaImpresion >= "2016-05-02" and Venta.fechaImpresion <= "2016-05-09"  
 GROUP BY hour( Venta.fechaImpresion) 

如果我尝试加入一个查询,结果为零。

SELECT DATE_FORMAT( Venta.fechaImpresion,  "%h" ) AS fecha, dia1.total AS total1
FROM  `Venta` 
LEFT JOIN (

SELECT DATE_FORMAT( Venta.fechaImpresion,  "%h" ) AS fechaImpresion
FROM  `Venta` 
WHERE Venta.fechaImpresion >=  "2016-05-02"
AND Venta.fechaImpresion <=  "2016-05-09"
GROUP BY HOUR( Venta.fechaImpresion )
)fecha ON fecha.fechaImpresion = Venta.fechaImpresion
LEFT JOIN (

SELECT DATE_FORMAT( Venta.fechaImpresion,  "%h" ) AS fechaImpresion2, COUNT( * ) AS total
FROM  `Venta` 
WHERE Venta.fechaImpresion LIKE  "2016-05-02 %"
GROUP BY HOUR( Venta.fechaImpresion ) , DAY( Venta.fechaImpresion )
)dia1 ON ( dia1.fechaImpresion2 = fecha.fechaImpresion ) 
WHERE Venta.fechaImpresion >=  "2016-05-02"
AND Venta.fechaImpresion <=  "2016-05-09"
GROUP BY HOUR( Venta.fechaImpresion ) 

2 个答案:

答案 0 :(得分:0)

您可以尝试这样

从第一个表中选择b.second table列,a。*,在第二个表中选择a。* adate column = b.date column

答案 1 :(得分:0)

我建议为表使用两个单独的句柄。像这样:

SELECT DATE_FORMAT( v1.fechaImpresion,  "%h" ) AS fechaImpresion2, COUNT( v1.* ) AS total, DATE_FORMAT(v2.fechaImpresion,"%h") as fechaImpresion
FROM  `Venta` v1, 'Venta' v2 where v1.fechaImpresion = v2.fechaImpresion 

然后,您可以根据需要应用各种日期条件。