SQL如何正确分组行

时间:2015-12-15 09:43:13

标签: sql-server group-by

我有三张桌子:

**Bookie**:

------------

Id : int (Primary Key)

Bookie : varchar
**Transactions**:

-------------------

Id : int (Primary Key)

Date : date

Bookie : int (Foreign Key)

Amount : decimal 
Wagers:

Id : int (Primary Key)

Stake : decimal

Bookie : int (Foreign Key)

Wagers表不是完整的,但对于sql这些列就足够了。

到目前为止,我尝试过这个sql代码:

SELECT Bookie.Bookie, SUM(Amount), Wagers.Stake FROM Transactions
JOIN Bookie on Transactions.Bookie = Bookie.Id
JOIN Wagers on Bookie.Id = Wagers.Bookie
GROUP BY Bookie.Bookie, Wagers.Stake

但我的输出看起来像这样:

Bookie | Amount | Stake
William Hill | 600.00 | 14.70
Bet at Home | 500.00 | 30.00
Bet at Home | 500.00 | 45.00
Bet at Home | 500.00 | 50.00
Bet365 | 10200.00 | 100.00

它应该是这样的:

Bookie | Amount | Stake
William Hill | 600.00 | 14.70
Bet at Home | 500.00 | 125.00
Bet365 | 10200.00 | 100.00

有谁知道如何解决这个问题?

由于

2 个答案:

答案 0 :(得分:2)

您需要汇总Stake

SELECT Bookie.Bookie, SUM(Amount) AS Amount, SUM(Wagers.Stake) AS Stake
FROM Transactions
JOIN Bookie 
  ON Transactions.Bookie = Bookie.Id
JOIN Wagers 
  ON Bookie.Id = Wagers.Bookie
GROUP BY Bookie.Bookie;

修改

SELECT Bookie, MAX(Amount) AS Amount, SUM(Stake) AS Stake
FROM (
  SELECT Bookie.Bookie, SUM(Amount) AS Amount, Wagers.Stake 
  FROM Transactions
  JOIN Bookie on Transactions.Bookie = Bookie.Id
  JOIN Wagers on Bookie.Id = Wagers.Bookie
  GROUP BY Bookie.Bookie, Wagers.Stake
) AS sub
GROUP BY Bookie;

答案 1 :(得分:0)

使用来自两个不同表的聚合,最好预先聚合数据,然后才加入:

select 
  b.bookie, 
  t.sum_amount, 
  w.sum_stake
from bookie b 
join
(
  select bookie, sum(amount) as sum_amount
  from transactions
  group by bookie
) t on t.bookie = b.id
join       
(
  select bookie, sum(stake) as sum_stake
  from wagers 
  group by bookie
) w on w.bookie = b.id;

由于您只对每个表中的一个聚合感兴趣,您甚至可以在select子句中使用相关子查询。易于编写和易于阅读: - )

select 
  b.bookie, 
  (select sum(t.amount) from transactions t where t.bookie = b.id),
  (select sum(w.stake) from wagers w where w.bookie = b.id)
from bookie b