我需要为将返回所有帐户类型的预算和交易数据的报告构建一个查询。问题是在预算表中存在一些帐户类型,而这些帐户类型不在事务表中,反之亦然。首先,预算:
Select bp.ProjectID, bp.AccountCategoryID, bp. FiscalYearPeriod, bp.Amount AS BudgetAmount
from BudgetsProject bp
where bp.ProjectId = 1063 and bp.FiscalYearPeriod = 201510
SELECT f.ProjectKey, f.AccountCategoryKey, f.PostFiscalPeriodKey, sum(f.IncomeAmount) as IncomeAmount, sum(f.ExpenseAmount) as ExpenseAmount, sum(f.TransactionCount) as TransactionCount
FROM ActualCategoryPivotAccountTypeSubAccountFact f
Where f.ProjectKey = 1063 and f.PostFiscalPeriodKey = 201510
Group by f.ProjectKey, f.AccountCategoryKey, f.PostFiscalPeriodKey
问题是,当我尝试完全联接这两个表时,并不是每个AccountCategoryKey值都在两个表的每一行中,因此我最终丢失了数据行。我需要在结果集中显示每个可能的Accountcategory,并在相应的事务或预算不可用的地方使用NULL。
我知道答案是存在的:What kind of join do I need to use to create one table from many?,但表必须在匹配的项目、AccountCategory和FiscalYear字段上联接,我不确定如何将那里提出的解决方案应用于需要在多个条件上联接的情况。
编辑:如果这有帮助,我在这里添加了重新创建表的逻辑:
Create Table BudgetsReport (
AccountCategoryID int NOT NULL,
ProjectID int NOT NULL,
FiscalYearPeriod char(6) NOT NULL,
Amount numeric(10,2)
);
Create Table ActualCategoryPivotAccountTypeSubAccountFact (
PostFiscalPeriodKey int,
ProjectKey int,
AccountCategoryKey int,
IncomeAmount money,
ExpenseAmount money,
TransactionCount int
);
INSERT INTO BudgetsReport VALUES (1063, 5, 201510, 1626.00), (1063, 15, 201510, 8.00), (1063, 26, 201510, 1757.00), (1063, 36, 201510, 0.00), (1063, 38, 201510, 6508.00), (1063, 41, 201510, 115000.00), (1063, 42, 201510, 667.00), (1063, 43, 201510, 167.00), (1063, 51, 201510, 7289.00), (1063, 54, 201510, 21.00), (1063, 81, 201510, 138164.00), (1063, 87, 201510, 83.00), (1063, 88, 201510, 54.00), (1063, 90, 201510, 833.00);
INSERT INTO ActualCategoryPivotAccountTypeSubAccountFact VALUES (1063, 2, 201510, 0.00, 0.00, 214), (1063, 5, 201510, 0.00, 1004.42, 1), (1063, 15, 201510, 0.00, 3.92, 1), (1063, 26, 201510, 0.00, 1556.44, 10), (1063, 34, 201510, 0.00, 26.37, 1), (1063, 36, 201510, 0.00, 0.00, 19), (1063, 38, 201510, 0.00, 5764.65, 10), (1063, 41, 201510, 0.00, 131857.10, 29), (1063, 51, 201510, 0.00, 6456.27, 10), (1063, 54, 201510, 0.00, .44, 1), (1063, 87, 201510, 0.00, 28.30, 1), (1063, 90, 201510, 0.00, 545.96, 120), (1063, 93, 201510, 149945.01, 0.00, 213);
发布于 2015-05-13 00:00:00
我认为,在where子句(WHERE f.PostFiscalPeriodKey = 201510 and f.ProjectKey = 1063
)中使用这些谓词会杀死您。您可以将它们移到on子句中,但是使用完整连接时,我不知道结果会是什么。也许可以尝试使用带有约束的派生表,然后连接到派生表。
select
...
FROM
(
select *
from
ActualCategoryPivotAccountTypeSubAccountFact
where
PostFiscalPeriodKey = 201510
and ProjectKey = 1063) F
full join BudgetsProject bp
on f.PostFiscalPeriodKey = bp.FiscalYearPeriod
and bp.ProjectId = f.ProjectKey
and bp.AccountCategoryId = f.AccountCategoryKey
您还可以尝试使用所有可能的键构建一个驱动程序表,然后外部连接到该表。不过,我不确定这将如何执行。
发布于 2015-05-13 22:19:07
我建议使用CTE并存储可能的帐户类型和期间。然后向左加入实际情况和预算。
另一种选择是首先使用这些值创建一个临时表,然后执行select操作。
https://stackoverflow.com/questions/30195167
复制相似问题