尝试按小时分组查询

时间:2019-05-23 10:59:52

标签: mysql

尝试按小时将查询分组,如果找不到任何内容,则将其设置为“ 0”。

SELECT 
tmhours.hours_value,
COALESCE(cc.countingSheep,0) AS countingSheep
FROM time_hours as tmhours
LEFT JOIN (
SELECT count(*) as countingSheep, company_id, `sales_date`
FROM tbl_cc 
WHERE `sales_date` BETWEEN '2019-05-01 00:00:00' AND '2019-05-01 23:59:59' AND company_id = '12345'  ) as cc on date_format(sales_date, '%H') = tmhours.hours_value
GROUP BY tmhours.hours_value

time_hours表仅包含01,02,03,04 .... 22,23

基于以上查询,我直到0才获得07

所以:

01 0
02 0
03 0
04 0
05 0
06 0
07 - 57 (the first match in the DB is 07:14:35) - the 57 is the total count, it's not grouping results
08 0
09 0
...
...
22 0
23 0

我尝试通过内部选择内部删除组,尝试移动date_format = hours_value。

2 个答案:

答案 0 :(得分:1)

您尚未在外部查询中聚合函数,因此,如果您需要不同的结果,请使用DISTINCT(分组依据可能会产生意外的结果),但在您的情况下,则不必要

相反,您是根据内部联接中的小时错过了分组的人

  SELECT 
    tmhours.hours_value,
    COALESCE(cc.countingSheep,0) AS countingSheep
  FROM time_hours as tmhours
   LEFT JOIN ( SELECT count(*) as countingSheep, company_id, date_format(sales_date, '%H')
      FROM tbl_cc 
      WHERE `sales_date` BETWEEN '2019-05-01 00:00:00' AND '2019-05-01 23:59:59' 
       AND company_id = '12345'
       GROUP BY company_id , date_format(sales_date, '%H')
      ) as cc on date_format(sales_date, '%H') = tmhours.hours_value

答案 1 :(得分:1)

您的问题是您没有按小时对子查询数据进行分组,因此您的子查询仅返回一行(因为其中有COUNT)。将分组添加到子查询中,它应该可以正常工作。请注意,您无需在外部查询中进行分组,因为您无需进行任何汇总。另外,由于只需要一天的数据,因此可以使用WHERE函数来简化DATE条件。

SELECT 
  tmhours.hours_value,
  COALESCE(cc.countingSheep,0) AS countingSheep
FROM time_hours as tmhours
LEFT JOIN (
  SELECT count(*) as countingSheep, date_format(sales_date, '%H') AS sales_hour
  FROM tbl_cc 
  WHERE DATE(`sales_date`) = '2019-05-01' AND company_id = '12345'
  GROUP BY sales_hour) as cc ON sales_hour = tmhours.hours_value