1

这是此处较早问题的扩展

我有两张桌子,昨天和今天,每张桌子都有两列

StockNumber, StockLevel

我怎么知道

  1. 只有 StockNumber 的 StockLevel 有差异
  2. 返回受影响的 StockNumber 和 StockLevel 值

例如:

今天的表:

StockNumber, StockLevel
ABC, 10
CBA,5
123,5

昨天的表:

StockNumber, StockLevel
ABC, 9
CBA,5
123,10

要返回以下 wi

StockNumber, StockLevel
ABC, 10
123, 5

现在注意到 StockNumber "ABC" 返回今天的值 10, StockNumber "123" 也返回今天的值 5, StockNumber "CBA" 没有变化,也没有返回。

非常感谢,

马特

4

5 回答 5

3

这将适用于两天都存在的股票;

SELECT t.StockNumber, t.StockLevel
FROM today t
JOIN yesterday y
  ON t.StockNumber=y.StockNumber
 AND t.StockLevel <> y.StockLevel

如果您(如您之前的问题)还希望包括今天的新股票;

SELECT t.StockNumber, t.StockLevel
FROM today t
LEFT JOIN yesterday y
  ON t.StockNumber = y.StockNumber
WHERE y.StockNumber IS NULL 
   OR t.StockLevel <> y.StockLevel

一个用于测试两者的 SQLfiddle

于 2013-02-24T16:23:17.727 回答
0

您可以加入 StockNumber 上的表并选择这些行WHERE NOT A.StockLevel = B.StockLevel

于 2013-02-24T16:18:36.150 回答
0

这有点棘手,因为您可能在两个表中有不同的项目。为此,我建议使用 union all 和 group by:

select stockNumer,
       max(case when which = 'yesterday' then stocklevel end) as yesterdaylevel,
       max(case when which = 'today' then stocklevel end) as todaylevel
from ((select StockNumber, StockLevel, 'yesterday' as which
       from yesterday
      ) union all
      (select StockNumber, StockLevel, 'today' as which
       from today
      )
     ) t
group by stockNumber
having min(StockLevel) <> max(stockLevel) and count(*) = 2
于 2013-02-24T16:22:06.460 回答
0
select T.StockNumber, T.StockLevel 
from Today as T 
left join Yesterday as Y 
on T.StockNumber = Y.StockNumber 
WHERE T.StockLevel <> Y.StockLevel

在这里玩结果:http ://sqlfiddle.com/#!2/367b0/3/0

于 2013-02-24T16:27:43.347 回答
0

以下查询将返回StockLevel与昨天不同 (by ) 或昨天不存在的股票(这是什么LEFTIS NULL适用于):

SELECT Today.*
FROM Today LEFT JOIN Yesterday
    ON Today.StockNumber = Yesterday.StockNumber
WHERE
    Today.StockLevel <> Yesterday.StockLevel
    OR Yesterday.StockLevel IS NULL
于 2013-02-24T16:41:07.187 回答