在t-SQL中减去同一行中的非连续值

时间:2015-09-28 14:59:47

标签: sql sql-server

我有一个包含年度数据点和季度数据点的数据表。我想从相应的先前年度条目中减去季度数据点,例如2014年 - 2014年第3季度,使用t-SQL。我为每个条目都有一个id变量,加上一个reconcile id变量,显示哪个季度条目对应于哪个年度条目。见下文:

CurrentDate PreviousDate Value  Entry Id  Reconcile Id  Annual/Quarterly
9/30/2012   9/30/2011    112      2            3             Annual
9/30/2013   9/30/2012    123      1            2             Annual
9/30/2014   9/30/2013    123.5    9            1             Annual
12/31/2013  9/30/2014    124      4            1            Quarterly
3/31/2014   12/31/2013   124.5    5            1            Quarterly
6/30/2014   3/31/2014    125      6            1            Quarterly
9/30/2014   6/30/2014    125.5    7            1            Quarterly
12/31/2014  9/30/2014    126      10           9            Quarterly
3/31/2015   12/31/2014   126.5    11           9            Quarterly
6/30/2015   3/31/2015    127      12           9            Quarterly

例如,季度条目的协调ID 9对应于条目ID 9,即年度条目。

我的代码只是从当前条目中减去先前的条目,但我无法弄清楚如何从条目ID和协调ID相同的年度条目中减去季度条目。

这是我正在使用的代码,这导致了正确的计算,但是增加了许多行的结果数量。我也试过这个作为内部联接。我只想要原始的10行,再加上一个新的差异列:

 SELECT DISTINCT T1.[EntryID] 
    , [T1].[RECONCILEID] 
    , [T1].[CurrentDate] 
    , [T1].[Annual_Quarterly] 
    , [T1].[Value] 
    , [T1].[Value]-T2.[Value] AS Difference 
    FROM Table T1 
    LEFT JOIN Table T2 ON T2.EntryID = T1.RECONCILEID;

2 个答案:

答案 0 :(得分:0)

就你如何减去这些价值而言,你的问题有点模糊,但这应该会给你一些想法。

Select      T1.*, T1.Value - Coalesce(T2.Value, 0) As Difference
From        Table   T1
Left Join   Table   T2  On  T2.[Entry Id] = T1.[Reconcile Id]

答案 1 :(得分:0)

您的代码应该没问题,这是我得到的结果:

EntryId Annual_Quarterly    CurrentDate ReconcileId Value   recVal  diff
2       Annual              9/30/2012   3           112     
1       Annual              9/30/2013   2           123     112     11
9       Annual              9/30/2014   1           123.5   123     0.5
4       Quarterly           12/31/2013  1           124     123     1
5       Quarterly           3/31/2014   1           124.5   123     1.5
6       Quarterly           6/30/2014   1           125     123     2
7       Quarterly           9/30/2014   1           125.5   123     2.5
10      Quarterly           12/31/2014  9           126     123.5   2.5
11      Quarterly           3/31/2015   9           126.5   123.5   3
12      Quarterly           6/30/2015   9           127     123.5   3.5

使用您的数据和此SQL:

SELECT  
    tr.EntryId, 
    tr.Annual_Quarterly, 
    tr.CurrentDate,
    tr.ReconcileId, 
    tr.Value, 
    te.Value AS recVal, 
    tr.[VALUE]-te.[VALUE] AS diff
FROM 
    t AS tr LEFT JOIN 
    t AS te     ON 
    tr.ReconcileId = te.EntryId
ORDER BY 
    tr.Annual_Quarterly, 
    tr.CurrentDate;