Hi,I have a table of transactions and I'm trying to get a nice list of total sales/purchases made per day by a single account. If the account doesn't have any transactions for that day then the query should return a row indicating 0 transactions.Here is a simplified tablecreate table garethTest ([date] datetime, accountid int, transactionType nvarchar(4), price int)
and some random datainsert garethTest select '2007-10-19', 1, 'sale', 45 union all select '2007-10-19', 1, 'buy', 221 union all select '2007-10-19', 2, 'buy', 334 union all select '2007-10-19', 2, 'sale', 12 union all select '2007-10-21', 2, 'sale', 15 union all select '2007-10-21', 2, 'sale', 18 union all select '2007-10-21', 2, 'sale', 9 union all select '2007-10-21', 2, 'sale', 33 union all select '2007-10-22', 2, 'sale', 21 union all select '2007-10-22', 2, 'buy', 142 union all select '2007-10-23', 1, 'sale', 17 union all select '2007-10-25', 2, 'sale', 1
Now the query I have I think should nearly be there!! The only difference is I have a date lookup/tally table instead of doing the dateadd part.Now it works fine until I add a where clause in at the bottom to decide which account I want to view.I would like to see results that look likeDate Sales Buys2007-10-19 45 2212007-10-20 0 02007-10-21 0 02007-10-22 0 02007-10-23 17 02007-10-24 0 02007-10-25 0 0
Instead my query just returns the rows with dataDate Sales Buys2007-10-19 45 2212007-10-23 17 0
Here it isselect [Date], sum(Sale) as [Sales], sum(Buy) as [Buys]from (select dateadd(d, numbers.number, '2007-10-18') as [Date], case when transactionType = 'sale' then price else 0 end Sale, case when transactionType = 'buy' then price else 0 end Buy, isnull(accountid, 0) as accountid from (select 1 as number union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7) as numbers left join garethtest gt on dateadd(d, number, '2007-10-18') = gt.date ) as dwhere accountid = 1 -- I remove this line and it works but shows me everyonegroup by date
Any ideas? I was thinking maybe I need to use that query as a derived table from another select and group by the accountid and date??ThanksGareth