Sql查询填充0表示缺少数据

时间:2012-10-18 12:35:58

标签: sql sql-server sql-server-2005 highcharts

要填充堆叠和分组的高图,我需要在数据中添加一些0值。我已经尝试过数字表但无法弄清楚如何为每个日期缺少的每个empoloyee添加0。所以我有:

表(基准,员工,数量,堆栈)

2012-10-13 00:00:00.000 Nick    3   corporate
2012-10-14 00:00:00.000 Jack    1   private
2012-10-15 00:00:00.000 Yannick 1   corporate
2012-10-15 00:00:00.000 Jack    2   corporate

我需要:

2012-10-13 00:00:00.000 Nick    3   corporate
2012-10-14 00:00:00.000 Nick    0   corporate
2012-10-15 00:00:00.000 Nick    0   corporate
2012-10-13 00:00:00.000 Jack    0   private
2012-10-14 00:00:00.000 Jack    1   private
2012-10-15 00:00:00.000 Jack    0   private
2012-10-13 00:00:00.000 Yannick 0   corporate
2012-10-14 00:00:00.000 Yannick 0   corporate
2012-10-15 00:00:00.000 Yannick 1   corporate
2012-10-13 00:00:00.000 Jack    0   corporate
2012-10-14 00:00:00.000 Jack    0   corporate
2012-10-15 00:00:00.000 Jack    2   corporate

我需要使用光标还是有更好的技巧?

1 个答案:

答案 0 :(得分:5)

    select dates.Datum, employees.Employee, isnull(tbl.Number,0), employees.Stack
      from (select distinct Datum from tbl) dates
cross join (select distinct Employee, Stack from tbl) employees
 left join tbl on tbl.Datum=dates.Datum and tbl.Employee = employees.Employee
                  and tbl.Stack = employees.Stack