0

I have a query where it has to return count of 0, if no records found on group by. but i am getting empty results.

SELECT DATEPART(YEAR, s.CreatedAt) AS 'Year',DATEPART(MONTH, s.CreatedAt) AS 
'Month', count(*) AS 'count'
FROM table1 t1
JOIN table2 t2 on t1.id = t2.id
WHERE t1.Id IN (
SELECT id FROM table3 WHERE Id IN (
SELECT id FROM table4 WHERE Gradingresult LIKE '%abcd%'
GROUP BY id
)) AND t1.column1 LIKE 'hello' AND t1.column2='world' AND t2.column1 != 
'somestring' 
AND t1.CreatedAt BETWEEN  DATEADD(YEAR, -1, GETDATE()) AND GETDATE() 
GROUP BY DATEPART(YEAR, t1.CreatedAt), DATEPART(MONTH, t1.CreatedAt)

i want it to be displayed like below,

    year month      count
    2019    2         0
    2019    4         0
    2018    7         0

but i am getting result as below

    year   month    count

nothing here, no rows.

i have tried different ways like case statement, isnull(), left join and others but not able to get desired result

editing i have considered year as well updated actual query i have, if i don't included t2.column1 condition i am getting below results

    year  month   count
    2019  5        10
    2019  4        25
    2019  2         9
    2018  10       19        

if i include above specified condition i should get desired result

1 Answers1

0

If there are no rows in the table, there are no rows in the result set. You can use a left join to get the rows you want:

select v.mon, count(t.createdat)
from (values (2), (4), (7)) v(mon) left join
     tableT t
     on month(t.createdat) = v.mon
group by v.mon
order by v.mon;

You need to be very careful with this formulation, because you have not included the year. When working with months, you should usually be considering the year as well.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786