我有一張表,我需要在發票上創建三個基於月份的總和。SQL嵌套總和查詢
使用「invoice_number」字段的前三個字母計算總和,然後爲該特定發票類型添加所有「Invoice_Amount」。數據
例 INVOICE_NUMBER - MSP-1111 發票金額 - $ 2100.00
我要那麼它格式,例如計算這個基礎關閉幾個月
Year | Month | Total MSP Invoices| Total PS Invoices | Total App Invoice
我能夠得到的幾個月裏,然而,所有月份的總數都是相同的,而不是特定於那個月。以下是我正在使用的查詢。
我想顯示過去12個月。
select year(date_invoice) as Year,
Case month(date_invoice)
When 1 Then 'Jan'
When 2 Then 'Feb'
When 3 Then 'March'
When 4 Then 'April'
When 5 Then 'May'
When 6 Then 'June'
When 7 Then 'July'
When 8 Then 'Aug'
When 9 Then 'Sept'
When 10 Then 'Oct'
When 11 Then 'Nov'
When 12 then 'Dec'
End
as Month,
(Select sum(invoice_amount) from invoices where Invoice_number like 'MSP%') as 'MSP',
(Select sum(invoice_amount) from invoices where Invoice_number like 'PS%') as'PS',
(Select sum(invoice_amount) from invoices where Invoice_number like 'APP%') as 'App'
from invoices
Where convert(nvarchar(50), date_invoice,100) > DATEADD(month, -12, getdate())
Group by year(date_invoice), month(date_invoice)
Order by year(date_invoice), month(date_invoice)
任何幫助都會很棒!
您正在使用哪些DBMS? –