两个列值相减有一列中有的行为空的情况,如果有一列数据为空,那么另一列数据和这一列数据的操作也为空。
测试表对应的ddl语句:
CREATE TABLE [dbo].[RowSubTest] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[product] [char] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[type] [char] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[price] [float] NULL
) ON [PRIMARY]
GO
需要计算出产品的盈利状况,即对应同一中产品type='s'的行对应的price-type='b''的行对应的price
情况1:
对应数据
1 apple b 1
2 apple s 2
3 orange b 11
4 orange s 21
当执行select (b.price-s.price) as profit,b.product from
(select * from rowsubtest where type = 'b') as b,
(select * from rowsubtest where type = 's') as s
where b.product = s.product
对应的执行结果
profit product
-1.0 apple
-10.0 orange
情况2:
对应的数据
1 apple b 1
3 orange b 11
4 orange s 21
执行上述sql语句后的结果:
profit product
-10.0 orange
情况3:
执行语句update RowSubTest set price = null where id=2后,对应数据:
1 apple b 1
2 apple s null
3 orange b 11
4 orange s 21
执行上述语句对应的结果:
NULL apple
-10.0 orange
情况4:
对应的数据
1 apple b 1
3 orange b 11
4 orange s 21
这是apple还没有销售出去,所以没有销售记录,但是上面的语句中没有了apple的盈利数据行,如果希望得到apple的盈利数据行,但对应的盈利一列对应的是null应该如何处理?
博客围绕SQL中两列值相减且存在空值的情况展开。给出测试表的DDL语句,通过不同数据情况,展示计算产品盈利(同一产品type='s'的price减去type='b'的price)的SQL执行结果,还提出如何获取未销售产品盈利数据行且盈利列为null的问题。
1万+

被折叠的 条评论
为什么被折叠?



