0

我有一个数据库,其中包含我的在线网上商店的所有交易,我试图进行查询以打印出一份简单的财务报表。

它将打印在这样的表格中:

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

查询失败:#1111 - 组函数的使用无效

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");

谁能指出我正确的方向?

4

3 回答 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. 使用聚合函数时需要指定一列
  2. year(timestamp)不适用于 mysql 索引(如果您在时间戳上定义了索引)
  3. 聚合函数count(incoming_amount > '0')不正确
  4. sum看起来也不正确
于 2011-08-31T12:46:21.040 回答
1

添加 group by 语句:

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");
于 2011-08-31T12:48:01.700 回答
1

在@ajreal's answer的基础上,您可以通过重用以前计算的值来加快此查询,如下所示:

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

如果您选择超出年份,请取消注释相关部分。
请注意,您可以添加DESC修饰符以group by首先获取最新结果。

于 2011-08-31T13:08:59.220 回答