sql server - How to show '0' amount for a month, if no data exists in the table for that month -
i have 2 tables costtable (id,resourceid, amount,date) , resourcetable (resourceid,name) shows output below.
i want show 0 amount rest of name in case of september. e.g. if rest of resources not appear in cost table should appear 0 in amount
my desired output
my current query
select rg.id id, rg.name name, isnull(sum(ac.amount), 0) amount, right(convert(varchar(10), ac.[date], 105), 7) [yearmonth] cost ac inner join resource rg on ac.resourcegroupid = rg.id ac.portalid = '100' , [date] >= dateadd(month, datediff(month, 0, dateadd(m, -11, getdate())), 0) group rg.name, rg.id, right(convert(varchar(10), ac.[date], 105), 7) order rg.name desc
you can cross join
, left join
. question hard follow because tables , descriptions differ. however, idea:
select t.minid, t.name, ym.yearmonth, coalesce(amount, 0) amount (select name, min(id) minid t group name) n cross join (select distinct yearmonth t) ym left join t on t.name = n.name , t.yearmonth = ym.yearmonth;
Comments
Post a Comment