如何使用完全外连接测试NULL?

时间:2014-06-04 17:54:40

标签: sql sql-server-2008

我有一个名为TabOne的表,其中包含这些列 Id日期价格说明

+----+-------------------------------+--------------+---------+
| id | Date                          |   Price      | descri  |
+----+-------------------------------+--------------+---------+
| 1  |2014-05-05                     |    10         |     bab|
| 2  |2014-05-05                     |    50         |     bab|
| 3  |2014-05-05                     |    50         |     bab|
| 1  |2014-05-04                     |    60         |     bab|
| 4  |2014-05-04                     |    60         |     bab|
| 5  |2014-05-04                     |    70         |     bab|
| 6  |2014-05-04                     |    70         |     bab|
|    |                               |               |        |
+----+-------------------------------+--------------+---------+

我必须比较两个日期之间的价格,如果日期中的条目在另一个日期没有等价,我也必须显示它

+----+-------------------------------+--------------+---------+
| id |                               |   Diff       | descri  |
+----+-------------------------------+--------------+---------+
| 1  | 2014-05-05 2014-05-04         |    60-10      |     bab|
| 2  | 2014-05-05                    |    Null       |     bab|
| 3  | 2014-05-05                    |    Null       |     bab|
| 4  | 2014-05-04                    |    Null       |     bab|
| 5  | 2014-05-04                    |    Null       |     bab|
| 6  | 2014-05-04                    |    Null       |     bab|
|    |                               |               |        |
+----+-------------------------------+--------------+---------+

2014-05-05
2014-05-04

所以我写道:

Select tabOne.Price - TO.Price from TabOne
Full outer JOIN TabOne as TO on TO.id = TabOne.id and TO.Date='2014-05-04'
where TabOne.Date='2014-05-05'

但它一直让我觉得2014-05-05

上存在Id
+----+-------------------------------+--------------+---------+
| id |                               |   Diff       | descri  |
+----+-------------------------------+--------------+---------+
| 1  |                               |    60-10     |     bab |
+----+-------------------------------+--------------+---------+

2 个答案:

答案 0 :(得分:4)

问题不是很清楚。我想你想要这样的东西。测试并根据您的需求进行调整:

; WITH a AS
    ( SELECT t.Id, t.Price
      FROM TabOne AS t
      WHERE t.Date = '20140505'
    ) ,
  b AS
    ( SELECT t.Id, t.Price
      FROM TabOne AS t
      WHERE t.Date = '20140504'
    ) 
SELECT 
    Id = COALESCE(a.Id, b.Id),
    PriceA = a.Price,
    PriceB = b.Price,
    Diff = a.Price - b.Price 
FROM 
    a FULL JOIN b
        ON  a.id = b.id ;

SQL-Fiddle

进行测试

由于where TabOne.Date='2014-05-05',原始查询无效。这基本上将FULL联接转换为LEFT联接(因为左表的列在WHERE条件中使用)。

答案 1 :(得分:-3)

试试这个

  Select tabOne.Price - TO.Price from TabOne tabOne
  Full outer JOIN TabOne as TO on TO.id = TabOne.id 
  where TabOne.Date='2014-05-05'and TO.Date = '2014-05-04'