自联接在上个月产生不一致的价值

时间:2016-07-14 14:50:05

标签: sql tsql join

为了在同一行显示上个月的一些记录,我不得不像这样加入我的表:

SELECT 
      a.[periodOrderNum]
      ,SUM(a.AktivNy) as ActiveNew
      ,SUM(b.[AktivNy]) as ActiveNewPrevMonth
  FROM myTable a
  JOIN myTable b 
    ON a.customerSNKey = b.customerSNKey 
   AND a.periodOrderNum = b.periodOrderNum + 1
  GROUP BY a.[periodOrderNum]

在上面的代码中,periodOrderNum是分配给期间的订单号。例如,如果当前期间为5,那么前一期间的订单号为4.

customerSNKey是客户的序列号密钥,我将其用作JOIN条件之一。我用来获取上一期间值的另一个条件(a.periodOrderNum = b.periodOrderNum + 1)。但结果并不一致。如下图所示,对于订单号280,ActiveNewPrevMonth的值为20203,而不是订单号279的ActiveNew值。

enter image description here

我在加入时做错了什么?

1 个答案:

答案 0 :(得分:1)

如果没有一些样本数据,我无法分辨出错的地方。但不管怎样,无论如何,你的查询都会返回错误的值。假设您在同一periodOrderNum下有多行,则几乎可以保证您的ActiveNew值被夸大。如何尝试将它们分成这样的子查询:

 SELECT a.[periodOrderNum]
 ,a.ActiveNew
 ,b.ActiveNewPrevMonth
 FROM
 (
 SELECT 
 customerSNKey, [periodOrderNum]
 ,SUM(AktivNy) as ActiveNew
 FROM myTable
 GROUP BY customerSNKey, [periodOrderNum]
 ) AS a
 INNER JOIN 
 (
 SELECT 
 customerSNKey, [periodOrderNum] + 1 as [periodOrderNum]
 ,SUM(AktivNy) as ActiveNewPrevMonth
 FROM myTable
 GROUP BY customerSNKey, [periodOrderNum] + 1
 ) AS b
 ON a.customerSNKey = b.customerSNKey
 AND a.[periodOrderNum] = b.[periodOrderNum]