php - 2 通过不同、求和、计数进行分组 : PHP MySQL

标签 php mysql count group-by sum

引用号:GROUP BY WITH HAVING ( DISTINCT ) : PHP , MYSQL

我得到了答案(感谢@coytech),但我还需要一栏:

按照:

id | mid | pid | owgh | nwgh |
1    3      12    1.5    0.6
2    3      12    1.5    0.3
3    3      14    0.6    0.4
4    3      15    1.2    1.1
5    4      16    1.5    1.0
6    4      17    2.4    1.2 
7    3      19    3.0    1.4

我得到了答案

Select mid , COUNT(distinct pid) as cpid , SUM(nwgh) as totalnwgh from test GROUP BY mid

sqlfiddle:http://sqlfiddle.com/#!9/45e68/2

mid  cpid       totalnwgh
3      4          3.8
4      2          2.2 

但在上面我还需要一列,如下所示:totowgh

mid cpid        totalnwgh  totowgh
3      4          3.8        6.3 (DISTINCT value as per pid column)
4      2          2.2        3.9

其中 totowgh = 6.3 来自根据 pid 列的 DISTINCT 值

mid = 3 的计数为 5,但 mid=3 的不同 pid = 4,同样,mid=3 和不同 pid 的“不同”owgh = 6.3。

由于 pid=12 因此计数了 1 次,

1.5 + 0.6 + 1.2 + 3 = 6.3(请注意,这是根据 pid 的 DISTINCT 值)

请注意:我需要根据不同的 pid 或按 pid 分组的 owgh 值..因为如果我用 1.5 替换 owgh 0.6 的值,那么它将是 5.7 而不是 7.2,但 owgh 0.6 的值属于 pid = 14 而不是pid = 12 因此 owgh 变化的总数...但我需要的是 7.2

看看我的意思:sqlfiddle.com/#!9/2a53c/6

最佳答案

好的,根据您的后续评论,这就是我的想法。首先获取不同 owgh 的分组,然后与主查询执行 JOIN 。查看演示 fiddle http://sqlfiddle.com/#!9/a56e4/1

SELECT t.`mid` , 
COUNT(distinct t.`pid`) AS countmid , 
SUM(t.`nwgh`) AS totalnwgh,
xx.`totowgh`
FROM test t JOIN (
select mid, sum(owgh) as totowgh 
from (
select distinct mid, owgh from test) x
group by mid) xx ON t.`mid` = xx.`mid`
GROUP BY t.`mid`;

这将导致

mid     countmid    totalnwgh   totowgh
3          4           3.8        6.3
4          2           2.2        3.9

关于php - 2 通过不同、求和、计数进行分组 : PHP MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32536393/

相关文章:

php - 无法获得我想要的 max 结果(类似)

python - 从现有词典创建频率词典

CSS 计算 DOM 中的所有元素

php - 如何从ajax加载的内容中获取复选框值

php - Slim Framework ^3 多个路由文件

mysql - 在一对多关系表中获取最新数据

来自同一个表的 MySQL 子查询

mysql - 如何在不同条件下显示不同的计数?

PHP SimpleXML 不保留 XML 属性中的换行符

php - 在 SQL 中组合条件