1

假设我有表Tab ( id,, DeptName, Total, ...)

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

然后我可以发出 SQL 进行这样的分组:

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

通常,根据 的值,结果将有 4 行DeptName

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

我想要的是结果总是有 4 行。如果没有数据Dept2,我希望得到如下结果:

Dept1    1234.09
Dept2    0
Dept3    34.34
Dept4    614.48

如何实现这个要求?

4

3 回答 3

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
于 2012-07-23T20:18:12.343 回答
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
于 2012-07-23T14:38:29.707 回答
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)
于 2012-07-23T14:51:49.767 回答