1

I want to SUM t.amount, w.bStake and w.lStake (conditionally)

from transactions t and wagers w.

The amount should always be summed up and between back and profit should be a condition.

If w.Profit is positiv -> t.Amount + w.Back

If w.Profit is negativ -> t.Amount + w.Profit

My code that I use until this point looks like this:

SELECT 
  b.Bookie, 
  (SELECT SUM(t.Amount) FROM Transactions t WHERE t.Bookie = b.id)
FROM Bookie b

My tables are:

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)
Profit : decimal
Back : decimal
Bookie : int (Foreign Key)

How can I solve this Issue? Or is it only possible if I restructure my database? Thanks a lot.

4
  • 1
    JOIN appropriately then sum(t.Amount + case when w.Profit >=0 then w.Back else w.Profit end) Commented Jan 4, 2016 at 17:19
  • 2
    which server? myQql? MsSql? Commented Jan 4, 2016 at 17:29
  • @spiderman sorry I use MsSql Commented Jan 4, 2016 at 20:04
  • @AlexK. my code looks now like this pastebin.com/sVwc3GK0 But I get an error using this code. "Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression." How can I fix this issue? Commented Jan 5, 2016 at 12:36

1 Answer 1

1

you need to join the three tables, and then you can use case to get the sum:

SELECT 
  b.Bookie,
  SUM(CASE mySum WHEN If w.Profit >= 0 then t.Amount + w.Back
             ELSE t.Amount + w.Profit)
FROM Transactions as t inner join Bookie as b on t.Bookie = b.id
INNER JOIN Wagers as w on b.id = w.bookie
Sign up to request clarification or add additional context in comments.

2 Comments

I get two Syntax error if I use your code - in near of if-keyword - in near of then-keyword I used the Code in Microsoft SQL Server Management Studio 2014 What is mySum after CASE keyword? Do I have to change mySum?
pastebin.com/FgWBgRUa This is the current code, but i get an error: Column 'Bookie.Bookie' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. And if I use the Group by Clause, it would be calculated incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.