Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HI Here's my sql query
SQL
select Month,count(id) transactions from `tbl_test` where id=" + id + " and Month is not NULL and Year = " + Convert.ToInt32(currentYear) + " group by Month;


Month is varchar and id is int I am using mysql.

Populating it into DataTable
C#
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);


The result I am getting is like
SQL
Month transactions 
May     122
December 178

And the result I want is like

SQL
Month transactions 
January    0
February   0
March      0
April      0
May        122
June       0
July       0
August     0
September  0
October    0
November   0
December   178


Kindly Help

What I have tried:

I have created another table with all the months and trying to join the 2. But of no use (I guess because of the where clause in the sql statement). Kindly help

Something like this:
SQL
select Month, ifnull(count(id), 0) transactions 
    from `tbl_test` 
    inner join my_month_table  as m on m.month_key = `tbl_test`.month_key 
    where id=" + id + " and Month is not NULL and Year = " + Convert.ToInt32(currentYear) + " 
    group by Month;


Quote:
PS: I would prefer not to change the query (1st one without join) and play around the front end coding (C#) to insert into the DataTable.
Posted
Updated 3-Dec-16 23:14pm
Comments
Tomas Takac 4-Dec-16 5:04am    
I'm confused. So you solved it with this additional join but you don't like the solution? So what did you try to solve it in your application layer?

1 solution

If you have the table with all the months, select from that as the primary table, and do a left join. like so:
SQL
select month, ifnull(count(t.id),0) transactions
from my_month_table m
left join 'tbl_test' t on m.month_key=t.month_key
where id=" + id + " and Month is not NULL and Year = " + Convert.ToInt32(currentYear) + "
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900