表格结构:
当前查询:
;WITH cte (clientid, invoiceid, paid, disc)
As
(
Select client_id clientId, vinvoice_Id invoiceId, sum(amount_received) paid, sum(discount) disc
From tbl_Vendor_Invoice_Payment
Group by vinvoice_id, client_id
)
Select I.date, I.total_price, Isnull(paid, 0) Paid, (Total_price - Isnull(paid,0) - Isnull(disc,0)) Balance
From tbl_Vendor_invoice I Left join cte On I.client_id = cte.clientId
And I.vinvoice_id = cte.invoiceid
order by vinvoice_id desc
输出:
但我的要求是获得过去六个月的月度结果如下:
Month total_price Paid Balance
--------------------------------------------
October 800.00 750.00 50.00
September 200.00 100.00 100.00
August 350.00 350.00 0.00
.........
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
SELECT DATEADD(month,DATEDIFF(month,0,[vi.date]),0), SUM(vi.total_price) total_price, SUM(vip.amount_received) Paid, SUM(vip.balance) balance
FROM tbl_Vendor_Invoice vi
INNER JOIN tbl_Vendor_Invoice_Payment vip
on vi.vInvoice_Id = vip.vInvoice_Id
WHERE [vi.date] >= DATEADD(month, -6, DATEADD(month,DATEDIFF(month,0,[vi.date]),0))
GROUP BY DATEADD(month,DATEDIFF(month,0,[vi.date]),0)
这将在该月的第一天(包括年份)进行分组。如果您只想要月份名称,可以使用DATENAME(month, [date])
。
答案 1 :(得分:0)
我找到了答案:
;WITH cte (clientid, invoiceid, paid, disc)
As
(
Select client_id clientId, vinvoice_Id invoiceId, sum(amount_received) paid, sum(discount) disc
From tbl_Vendor_Invoice_Payment
Group by vinvoice_id, client_id
)
SELECT DATENAME(month, [date]) mMonth, SUM(Isnull(paid, 0)) Amount_Paid
FROM tbl_Vendor_Invoice vi
INNER JOIN cte vip on vi.vinvoice_Id = vip.invoiceid
WHERE [date] >= DATEADD(month, -6, DATEADD(month,DATEDIFF(month,0,getdate()),0))
GROUP BY DATENAME(month, [date]), MONTH([date])
ORDER BY MONTH([date])