2015-10-27 53 views
2

我有表MONTHNAME,MonthNumber和整個財年7月份開始,所以我已經分配的值的幾個月就像SQL查詢外與集團參加由

MONTHNAME =七月和MonthNumber = 1
MonthName = August和MonthNumber = 2。 MonthName = August和MonthNumber = 2。

我有另一個域表BudgetCategory它有BudgetCategoryId,BudgetCategoryName。

PurchaseOrder表中有OrderID,PurchaseMonth,BudgetCategoryId。

現在我想查詢找出每個BudgetCategory每月購買SUM(TOTALCOST)。如果沒有購買任何BudgetCategoryId我想在報告中顯示零。表

模式:

CREATE TABLE [dbo].[BudgetCategory](
[BudgetCategoryId] [numeric](18, 0) NOT NULL, 
[BudgetCategoryName] [varchar](50) NULL, 
[TotalBudget] [nvarchar](50) NULL) 


CREATE TABLE [dbo].[PurchaseOrder](
[OrderId] [bigint] NOT NULL, 
[BudgetCategoryId] [bigint] NULL, 
[PurchaseMonth] [nvarchar](50) NULL, 
[QTY] [bigint] NULL, 
[CostPerItem] [decimal](10, 2) NULL, 
[TotalCost] [decimal](10, 2) NULL) 


CREATE TABLE [dbo].[MonthTable](
[MonthNumber] [bigint] NULL, 
[MonthName] [nvarchar](30) NULL) 
+0

每月購買 - 你想知道的總和,計數,真/假呢? – user2989845

+0

我想知道每月每個BudgetCategory的SUM(TotalCost)... –

+0

如何將採購訂單與月份相關聯? –

回答

0
SELECT b.*, m.MonthNumber, q.[BudgetCategoryId], q.[PurchaseMonth], ISNULL(q.[TotalCost],0) 
FROM [dbo].[BudgetCategory] b 
LEFT JOIN 
    (
     SELECT [BudgetCategoryId], [PurchaseMonth], sum([TotalCost]) [TotalCost] 
     FROM [dbo].[PurchaseOrder] p 
     GROUP BY p.[BudgetCategoryId], [PurchaseMonth] 
    ) q ON b.BudgetCategoryId = q.BudgetCategoryId 
LEFT JOIN [dbo].[MonthTable] m ON q.[PurchaseMonth] = m.[MonthName] 
0

試試這個:

select a.BudgetCategoryName, 
ISNULL(c.MonthName,'No purchase') as Month, 
sum(ISNULL(TotalCost,0)) as TotalCost 
from #BudgetCategory a left join #PurchaseOrder b on a.BudgetCategoryId = b.BudgetCategoryId 
left join #MonthTable c on b.PurchaseMonth = c.[MonthName] 
group by a.BudgetCategoryName,c.MonthName 
order by a.BudgetCategoryName 

測試與此數據

INSERT #BudgetCategory 
VALUES (1,'CategoryA',1000), 
(2,'CategoryB',2000), 
(3,'CategoryC',1500), 
(4,'CategoryD',2000) 

INSERT #PurchaseOrder (OrderId,BudgetCategoryId,TotalCost,PurchaseMonth) 
VALUES (1,1,550,'July'), 
(2,1,700,'July'), 
(3,2,600,'August') 

INSERT #MonthTable 
VALUES 
(1,'July'), 
(2,'August') 

它會產生這樣的結果:

enter image description here

讓我知道如果這能幫助你

+0

非常感謝回覆。我想爲Eevery CategoryId顯示月份名稱和總購買量。 月TotalPurchase BudgetCategory 2000年7月組別 八月0組別2000 月2類 –

+0

你並不需要,如果你想找回MONTHNAME加入到MonthTable,因爲你在[DBO]這個值。[PurchaseOrder的] – user2989845

+0

如果有如果沒有購買'CategoryId',那麼在這種情況下將不會出現'PurchaseMonth',查詢將在月份顯示'No Purchase'。 –