tags:

views:

263

answers:

2

By "fixed vector" I mean a static list of values, like 1 through 24.

The current query looks like this (simplified)

SELECT Period, Profit FROM Projections

But the data is "sparse" — so there's not a row for every period.

What query will give me a row for peiods 1-24 every time, with zeros (or NULLs) where there's no data?

I would like to do this with just the query to avoid a mess of client code.

Thanks!

+1  A: 

Why not create a 'Periods' lookup table, with values 1 - 24 (and any other columns that might be relevant, like a description of the period, or its name) then do a left outer join between the Periods lookup table and your projections table.

Harper Shelby
Mainly because it's not really "data" (and it's not my database). I can accomplish the report in a read-only manner, but as I said it will just take more client code.
harpo
The possible periods most certainly do constitute "data". This is a pretty common approach.
Tom H.
+1  A: 

You could make a udf called udfRange(start int,count int) or something like that, and left-join to the output of the function.

Or for something really quick and dirty, you could join to a subselect that looked like

SELECT DATA.Period, P.Profit
FROM (
SELECT 1 AS Period
UNION SELECT 2
...
UNION SELECT 24) AS DATA 
LEFT JOIN Projections P ON DATA.Period = P.Period
Barry Fandango
I had something like this in mind among my "last resorts", and it looks like it's going to work. It's even more onerous in Access, though, because you can't just SELECT 1, you have to include a FROM clause. Still, I prefer it to the alternatives. Thanks!
harpo
+1 for the fabricated table ('DATA') approach (harpo is correct: you need a FROM clause, preferable using a table you *know* always has one row, otherwise use the DISTINCT keyword; but if you used an empty table you would end up with a zero row table -- not good!)
onedaywhen