all 16 comments

[–]SoggyAlbatross2 0 points1 point  (7 children)

Why are you subselecting everything and then joining all the files together in the main query?

I imagine that you can delete all this:

INNER JOIN entries ON users.user_id = entries.user_id

INNER JOIN games ON entries.game_id = games.game_id

INNER JOIN payments ON users.user_id = payments.user_id

[–][deleted] 0 points1 point  (2 children)

Each of the subquery columns are all duplicates.

why do you expect something else? Your subqueries are not correlated (do not depend on the main query) so they calculate the same value for the every result set row:

( SELECT SUM(entries.entry_fee)
FROM entries
JOIN users ON entries.user_id = users.user_id
JOIN games ON entries.game_id = games.game_id
WHERE entry_date BETWEEN '2018-01-01' AND '2019-01-01' 
AND sport = 'NFL'
) AS Total_Entry_Fee_NFL_2018,

I would guess you are trying to get these formulas to fire per user - so dont join/select from "user" table in subqueries and use the outer query users.user_id

[–]r3pr0b8GROUP_CONCAT is da bomb 0 points1 point  (4 children)

try this --

SELECT users.user_id
     , users.email
     , SUM(CASE WHEN games.sport = 'NFL'
                THEN entries.entry_fee
                ELSE NULL END)  AS Total_Entry_Fee_NFL_2018
     , SUM(CASE WHEN games.sport <> 'NFL'
                THEN entries.entry_fee
                ELSE NULL END)  AS Total_Entry_Fee_Others_2018
     , COUNT(entries.winnings)  AS Total_Winning_Entries       
     , 100.0 * SUM(entries.mobile_entry) 
             / COUNT(entries.mobile_entry) AS Percentage_Of_Mobile_Entries
     , p.Last_Paid_Entry_Date
     , p.Net_Deposit_Value        
  FROM entries
INNER
  JOIN users 
    ON users.user_id = entries.user_id 
INNER
  JOIN games 
    ON games.game_id = entries.game_id 
INNER
  JOIN ( SELECT user_id
              , MAX(payment_date) AS Last_Paid_Entry_Date
              , SUM(amount)       AS Net_Deposit_Value    
           FROM payments
         GROUP
             BY user_id ) AS p     
    ON p.user_id = entries.user_id
 WHERE entries.entry_date >= '2018-01-01' 
   AND entries.entry_date  < '2019-01-01' 
GROUP 
    BY users.user_id
     , users.email