0

i have a DB with all transactions of my online webshop, and im trying to make a query to print out a simple financial statement.

it will be printed in a table like this:

<th>month</th>
<th>number of sales</th>
<th>money in</th>
<th>money out</th>
<th>result</th>

the query that fails with: #1111 - Invalid use of group function

SELECT 
month(transaction_date) as month,
count(incoming_amount > '0') as number_of_sales,
sum(incoming_amount / 1.25) as money_in,
sum(outgoing_amount) as money_out,
sum((incoming_amount / 1.25) - sum(outgoing_amount)) as result
FROM myDB WHERE year(timestamp) = '2011' order by id desc");

Can anyone point me in the right direction?

1
  • Do you really have a table called myDB ? Commented Aug 31, 2011 at 13:18

3 Answers 3

2
SELECT 
month(transaction_date) as month,
sum(if(incoming_amount>0,1,0)) as number_of_sales,
sum(incoming_amount)/1.25 as money_in,
sum(outgoing_amount) as money_out,
sum((incoming_amount/1.25)-outgoing_amount) as result
FROM myDB 
WHERE timestamp>='2011-01-01 00:00:00' AND timestamp<='2011-12-11 23:59:59'
GROUP BY month;
  1. you need to specify a column when using aggregate function
  2. year(timestamp) does not make use on mysql index (if you have define an index on timestamp)
  3. aggregate function on count(incoming_amount > '0') is incorrect
  4. sum does not looks correct too
Sign up to request clarification or add additional context in comments.

Comments

1

Add group by statement:

SELECT 
month(transaction_date) as month,
count(incoming_amount > '0') as number_of_sales,
sum(incoming_amount / 1.25) as money_in,
sum(outgoing_amount) as money_out,
sum((incoming_amount / 1.25) - sum(outgoing_amount)) as result
FROM myDB WHERE year(timestamp) = '2011' GROUP BY month order by id desc");

Comments

1

Building on @ajreal's answer, you can speed this query up by reusing previously calculated values like so:

SELECT s.*,
       (s.money_in - s.money_out) as result 
FROM
  (
  SELECT 
    month(transaction_date) as month,
    /*  year(transaction_date) as year   */  
    sum(incoming_amount>0) as number_of_sales, -- true = 1, false = 0.
    sum(incoming_amount)/1.25 as money_in,
    sum(outgoing_amount) as money_out,
  FROM myDB 
  WHERE transaction_date BETWEEN '2011-01-01 00:00:00' AND '2011-12-31 23:59:59'
  GROUP BY /*year,*/ month DESC;
  ) AS s

If you select beyond the year, uncomment the relevant sections.
Note you can add a DESC modifier to group by to get the most recent results first.

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.