我有一个数据库,包含我在线网上商店的所有交易,我试图查询打印出简单的财务报表。
它会打印在这样的表格中:
<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");
有人能指出我正确的方向吗?
答案 0 :(得分: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;
year(timestamp)
没有使用mysql索引(如果你在时间戳上定义了一个索引)count(incoming_amount > '0')
上的汇总功能不正确sum
看起来也不正确答案 1 :(得分:1)
按语句添加分组:
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");
答案 2 :(得分:1)
在@ 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
修饰符,以便首先获得最新结果。