tags:

views:

42

answers:

1

I would like a query that will show a sum of columns with a default value for missing data. For example assume I have a table as follows:

type_lookup:

id name
-----------
1  self
2  manager
3  peer

And a table as follows

data:

id  type_lookup_id value
--------------------------
1   1              1
2   1              4
3   2              9
4   2              1
5   2              9
6   1              5
7   2              6
8   1              2
9   1              1

After running a query I would like a result set as follows:

type_lookup_id   value
----------------------
1                13
2                25
3                0

I would like all rows in type_lookup table to be included in the result set - even if they don't appear in the data table.

A: 

It's a bit hard to read your data layout, but something like the following should do the trick:

SELECT tl.type_lookup_id, tl.name, sum(da.type_lookup_id) how_much
 from type_lookup tl
  left outer join data da
   on da.type_lookup_id = tl.type_lookup_id
 group by tl.type_lookup_id, tl.name
 order by tl.type_lookup_id

[EDIT] ...subsequently edited by changing count() to sum().

Philip Kelley
count() or sum(), I couldn't really tell which was required here.
Philip Kelley
If you look at his resultset, it's definitely sum() -- 1+4+5+2+1=13 for lookup id # 1.
patmortech
Yes, with his edited question it's a lot clearer. I have updated my answer accordingly.
Philip Kelley
philip, thanks for the response!
markpirvine