在SQL查询中将两个记录的空值视为不相等

时间:2014-07-31 14:27:24

标签: sql sql-server-2012

我正在处理SQL查询,该查询执行一些计算并返回属于两个不同的单个表行的两个列的差异,而其他列中的某些值不相等

例如,我在表格中有以下数据

id      Market  Grade       Term     Bid     Offer  CP
1       Heavy   ABC         Jun14   -19.5     -17   BA
2       Heavy   ABC         Jul14   -20      -17.5  BB
3       Sour    XYZ         Jun14   -30       -17   NULL
4       Sour    XYZ         Jul14   -32       -27   NULL
5       Sweet   XY          Jun14   -30       -17   PV
6       Sweet   XY          Jul14   -32       -27   PV

现在,我想要以下结果

(AS MarketGrade相同且Id=1,2的CP不相同所以,它应该计算

Bid of Id=1 - Offer of Id=2
Offer of Id=1- Bid of Id=2

MarketGrade对于Id=3,4是相同的,并且它们的CP在逻辑上都是NULL,但我仍然想像在前一种情况中那样计算

Bid of Id=3 - Offer of Id=4
Offer of Id=3- Bid of Id=4

而且,最后我不想用Ids 5和6计算任何记录,因为他们的CP是相同的

以下内容应该是结果

Market     Term          Bid                   Offer
Heavy/ABC  Jun14/Jul14   (-19.5-(-17.5))=-2    (-17-(-20))=3
Sour/XYZ  Jun14/Jul14    (-30-(-27))=-3        (-17-(-32))=15

我能够找出大部分内容,除非CP是两个记录的情况是NULL,因为它将它们视为相等而且显而易见

;with numbered as
(
    select id, market, grade, term, bid, offer, row_number() OVER (Partition BY Market, Grade ORDER BY Bid desc) i
    from things
)
--select * from numbered
select r1.market + '/' + r1.grade as Market, r1.term + '/' + r2.term as Term, r1.Bid - r2.Offer [Bid], r1.Offer - r2.Bid [Offer] 
from numbered r1 
join numbered r2 on r1.market = r2.market and r1.grade = r2.grade and r1.i < r2.i and r1.CP!=r2.CP

如何将两个NULL视为不相等。

3 个答案:

答案 0 :(得分:3)

你能不能改变:

and r1.CP!=r2.CP

为:

and ISNULL(r1.CP, 'X') != ISNULL(r2.CP, 'Y')

编辑。如果你想要真正安全并且生活有点危险,你甚至可以这样做:

and ISNULL(r1.CP, CONVERT(VARCHAR(36), NEWID())) != ISNULL(r2.CP, CONVERT(VARCHAR(36), NEWID()))

答案 1 :(得分:1)

我并没有把它作为一个答案,因为它是一个糟糕的解决方案,但您可以使用ISNULL函数替换NULLS的替代值。

;with numbered as
(
 select id, market, grade, term, bid, offer, row_number() 
 OVER (Partition BY Market,     Grade ORDER BY Bid desc) i
from things
)
--select * from numbered
select r1.market + '/' + r1.grade as Market, r1.term + '/' + r2.term as Term, 
       r1.Bid -      r2.Offer [Bid], r1.Offer - r2.Bid [Offer] 
from numbered r1 
join numbered r2 on r1.market = r2.market and r1.grade = r2.grade and r1.i < r2.i 
and  ISNULL(r1.CP, 1) != ISNULL(r2.CP,2)

答案 2 :(得分:0)

即使您愿意,也无法将两个NULL视为相等。 NULL是缺少值;你无法与任何东西进行比较,没有任何意义。