2

I need to sum a group for my query. Something like:

SELECT customer_id, SUM(weekly) FROM earnings GROUP BY customer_id

The above works, but I need something a bit more complex, and my query is like this:

SELECT
    (SELECT SUM(weekly) FROM earnings) + 
    (SELECT SUM(day_earnings) FROM earnings) / .75

The above makes the sum of all the earnings, weekly and daily, but I need to group them by customer_id like in the first example. How do I achieve this?

4 Answers 4

3

According to the order of operations in your attempt above, it's the SUM(day_earnings) only that's divided by .75. If it should be the weekly & day_earnings sums together, then put parentheses around them as (SUM(weekly) + SUM(day_earnings)) / 0.75 AS earnings.

SELECT 
  customer_id,
  customer_name,
  SUM(weekly) + SUM(day_earnings) / 0.75 AS earnings
FROM earnings JOIN customers ON earnings.customer_id = customers.customer_id
GROUP BY customer_id, customer_name
Sign up to request clarification or add additional context in comments.

5 Comments

thanks! how can I also join that customer_id with the table customers to get the names? thank you!
See change above. customer_name added to select list and group by list, and joined in the FROM
excellent! thanks! please notice however that customer_id needs the table before it since it exists in both. Thanks for your help!
why you did not use of table name in the sum() ? I thought if I'm using join and sum() then I should use some thing like this: sum(table.column), that is not correct ?
@Sajad The table name is only necessary if more than one table in the FROM has a column of the same name. Otherwise the column name can be used alone, just as it could in the plain SELECT.
0

Does this work?

SELECT customer_id, SUM(weekly + (day_earnings / .75)) 
FROM earnings 
GROUP BY customer_id

Comments

0
SELECT 
  customer_id, 
  SUM(weekly) weekly, 
  SUM(day_earnings) daily, 
  ((SUM(weekly) + SUM(day_earnings)) / .75) calc
FROM 
  earnings 
GROUP BY 
  customer_id 

Comments

0

Can't you just do:

SELECT customer_id, (SUM(weekly) + SUM(day_earnings) / .75) AS earnSum FROM earnings GROUP BY customer_id

Comments

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.