Sql server 使用Group By进行外部联接的SQL查询
我有月份表,表中有MonthName、MonthNumber和从7月开始的财政年度,因此我为月份分配了值,如 MonthName=July和MonthNumber=1Sql server 使用Group By进行外部联接的SQL查询,sql-server,sql-server-2008,tsql,group-by,Sql Server,Sql Server 2008,Tsql,Group By,我有月份表,表中有MonthName、MonthNumber和从7月开始的财政年度,因此我为月份分配了值,如 MonthName=July和MonthNumber=1 MonthName=8月,MonthNumber=2月 我有另一个域表BudgetCategory,它有BudgetCategoryId和BudgetCategoryName PurchaseOrder表包含OrderID、PurchaseMonth和BudgetCategoryId 现在我想查询每个预算类别的每月采购量总和(总成
MonthName=8月,MonthNumber=2月 我有另一个域表BudgetCategory,它有BudgetCategoryId和BudgetCategoryName PurchaseOrder表包含OrderID、PurchaseMonth和BudgetCategoryId 现在我想查询每个预算类别的每月采购量总和(总成本)。如果没有任何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)
试试这个:
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')
它将产生以下结果:
让我知道这是否可以帮助您每月采购-您想知道的金额、计数、对/错?我想知道每个月每个预算类别的金额(总成本)…您如何将采购订单与月份联系起来?[PurchaseMonth]=“7月”、“8月”非常感谢您的回复。我想显示每个类别ID的月份名称和TotalPurchase。Month TotalPurchase BudgetCategory 2000年7月类别1 2000年8月0日类别1 2000年8月类别2如果要检索MonthName,则不需要加入MonthTable,因为[dbo].[PurchaseOrder]中有此值如果没有购买
类别ID
,那么就不会有PurchaseMonth
在这种情况下,查询将显示没有购买
在month.@user2989845,我怀疑month表中可能有几列对用户报告有用,我想他只是简单地把这些列放在这里解释他需要什么。
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')