2015-12-15 70 views
1

我有三個表:SQL如何分組行正確

**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) 

下注表不是全部,但對於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 

有誰知道要實現這個問題?

感謝

+0

,而不是'Wagers.Stake'做'總和(Wagers.Stake)作爲Stake'和Stake' –

+0

@Gohan的數據庫使用的是刪除'組? –

+0

我不明白,但我可以看到別人做的,所以我會把它留給他們。 – Strawberry

回答

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; 
+0

這就是我已經試過的,但我不會工作。 輸出看起來像這樣: William Hill | 600.00 | 29.40 // 14.70(賭金)將是正確的 Bet at Home | 1500.00 | 125.00 // 500.00(金額)將是正確的 Bet365 | 10200.00 | 200.00 // 100.00(股權)將是正確的 – Gohan

+0

@Gohan檢查更新並準備http:// sqlfiddle。com – lad2025

+1

謝謝你現在都是完美的:) – Gohan

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 
+1

謝謝你,第一次正常工作 第二個不起作用,因爲附近'from'或b.bookie在選擇子句 – Gohan

+0

後沒有找到多部分標識符啊,缺少一個逗號。我已經添加了它。 –

+0

謝謝,我錯過了。你的回答也是正確的,但另一個人發佈的時間較早,這就是爲什麼我將他的答案標記爲正確的......儘管我使用第二種解決方案,因爲它很簡單。 – Gohan