简体   繁体   中英

How to SUM() columns based on other column values SQL

I have some data of people betting. The bets can be 'won', 'lost' or 'pending'. I want to get the amount people have bet and the amount they have won.

The amount won should be amount * odds BUT if it was a bonus bet (1) it will subtract the original stake (amount) from the total. Bonus bets do not include the original stake in the total win amount.

Also amountbet should not include the amount from Bonus bets as they are more tokens then lost money. Hopefully in one SQL.

I have got this far....

SELECT *, SUM(amount) AS amountbet 
FROM bets 
WHERE club = 2 
  AND result <> 'pending'
  AND bonus = 0
GROUP BY user

And I also have this SQL statement

SELECT *, SUM(amount * odds - (amount * bonus)) AS amountwon 
FROM bets 
WHERE club = 2 
  AND result = 'won' 
GROUP BY user

So if it is a bonus bet it will subtract amount or it will subtract amount * 0 ie = 0

I can probably work around if not but if there is an elegant way I would like to try.

Thanks

The DB table looks like this

ID | user | amount | odds | result | bonus | club | 

You can use CASE expressions inside the SUM() to apply the filtering you want.

SELECT
  user,
  SUM(                                   amount    )  AS total_amount,
  SUM(CASE WHEN result  = 'won'     THEN amount END)  AS amount_won,
  SUM(CASE WHEN result <> 'pending' THEN amount END)  AS amount_bet
FROM
  bets 
WHERE
  club = 2 
GROUP BY
  user

There's no ELSE in those, which implicitly does ELSE NULL , and then NULL s are effectively ignored by aggregates.

You can use conditional aggregation using a case expression,

SELECT User,
  sum (case when result in ('won','lost') then amount end) as AmountBet,
  sum (case when result='won' then amount end) as AmountWon
FROM bets 
WHERE club = 2 
GROUP BY user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM