当前位置:   article > 正文

sum 加 Group By 的使用_sql sum group by用法

sql sum group by用法

1、A 表 有server_id  为1的两条数据

2、B表有server_id 为1的数据也有两条

原本Sql是这样   乍一看没啥问题  但是group by 没生效 

SELECT a.server_id,sum(b.score) as score FROM `a` INNER JOIN `b` ON `a`.`server_id`=`b`.`server_id` WHERE  `b`.`server_id` = 1 GROUP BY `a`.`server_id` LIMIT 1

期望的值是 20 返回结果却是 40

修改Sql 构建子查询:

 

distinct说明:用于返回唯一不同的值。

select a.server_id, sum(b.score) from ( select distinct a.server_id from a)a inner join b on a.server_id = b.server_id group by a.server_id

Tp写法:

  1. // 构建子查询
  2. $sql = Db::name('a')->field('distinct server_id')->buildSql();
  3. $r = Db::table($sql.'a')
  4. ->join('b','a.server_id = b.server_id')
  5. ->where('b.server_id', 1)
  6. ->field('a.server_id,sum(b.score) as score')
  7. //->group('a.server_id')
  8. ->find();

Laravel写法:

  1. $build_sql = DB::table('a')
  2. ->select('server_id')
  3. ->groupBy('ServerID');
  4. $r = DB::table( DB::raw("({$build_sql->toSql()}) as a") )
  5. ->join('b', 'a.server_id', 'b.server_id')
  6. ->whereDate('a.CreateTime', date('Y-m-d'))
  7. ->selectRaw('sum(b.score) as score')
  8. ->where('a.server_id', 1)
  9. ->first();

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/986672
推荐阅读
相关标签
  

闽ICP备14008679号