【问题标题】:Count based on condition using query builder not working使用查询生成器根据条件计数不工作
【发布时间】:2020-12-27 14:20:42
【问题描述】:

我从 Laravel 查询中获得的结果集遇到了一些问题

查询

     $collegecounts = DB::table('colleges as cs')
        ->select(DB::raw('count(college_id) as graduates'),'cs.id','cs.collegename',
            DB::raw('round(AVG(st.status_id),0) as average'),
            DB::raw("(CASE WHEN (st.status_id = 4) THEN count(st.college_id) END) as placements")

        )
        ->join('students as st', 'st.college_id', '=', 'cs.id')
        ->groupBy('st.college_id', 'cs.id', 'cs.collegename')
        ->get();

预期结果类似于下表:(下表中的 Placements 列是 status_id 计数)

SQL 表:

学生桌

Column
id
Name
College_id
Status_id

学院桌

Column
id
Name
location

状态可在状态表中找到。如果我没有在 groupby 查询中添加 status_id,我会收到一个错误,要求我将 status_id 添加到 groupby。将其添加到 Groupby 后,我会为每个学生获得更多列,而不是按大学分组。我也尝试使用 having 而不是 case condition 我得到相同的结果

错误:

SQLSTATE[42803]:分组错误:7 错误:列“st.status_id”必须 出现在 GROUP BY 子句中或用于聚合函数 LINE 1: ...ound(AVG(st.status_id),0) 作为平均值,(CASE WHEN (st.status_... ^

我可以轻松地将 st.status_id 添加到 group by,但这并没有得到正确的结果

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以使用 'sum' 进行有条件的计数。以下查询是您的预期结果:

    select c.name, count(s.id) as Graduates, SUM(s.status_id=4) AS Placements
    from college as c join student as s on s.collegge_id = c.id
    group by c.id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2021-09-07
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多