2012-04-18 77 views
3

任何人都可以幫我一個查詢嗎? 我有一個數據庫,看起來像這樣: 表費用mysql總額付款

paydate  receiver payment 
2011-05-06  SOLO  3000 
2011-05-08  Walmart 5000 
2011-05-09  McDonalds 400 
2011-05-08  Korona  700 
2011-05-08  Walmart 1000 
2011-05-09  BigZ  1300 

我要計算在當天的所有款項的總和時,最高支付已完成。 的結果應該是這樣的:

paydate  payment 
2011-05-08 6700 

我設法找到最大的支付和它的paydate:

SELECT payment, paydate FROM expenses WHERE payment=(SELECT max(payment) FROM expenses); 

但只給了我最大的支付和paydate,我需要一個當天的付款總額。

+0

檢查有關mysql的集合函數的信息,還有很多有關sql練習的網站,例如, http://sql-ex.ru/ – llamerr 2012-04-18 11:53:38

+0

'SELECT SUM(支付)作爲sum_payment,paydate FROM GROUP BY paydate ORDER BY sum_payment DESC LIMIT 1' – 2012-04-19 12:34:16

回答

1
CREATE TABLE `t` (
`t1` INT(10) NULL DEFAULT NULL, 
`t2` DATE NULL DEFAULT NULL, 
`t3` INT(10) NULL DEFAULT NULL 
) 


INSERT INTO `t` (`t1`, `t2`, `t3`) VALUES 
(1, '2012-04-19', 100), 
(2, '2012-04-18', 200), 
(3, '2012-04-18', 300), 
(4, '2012-04-19', 150); 

和查詢:

select sum(t3), t2 from t where t2=(select t2 from t where t3 = (select max(t3) from t)) 

結果給了我們500 2012-04-18,即金額和日期

或檢查:

select t1, sum(t3), t2 from t where t2=(select t2 from t where t3 = (select max(t3) from t)) group by t1 
+0

非常感謝您的幫助! – Gipsy 2012-04-18 12:19:46

7

查詢改成這樣:

select sum(payment), paydate 
from expenses 
where paydate=(
    select paydate from expenses 
    where payment = (
    select max(payment) from expenses) 
); 

,我已經使用了SUM功能。

編輯:以前的輸出不是要求的。這裏是我以前和現在使用的sqlfiddle

+0

你忘了日期費用:'GROUP BY paydate' – 2012-04-18 11:50:43

+2

@ daemonfire300我不需要這麼做,因爲可能有兩個/多個接收者在不同的日子接收*相同的*(和**最高**)付款。 – hjpotter92 2012-04-18 11:53:25

+2

是的,但作者說:_我必須計算當天所有支付**的總和** _ – 2012-04-18 11:57:06

2

至於我可以說,其他答案沒有考慮到可以有多個日期和最高付款額相同。我的回答如下回答所有可能的答案:

SELECT sum(payment) total_amount, paydate 
FROM expenses 
WHERE paydate in (SELECT paydate 
        From expenses 
        WHERE payment = (Select max(payment) from expenses)) 
group by paydate 
order by total_amount desc 

祝你好運!