我有table =>
Main Table : MT
================
PK SPK Name D1
==============
1, 0, XYZ, 0
1, 1, A, 99
1, 2, B, 88
1, 3, C, 77
2, 0, NULL, 0
2, 1, NULL, 99
2, 2, Z, 88
从那我想得到
Result Table : RT
================
PK SPK Name D1
==============
1, 0, XYZ, 264
1, 1, A, 99
1, 2, B, 88
1, 3, C, 77
2, 0, NULL, 187
2, 1, NULL, 99
2, 2, Z, 88
对于SPK = 0而不是0的每个PK,我想在第一行中使用SUM的总和。
此外,D1始终为0,其中SPK = 0。我想在D1字段中显示SUM,其中SPK = 0,基于PK值。
如果在第一行中获得D1的SUM而不是在SPK = 0时获得0的任何方法?
答案 0 :(得分:2)
SELECT
t.pk,
t.spk,
t.name,
CASE WHEN t.spk = 0 THEN ts.d1 ELSE t.d1 END AS d1
FROM your_table t
LEFT JOIN (
SELECT tt.pk, SUM(tt.d1) AS d1
FROM your_table tt
GROUP BY tt.pk
) ts ON t.pk = ts.pk
答案 1 :(得分:2)
使用排名功能(sqlserver 2005 +)
select PK, SPK, Name,
case when SPK = 0 then sum(D1) over (partition by pk)
else D1 end as D1
from table
order by PK, SPK
答案 2 :(得分:1)
select PK, SPK, Name,
case when SPK = 0 then ( select Sum( D1 ) from ThineTable where PK = TT.PK )
else D1 end as D1
from ThineTable as TT
order by PK, SPK