2012-07-23 59 views
1

假設我有表標籤id,, DeptName, Total, ...如何在sql server中爲組創建一個和集合中的行?

有4個可能的值DeptnameDept1, Dept2, Dept3, Dept4

然後我就可以發出SQL對於這樣的分組:

Select DeptName, Totaol = Sum(total) 
from Tab 
group by DeptName 

通常情況下,其結果是將基於對DeptName價值4行:

DeptName Total 
Dept1 1234.09 
Dept2 234.80 
Dept3 34.34 
Dept4 614.48 

如果沒有數據Dept2,結果只會有3行:

Dept1 1234.09 
Dept3 34.34 
Dept4 614.48 

什麼我wa nt結果總是有4行。如果沒有爲Dept2沒有數據,我要像結果:

Dept1 1234.09 
Dept2 0 
Dept3 34.34 
Dept4 614.48 

如何落實這一要求?

回答

1

這似乎是正確SQL Fiddle

SELECT t2.DeptName, Total = COALESCE(Sum(total),0) 
FROM Tab t1 
RIGHT OUTER JOIN (SELECT 'Dept1' as DeptName UNION ALL 
        SELECT 'Dept2' UNION ALL 
        SELECT 'Dept3' UNION ALL 
        SELECT 'Dept4') t2 ON t2.DeptName = t1.DeptName 
GROUP BY t2.DeptName 
0

試試這個:

select b.DeptName,b.Total from(
select 'Dept1' as Dept union all 
select 'Dept2' as Dept union all 
select 'Dept3' as Dept union all 
select 'Dept4' as Dept)a left outer join 
(
Select DeptName, case when b.DeptName IS null then 0 else SUM(total) end as Total 
from Tab 
group by DeptName)b 
on b.DeptName=a.Dept 
0

使用「UNION ALL」,打破每一行成多行:

select dept, sum(val) as sumval 
from ((select 'dept1' as dept, t.dept1 as val from tab t) union all 
     (select 'dept2', t.dept2 as val from tab t) union all 
     (select 'dept3', t.dept3 as val from tab t) union all 
     (select 'dept4', t.dept4 as val from tab t) 
    ) t 
group by dept 
order by 1 

如果你有很多很多的數據,下面可能有點多高效:

 (select 'dept1' as dept, sum(t.dept1) as val from tab t) union all 
     (select 'dept2', sum(t.dept2) as val from tab t) union all 
     (select 'dept3', sum(t.dept3) as val from tab t) union all 
     (select 'dept4', sum(t.dept4) as val from tab t) 
+0

謝謝。我擔心這個案件的表現太多,所有工會都是如此。 – KentZhou 2012-07-23 15:04:39

相關問題