2015-10-27 54 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'。 –