sql-server-2008 - 计数和求和函数在左连接中不起作用
问题描述
我有以下 3 个表,我想知道预期结果的正确 sql,如下所示。我这里的 sql 不工作;
select h.pid,
h.name,
sum(r.amount1) as total1,
sum(r.amount2) as total2,
count(g.pid) as times,
sum(g.take) as totaltaken
from history h
left join rpt_revenue r on h.pid=r.pid
left join guest g on g.pid=r.pid
group by h.pid, h.name;
history
pid name
1 peter
2 may
rpt_revenue
id pid amount1 amount2
1 1 10.00 11.00
2 2 20.00 20.00
3 1 2.00 2.00
4 2 2.00 2.00
guest
gid pid id take
1 1 1 2
2 1 3 2
3 2 2 3
expected result
pid total1 total2 times totaltaken
1 12.00 13.00 2 4
2 22.00 22.00 1 3
解决方案
因此,为了能够在连接上使用聚合函数,您应该首先在连接子查询中聚合数据,然后在顶层聚合所有数据
这里有一些聚合的例子
推荐阅读
- plotly - 带有一个下拉列表和多个选择器的 Plotly Dash 散点图(全部)
- angular - 电容存储时序问题
- javascript - 如何在循环中执行事件,直到事件为真
- c# - C#:从数组中删除许多元素
- excel-2010 - 使用 excel 和 Visual Basic 每十秒计数一次
- python - Django 身份验证流程如何工作?【特例】
- node.js - find() 方法不适用于猫鼬中的异步函数
- java - JTable排序和渲染
- openvpn - 如何进行第 2 层 OpenVPN 站点到站点设置
- list - Prolog - 将列表保存到类似原子的东西中?