Sum with Loop 表达式

Sum with Loop expression

我想计算几行,结果应该是一个结果

Table g

| id |Oppervlakte|
| 1  | 10        |
| 2  |12         |
| 3  | 7         |
| 4  | 8         |

tabled

| id | gid | Oppervlakte |
| 1  | 1   | 2           |
| 1  | 2   | 3           |
| 1  | 2   | 2           |
| 1  | 2   | 2           |
| 1  | 3   | 1           |

结果

| id |test |
| 1  | 216 |

我现在的代码是

Select r.id,
sum((g.oppervlakte-sum(d.oppervlakte)*8) as 'test' 
from r 
join g on g.rid=r.id 
join d on d.gid=g.id 
join c on c.id = g.Id 
where c.cType=0 
Group by r.id, g.oppervlakte

您可能只想聚合两次,一次在子查询中...

SELECT
  r.id,
  SUM((g.oppervlakte - d.oppervlakte) * 8) as 'test' 
FROM
  r 
INNER JOIN
  g
    ON g.rid = r.id
INNER JOIN
(
  SELECT
    d.gid,
    SUM(d.oppervlakte)   AS oppervlakte
  FROM
    d
  GROUP BY
    d.gid
)
  d
    ON d.gid = g.id 
INNER JOIN
  c
    ON c.id = g.id
WHERE
  c.cType = 0
GROUP BY
  r.id