查询没有返回预期的结果?

时间:2017-08-22 13:03:51

标签: mysql sql laravel

我有两张桌子:

1)report_details

report_details

2)报告

enter image description here

查询:

SELECT COUNT(channel),DATE_FORMAT(date,'%d/%m/%Y') AS niceDate,
    channel FROM `report_details`
JOIN report on report.report_id=report_details.report_id
where report.report_hash='abcd'
GROUP BY  channel,niceDate;

输出

enter image description here

预期输出

enter image description here

3 个答案:

答案 0 :(得分:2)

 $value =  DB::table('report_details')
 ->join('reports','report_details.report_id','=','reports.report_id')
 ->groupBy('channel')->get();

// print_r($value);
 also use DB; in your controller

答案 1 :(得分:1)

使用GROUP_CONCAT()功能:

SELECT GROUP_CONCAT(COUNT),GROUP_CONCAT(channel)channel,niceDate FROM
(
    SELECT COUNT(channel)COUNT, DATE_FORMAT(date, '%d/%m/%Y') AS niceDate,channel 
    FROM `report_details` 
    JOIN report ON report.report_id = report_details.report_id 
    WHERE report.report_hash = 'abcd' 
    GROUP BY niceDate,channel 
)Z
GROUP BY niceDate ;

答案 2 :(得分:1)

问题: 据我所知,您的查询中存在问题,因为您需要聚合,因此您需要的不仅仅是一个简单的组。所以你可能想使用GROUP_CONCAT()来获取你的chanel,但如果你想在1行但是使用分隔符对同一日期的所有chanel进行分组,你需要一个内部选择

修改后的查询

SELECT GROUP_CONCAT(cnt),niceDate,GROUP_CONCAT(channel)channel FROM
(
  SELECT COUNT(channel) as cnt ,DATE_FORMAT(date,'%d/%m/%Y')
  AS  niceDate,group_concat(channel) channel
  FROM `report_details` JOIN report on report.report_id=report_details.report_id
  where report.report_hash='abcd' GROUP BY  chanel,niceDate
) f
GROUP BY niceDate ;

<强>阐释

  • 我将第一个查询作为内部选择,这样你就可以在1行中拥有相同日期的所有chanel,你不能在1中选择,因为Group_Concat不能在内部进行计数,除非它来自内部选择,如本例中的
  • 我添加了group_concat(chanel)的使用,这样你就可以获得chanel的列表,而不是每行的单独行

如果您想了解有关group_concat的更多信息,请访问doc: Documentation

相关问题