我可能會離開這裏。但嘗試:
select top 1
p.amount, c.amount, n.amount
from payment c
inner join payment p ON p.pay_date < c.pay_date
inner join payment n ON n.pay_date > c.pay_date
where monthname(c.paydate) LIKE 'April'
and year(c.pay_date) LIKE 2012
order by p.pay_date DESC, n.pay_date ASC
編輯,我沒有正確地讀你的問題。我正在去往,現在和下個月。 1分鐘,我會再試一次。
select top 1
p.amount AS april_amount, c.amount AS current_month_amount, n.amount AS previous_month_amount
from payment c
inner join payment p ON monthname(p.pay_date) = 'April' AND year(p.pay_date) = 2012
inner join payment n ON n.pay_date > c.pay_date
where monthname(c.paydate) = monthname(curdate())
and year(c.pay_date) = year(curdate())
order by n.pay_date ASC
這假定每個月只有1個條目。
好的,所以我沒有寫在MySQL一段時間。這裏是您的示例數據什麼工作:
select
p.amount AS april_amount, c.amount AS current_month_amount, n.amount AS previous_month_amount
from payment AS c
inner join payment AS p ON monthname(p.pay_date) LIKE 'April' AND year(p.pay_date) LIKE 2012
inner join payment AS n ON n.pay_date < c.pay_date
where monthname(c.pay_date) LIKE monthname(curdate())
and year(c.pay_date) LIKE year(curdate())
order by n.pay_date DESC
limit 1
比上月表連接的直覺相反命名n
,但這個工程。我在WAMP安裝中驗證了它。
要處理每月的聚合,您可以使用子選擇。性能可能會受到非常大的表格影響(數百萬行或更多)。
SELECT SUM(a.amount) AS april_amount,
(
SELECT SUM(c.amount)
FROM payment c
WHERE MONTH(c.pay_date) = MONTH(CURDATE())
) AS current_month_amount,
(
SELECT SUM(p.amount)
FROM payment p
WHERE MONTH(p.pay_date) = MONTH(CURDATE() - INTERVAL 1
MONTH)
) AS previous_month_amount
FROM payment a
WHERE MONTHNAME(a.pay_date) = 'April'
AND YEAR(a.pay_date) =2012
如果每個月有幾個條目並且迄今爲止感謝一百萬的情況下會怎麼樣,生病嘗試並讓您知道結果? – dames
'previous_month_amount'會更準確地命名爲'previous_payment_amount' –
我創建了表格並意識到我的錯誤。在這裏你去: –