Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql query to populate 0's for missing data

To populate a stacked and grouped highchart I need to add some 0 values into my data. I've tried with a numbers table but could not figure out how to add 0's for every empoloyee missing per date. So I have:

TABLE (Datum, Employee, Number, Stack)

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

and I need:

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

do I need to use a cursor or is there a better trick?

like image 528
Yannick Smits Avatar asked Feb 27 '26 14:02

Yannick Smits


1 Answers

    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
like image 67
RichardTheKiwi Avatar answered Mar 02 '26 09:03

RichardTheKiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!