使用Group By的外部联接的SQL查询

时间:2015-10-27 21:46:31

标签: sql-server sql-server-2008 tsql group-by

我有 Months 表,其中MonthName,MonthNumber和Fiscal Year从7月开始,所以我已将值分配给月份,如

MonthName = July和MonthNumber = 1
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) 

2 个答案:

答案 0 :(得分:0)

+'folder/_file.sass'

答案 1 :(得分: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

如果这可以帮到你,请告诉我