2011-08-31 144 views
0

我有一個數據庫與我的在線網上商店的所有交易,並試圖進行查詢打印出一個簡單的財務報表。幫助一個MySQL查詢

它會在一個表格打印:

<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

你真的有一個名爲'myDB'的表嗎? –

回答

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也看起來不正確
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"); 
+0

謝謝!當然.. –

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以獲得最新的結果。