【问题标题】:Sum with Loop expression使用循环表达式求和
【发布时间】:2021-10-11 14:52:21
【问题描述】:

我想对多行进行计算,结果应该是一个结果

表 g

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

表 d

| 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

【问题讨论】:

标签: sql loops join sum sql-query-store


【解决方案1】:

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

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

【讨论】:

  • INNER JOIN c ON c.id = g.id 我得到错误 Msg 4104, Level 16, State 1, Line 21 The multi-part identifier "g.Id" could not be bound。
  • @user2275634 这就是为什么您应该创建一个最小的可重现示例,根据我在您问题的评论中的链接。
  • 我已经更新了答案,如果仍然不正确,那么您将需要编辑您的问题并添加所需的详细信息; fullaccruate 引用的 all 表示例到查询中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
相关资源
最近更新 更多