在年份和时间上组合多个SQL视图月

时间:2014-01-13 14:33:20

标签: sql

我有一个包含许多表的SQL Server数据库(2012 express)。 我基于底层表的不同组合生成了三种不同的VIEWS。 这些视图中的每一个都包含三列:Year,Month&总 3个视图中每个视图中的总列数具有不同的度量。 我想要做的是将三个Totals组合成一个View

我尝试使用以下脚本 -

SELECT b.[Year], b.[Month], b.Fees AS [Billing],
       f.Estimate AS [Estimate],
       w.Fees AS [WIP]

FROM MonthlyBillingTotals AS b

FULL JOIN MonthlyFeeEstimates AS f
ON (b.[Year] = f.[Year] AND b.[Month] = f.[Month])

FULL JOIN MonthlyInstructionsWIP AS w
ON (b.[Year] = w.[Year] AND b.[Month] = w.[Month])

ORDER BY b.[Year], b.[Month]

最初我尝试过INNER JOINS但当然除非在第一个视图(MonthlyBillingTotals)中存在年/月组合,否则它不会出现在合并查询中。因此我尝试了FULL JOINS,但问题是我在Year和Month列中得到了一些NULLS,当它们在第一个视图(MonthlyBillingTotals)中不存在时。

如果三个视图中的数据如下 -

enter image description here

然后我想要的是 -

enter image description here

甚至更好(如果可能的话) -

enter image description here

缺少月份

3 个答案:

答案 0 :(得分:2)

您可以尝试使用UNION子查询从表中构建完整的月/年列表,然后使用它来驱动您的联接..这样的事情:

SELECT a.[Year], a.[Month], b.Fees AS [Billing],
       f.Estimate AS [Estimate],
       w.Fees AS [WIP]

FROM (SELECT a.[Year], a.[Month] FROM MonthlyBillingTotals AS a
      UNION 
      SELECT b.[Year], b.[Month] FROM MonthlyFeeEstimates AS b
      UNION 
      SELECT c.[Year], c.[Month] FROM MonthlyInstructionsWIP AS c) AS a 

LEFT OUTER JOIN MonthlyBillingTotals AS b
ON (a.[Year] = b.[Year] AND a.[Month] = b.[Month])

LEFT OUTER JOIN MonthlyFeeEstimates AS f
ON (a.[Year] = f.[Year] AND a.[Month] = f.[Month])

LEFT OUTER JOIN MonthlyInstructionsWIP AS w
ON (a.[Year] = w.[Year] AND a.[Month] = w.[Month])

ORDER BY a.[Year], a.[Month]

答案 1 :(得分:0)

您可以设置一个包含年份和月份的小日期表,然后使用它连接视图,并使用ISNULL(variable,0)函数将NULL替换为0.另一个选项而不是日期表将使用公用表表达式,用于生成要加入的日期范围。在任何情况下,我建议你查找日期表(或数字表),它可以是一个非常有用的工具。

编辑:添加了一个关于如何创建日期表的示例(供参考):

declare @year_month table (y int, m int)

;with cte as (
  select cast('2000-01-01' as datetime) date_value
  union all
  select date_value + 1
  from cte   
  where date_value + 1 < '2010-12-31'
)

insert @year_month (y, m) 
select distinct year(date_value), month(date_value)
from cte
order by 1, 2
option (maxrecursion 0)

select * from @year_month

答案 2 :(得分:0)

这是完全未经测试的,但看看这是否能解决您的问题:

SELECT b.[Year], b.[Month], Coalesce(b.Fees, '0') AS [Billing],
       Coalesce(f.Estimate,'0') AS [Estimate],
       Coalesce(w.Fees,'0') AS [WIP]

FROM MonthlyBillingTotals AS b

LEFT JOIN MonthlyFeeEstimates AS f
ON (b.[Year] = f.[Year] AND b.[Month] = f.[Month])

LEFT JOIN MonthlyInstructionsWIP AS w
ON (b.[Year] = w.[Year] AND b.[Month] = w.[Month])

ORDER BY b.[Year], b.[Month]

如果没有找到任何内容,Coalesce函数会输入一个'0'值,而当年和月匹配时,左连接只应加入MonthlyFeeEstimates和MonthlyInstructionsWIP的部分。