sql三条记录求差(一个减去另外两个)

测试表【test1】

 

 

错误的写法:

select s1.kc1-s2.kc2 from (
(
select kc as kc1 ,[MONTH]
from test1
where [type]=1
) s1
left join
(
select kc as kc2,[MONTH] from test1
where [type] in (2,3)
) s2 on s1.[month] = s2.[month]
)

正确的写法:

select s1.kc1-s2.kc2 from (
(
select kc as kc1 ,[MONTH]
from test1
where [type]=1
) s1
left join
(
select sum(kc) as kc2,[MONTH] from test1
--select kc as kc2,[MONTH] from test1
where [type] in (2,3)
group by [MONTH]
) s2 on s1.[month] = s2.[month]
)

posted @ 2022-06-14 19:07  冬月二四  阅读(234)  评论(0编辑  收藏  举报