Re: ASP/SQL Query Build - Myth Breaking -
02-06-2004
, 03:53 PM
Put your Financial Calendar into a table and join that into your query.
CREATE TABLE Accounts (accountno INTEGER PRIMARY KEY, accountname
VARCHAR(30) NOT NULL UNIQUE)
CREATE TABLE FinancialCalendar (yearno INTEGER CHECK (yearno BETWEEN 2000
AND 2100), periodno INTEGER CHECK (periodno BETWEEN 1 AND 12), PRIMARY KEY
(yearno,periodno))
CREATE TABLE Budgets (accountno INTEGER REFERENCES Accounts (accountno),
yearno INTEGER, periodno INTEGER, amount NUMERIC(10,2) NOT NULL, FOREIGN KEY
(yearno,periodno) REFERENCES FinancialCalendar (yearno,periodno))
SELECT A.accountno, A.accountname, C.yearno, C.periodno,
COALESCE(B.amount,0) AS amount
FROM FinancialCalendar AS C
CROSS JOIN Accounts AS A
LEFT JOIN Budgets AS B
ON A.accountno = B.accountno
AND B.yearno = C.yearno
AND B.periodno = C.periodno
WHERE C.yearno BETWEEN 2001 AND 2004
I recommend Celko's SQL Puzzles and Answers if you want to expand your
repertoire of query techniques:
http://tinyurl.com/353dw
--
David Portas
SQL Server MVP
-- |