SQL Merge with Partial Matching表

时间:2017-11-28 08:30:33

标签: sql-server merge

我已经调查了很多与两个表的SQL合并相关的帖子,并且我非常熟悉SQL中的合并,但这个让我感到难过。这是一个场景:我有一个按等级和货币存储的值表,即
GradeID = 3,Rate = 175,CurrencyID = 5 有五个等级,每个等级都有不同的值,这些是GBP中每个等级的默认值(CurrencyID = 5) 我有另一个表格,其中包含一个额外的财政期间列,这是该费率适用的月份日期的第1列,即 GradeID = 3,Rate = 150,FiscalPeriodID = 95,CurrencyID = 5 并非每个等级,会计期间和货币的所有值都与默认值不同,因此用户只会在必要时输入差异。我有一个Windows窗体供用户查看和更新​​这些值,但我很难同时显示两个表的结果 对于没有存储数据(即仅应用默认值)的情况,理想的解决方案是屏幕将显示当前会计期间的默认值,即95 = 01/11/2017,但是哪里有值输入后,表格将按等级显示已更改的行,但按每个具有非默认值的会计期间进行分组 设置默认值的当前会计期间的第一部分相对容易:

SELECT [RateID], [GradeID], [ChargeRate],   
(SELECT [FiscalPeriodID] FROM [dbo].[FiscalPeriod] WHERE MONTH([FiscalPeriod]) = 
MONTH(GETDATE()) AND YEAR([FiscalPeriod]) = YEAR(GETDATE())) AS [FiscalPeriodID]   
,[CurrencyID]   
FROM [dbo].[DefaultChargeRateByLevel]

但我想要做的是执行一个查询,该查询执行此简单选择(当没有任何财务期间返回结果时)或合并默认值和更新值以显示每个会计期间5个值的组。
我最初的想法是使用每个查询的结果填充两个临时表,然后执行合并,但我无法弄清楚如何为每个值组填充财务期。这是我到目前为止,但它失败并出现以下错误: 无法将值NULL插入列'FiscalPeriodID',表'tempdb.dbo。#TempTarget < / p>

IF OBJECT_ID('tempdb..#TempTarget') IS NOT NULL
DROP TABLE #TempTarget
IF OBJECT_ID('tempdb..#TempSource') IS NOT NULL
DROP TABLE #TempSource

SELECT  
    [GradeID]
    ,[ChargeRate]
    ,[FiscalPeriodID]
    ,[CurrencyID]       
INTO #TempTarget 
FROM (SELECT 
    [GradeID]
    ,[ChargeRate]
    ,[FiscalPeriodID]
    ,[CurrencyID]
FROM 
    [dbo].[ChargeRateByProjectAndLevel]) AS A

SELECT * FROM #TempTarget

SELECT  
    [GradeID]
    ,[ChargeRate]
    ,[FiscalPeriodID]
    ,[CurrencyID]       
INTO #TempSource
FROM (SELECT 
    D.[GradeID]
    ,D.[ChargeRate]
    ,M.[FiscalPeriodID]
    ,D.[CurrencyID]
FROM 
    [dbo].[DefaultChargeRateByLevel] AS D
LEFT JOIN #TempTarget AS M ON M.[GradeID] = D.[GradeID]
                    AND M.[CurrencyID] = D.[CurrencyID]
) AS B

SELECT * FROM #TempSource

/* Now merge rates data from temp table to FxRates table */
    MERGE #TempTarget AS [Target]
    USING  #TempSource AS [Source]
    ON [Source].[GradeID]           = [Target].[GradeID]        
    AND [Source].[CurrencyID]       = [Target].[CurrencyID]     

    WHEN NOT MATCHED BY TARGET THEN
    INSERT (
        [GradeID]
        ,[ChargeRate]
        ,[FiscalPeriodID]
        ,[CurrencyID]
    )
    VALUES  (
       [Source].[GradeID]
        ,[Source].[ChargeRate]
        ,[Source].[FiscalPeriodID]
        ,[Source].[CurrencyID]
    );

SELECT * FROM #TempTarget

0 个答案:

没有答案