计算Ms Access中行之间的绝对差异

时间:2011-03-05 01:29:36

标签: sql ms-access

我整个上午都花在这上面,但是无法做到这一点......我真的很感谢能比我更了解的人的帮助。

我有一个包含一些数据的表,如下所示:

MonthYear WeekBeg.  Week  Value  
Dec-10  27/12/2010  1   66.66  
Jan-11  3/01/2011   2   50  
Jan-11  10/01/2011  3   17.5  
Jan-11  17/01/2011  4   20  
Jan-11  24/01/2011  5   0  
Jan-11  31/01/2011  6   50  
Feb-11  7/02/2011   7   0  
Feb-11  14/02/2011  8   74  
Feb-11  21/02/2011  9   100  

对不起,上面的表格看起来不太好......我需要计算每周的值之间的差异 - 所以在这种情况下的结果列将是:

16.66
32.5
2.5
20个
50个
50个
74个
26

我在网上看了很多代码 - (例如from this site)但似乎无法使其正常工作。我在ABS功能中添加了以确保差异是绝对值并使其工作但数字本身不正确。

我没有发布我最终得到的东西,因为它刚刚陷入更大更大的混乱,但我开始的是上面的链接。再一次,我真的很感激任何人能够提供的任何见解。

非常感谢

增加:

非常感谢快速回复。让这个工作变得轻松 - 添加了一些内容:

SELECT T1.MonthYear AS [From],T2.MonthYear AS [To],T1.Week AS Week,T1.WeekBeg AS WeekBeg,ABS(T1.Value - T2.Value)AS FROM FROM Test AS T1 LEFT JOIN测试AS T2 ON T2.Week = T1.Week + 1

唯一的结果是差异值必须在两行的第二行中,而这里它们在两者中的第一行。有没有简单的方法来修改它?

再次感谢。

增加:

如果可能的话,肯定值得使用第二个选项,因为不能总是保证周不会错过。我可能遗漏了一些东西,但当我从托马斯那里运行第二个选项时,我收到了消息:

'指定的字段[T1]。[Datavalue]可以引用SQL语句的FROM子句中列出的多个表'。

我认为这可能与表中的字段为VALUE而不是DataValue有关,但是当我更改它时,我得到'表达式中的类型不匹配'。

非常感谢。

2 个答案:

答案 0 :(得分:3)

假设“周”列是完全顺序的:

Select T1.MonthYear As T1Year
    , T1.WeekBeg As T1WeekBeg
    , T2.MonthYear As T2Year
    , T2.WeekBeg As T2WeekBeg
    , [T2].[Value]-[T1].[Value] AS Expr1
From TableWithData AS T1 
    Left Join TableWithData AS T2 
        On T1.Week = T2.Week + 1;

应该注意,这不会在QBE设计器中编译。您必须纯粹通过SQL视图(或代码)

来查看和修改它

如果由于某种原因你不能依赖周数是连续的,那么你需要使用派生表会变得更加棘手。同样,此解决方案仅适用于SQL View或代码:

Select T1.MonthYear, T1.WeekBeg
    , T2.MonthYear, T2.WeekBeg
    , [T2].[Value]-[T1].[Value] AS Diff
From (TableWithData AS T1 
    Inner Join (
            Select T1.WeekBeg As T1WeekBeg
                    , Min(T2.WeekBg) As T2WeekBeg
                From TableWithData As T1 
                    Left Join TableWithData AS T2 
                        On T2.WeekBeg > T1.WeekBeg
                Group By T1.WeekBeg
                ) As Query1
        On T1.WeekBeg = Query1.T1WeekBeg) 
    Inner Join TableWithData AS T2 
        On Query1.T2WeekBeg = T2.WeekBeg;

答案 1 :(得分:0)

基于基本链接的示例查询的版本。 (它在Week字段中使用ORDERY BY,TOP 1也使用标量值。)

SELECT  t1.Value - (SELECT TOP 1 t2.Value FROM myTable AS t2 
                               WHERE t2.Week < t1.Week
                               ORDER BY t2.Week DESC) AS t2Val
FROM myTable t1
WHERE (SELECT TOP 1 t3.Value FROM myTable AS t3
       WHERE t1.Week < t3.Week) Is Not Null
ORDER BY t1.Week;

应该接近工作但是混叠非常容易出错。我建议,如果按顺序排列周数,你可以选择Thomas的回答。