SQL 2005
同表同字段,
以字段分组计算差
谢谢帮忙,
------解决方案--------------------
/* A字段的值是否确定只有2个:J和C,如果有更多其他值,就需要做其他处理了,目前先以当前情况写出语句 */
with Test ([A], [B], [C]) as
(
select 'J', 500, 1 union all
select 'J', 300, 1 union all
select 'J', 600, 2 union all
select 'J', 700, 2 union all
select 'C', 100, 1 union all
select 'C', 200, 1 union all
select 'C', 300, 2 union all
select 'C', 400, 2
)
select
[A] = max(case when [A]='J' then [A] end) + min(case when [A]='C' then [A] end)
, [B] = sum(case when [A]='J' then [B] end) - sum(case when [A]='C' then [B] end)
, [C]
from Test
group by [C]
------解决方案--------------------
select
'JC',
SUM(CASE WHEN C字段=2 then b字段 when c字段=1 then -b字段 else 0 end) as B字段,
C字段
from
tb
group by
C字段
------解决方案--------------------
select 'JC' as A,SUM(case when A='J' then B else -B end) B,C from XX group by C