SQL Server中两个不同分组的求和和和计数
我想打印每个帐户的总订单、交易金额和计数 运行下面的查询时,出现以下错误: 列“orders.order\u amount”在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中 我怎样才能解决这个问题SQL Server中两个不同分组的求和和和计数,sql,sql-server,Sql,Sql Server,我想打印每个帐户的总订单、交易金额和计数 运行下面的查询时,出现以下错误: 列“orders.order\u amount”在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中 我怎样才能解决这个问题 SELECT trans.account_id, SUM(trans.amount), COUNT(trans.account_id), orders.order_amount, orders.order_count FROM tran
SELECT
trans.account_id,
SUM(trans.amount),
COUNT(trans.account_id),
orders.order_amount,
orders.order_count
FROM
trans
FULL JOIN
(SELECT
[order].account_id,
SUM([order].amount) as order_amount,
COUNT([order].account_id) as order_count
FROM
[order]
GROUP BY
[order].account_id) AS orders ON (trans.account_id = orders.account_id)
GROUP BY
trans.account_id
ORDER BY
trans.account_id;
Trans
表格:
trans_id account_id type amount balance account date
-----------------------------------------------------------------
1 1 a 88 213 75 1995-03-24
7 1 b 156 66 75 1995-02-25
订单
表格
order_id account_id bank_to amount
-------------------------------------
1 1 a 88
7 1 b 156
您需要将
订单。订单金额
和订单。订单计数
添加到分组依据
:
select trans.account_id,
SUM(trans.amount),
COUNT(trans.account_id),
orders.order_amount,
orders.order_count
from trans
FULL JOIN (
select [order].account_id,
SUM([order].amount) as order_amount,
COUNT([order].account_id) as order_count
from [order]
GROUP BY [order].account_id
) as orders
ON (trans.account_id = orders.account_id)
group by trans.account_id, orders.order_amount, orders.order_count
order by trans.account_id;
如果您认为帐户可以在任一表中,但不一定同时在两个表中,那么您将使用
full join
。如果是这样,您应该修复您的查询
我建议在join
ing之前聚合这两个表。然后根据条件固定订单:
select coalesce(t.account_id, o.account_id), t.trans_amount, t.trans_count,
o.order_amount, o.order_count
from (select t.account_id, sum(t.amount) as trans_amount, count(*) as trans_count
from trans t
group by t.account_id
) t full join
(select o.account_id,
sum(o.amount) as order_amount,
count(o.account_id) as order_count
from [order] o
group by o.account_id
) o
on t.account_id = o.account_id
order by coalesce(t.account_id, o.account_id);
请注意,通常不需要完全连接。但是,如果需要,应该为其正确编写查询