由于其中有SUM函数,MySQL查询仅返回一行

时间:2018-11-06 07:50:41

标签: mysql

我正在尝试创建一个广告查询,在这里我想获取每个广告的所有印象数的数据。一个用户可以有多个广告,并且每天都会在表格中计算一次印象。因此,每天我都会有不同的一行。这是我的查询当前的样子。

SELECT  
   eac.id,
   eac.gender,
   eac.start_date,
   eac.end_date,
   eac.ad_image_path,
   eac.ad_link,
   eac.requestfrom,
   eac.traffic,
   eac.registertype,
   eacr.region_id,
   eac.active,
   eac.impression,
   eac.center_image_path,
   eac.bottom_image_path,
   eac.approved_by,
   er.name as country_name,
   eac.budget,
   sum(budget/ (DATEDIFF(end_date,start_date)) *1000) as daily_imp,  
   eaa.impression_count,
   eac.customer_id,
   eaa.created_at
FROM 
   `enrich_advert_customer` eac         
   JOIN `enrich_advert_customer_regions` eacr ON eac.id = eacr.advert_customer_id  
   JOIN `enrich_regions` er ON er.id = eacr.region_id
   LEFT JOIN `enrich_advert_abstract` eaa on eac.id = eaa.advert_customer_id        
WHERE 
   eac.requestfrom ='web' AND
   eac.registertype = 'paid' AND
   eac.active = 1 AND
   eac.approved_by = 1 AND
   eac.gender ='male' AND
   er.name = 'india' AND
   eac.start_date <= '2018-11-5' AND
   eac.end_date >= '2018-11-10'

但是这里的问题是,如果我正在使用

sum(budget/ (DATEDIFF(end_date,start_date)) *1000) as daily_imp 

然后它一次只返回一行。

如果您可以建议我在哪里犯了错误,那将是有帮助的。

谢谢!

1 个答案:

答案 0 :(得分:0)

应用聚合时,您需要在其中添加group by子句和其他列

SELECT  eac.id,eac.gender,eac.start_date,eac.end_date,eac.ad_image_path,eac.ad_link,eac.requestfrom,eac.traffic,eac.registertype,eacr.region_id,eac.active,eac.impression,eac.center_image_path,eac.bottom_image_path,eac.approved_by,er.name as country_name,eac.budget,sum(budget/ (DATEDIFF(end_date,start_date)) *1000) as daily_imp  ,eaa.impression_count,eac.customer_id,eaa.created_at

FROM 
    `enrich_advert_customer` eac 

JOIN 
    `enrich_advert_customer_regions` eacr
   ON eac.id = eacr.advert_customer_id 

JOIN 
    `enrich_regions` er
   ON er.id = eacr.region_id

LEFT JOIN 
    `enrich_advert_abstract` eaa
    on eac.id = eaa.advert_customer_id

WHERE eac.requestfrom ='web' AND
      eac.registertype = 'paid' AND
      eac.active = 1 AND
      eac.approved_by = 1 AND
      eac.gender ='male' AND
      er.name = 'india' AND
      eac.start_date <= '2018-11-5' AND
      eac.end_date >= '2018-11-10'
group by eac.id,eac.gender,eac.start_date,eac.end_date,eac.ad_image_path,eac.ad_link,eac.requestfrom,eac.traffic,eac.registertype,eacr.region_id,eac.active,eac.impression,eac.center_image_path,eac.bottom_image_path,eac.approved_by,er.name,eac.budget,  eaa.impression_count,eac.customer_id,eaa.created_at