【问题标题】:help with a mysql querymysql查询帮助
【发布时间】:2011-11-07 14:16:23
【问题描述】:

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

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

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

谁能指出我正确的方向?

【问题讨论】:

  • 你真的有一个叫myDB的表吗?

标签: mysql sql mysql-error-1111


【解决方案1】:
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 &gt; '0') 上的聚合函数不正确
  4. sum 看起来也不正确

【讨论】:

    【解决方案2】:

    按语句添加分组:

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

    【讨论】:

      【解决方案3】:

      基于@ajreal 的回答,您可以通过重用之前计算的值来加快查询速度,如下所示:

      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 以首先获取最新结果。

      【讨论】: