0

I'm trying to get the count of a column in a table using a SQL query to a C# list

my sample code is below

"Select count(1) as Values, SM.Name from SM INNER JOIN Bill on SM.ID = Bill.AL INNER JOIN Details on Bill.ID = Details.ID"

I need to to add the count to a list<> Can some one tell me how to do that?

Since this count value doesn't have a column name I have given it the name "Values" I have tried to get the value as following code

 public IHttpActionResult Post(Brands brand)
        {
            DataTable dt = new DataTable();
            List<Brands> list = new List<Brands>();
            try
            {
                SqlConnection con =
                    new SqlConnection(
                        "MyConnectionString");
                con.Open();
                    var query = "Select count(1) as Values, SM.Name from SM INNER JOIN Bill on SM.ID = Bill.AL INNER JOIN Details on Bill.ID = Details.ID";

                SqlCommand com = new SqlCommand(query, con);   

                com.ExecuteNonQuery();
                con.Close();
                SqlDataAdapter adptr = new SqlDataAdapter(com);
                adptr.Fill(dt);
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    Brands GetAll = new Brands();
                   GetAll.Count = Convert.ToInt32(dt.Rows[i]["Values"]);
                    GetAll.Name = dt.Rows[i]["Name"].ToString();

                    list.Add(GetAll);
                }
            }
            catch (Exception e)
            {

            }
            return Ok(list);
        }
    }
}
Tharindu
  • 13
  • 7

2 Answers2

0

Thanks Every one for contributing to help me out. Special Thanks to @Kason. What I did was add Group by to SQL Query. That Solved the Issue. Hope this would be helpful to others.

Tharindu
  • 13
  • 7
-1

I appriciate the efforsts and suggestion for all helpers,but some comments are showing they have less knowledge of sql.

1)

you used column(1), please never ever use this syntax for query,this is bad practice to get data,always use name of column.

2)

Someone posted that count(1) is equals to count() than it's myth,because count() will provide count of all the rows where count(1) will provide only count of that which are not null. (Not believing try this in your system.)

keep this points in mind also suggest to others,hope you like this post.

Sagar R
  • 595
  • 3
  • 14
  • count(*) and count(1) also include null. – Kason Apr 29 '16 at 06:28
  • it may be your primary key field that why. – Sagar R Apr 29 '16 at 06:35
  • http://stackoverflow.com/questions/5179969/what-is-better-in-mysql-count-or-count1 if your sql knowledge is not enough, please do more research. – Kason Apr 29 '16 at 06:42
  • @Kason the issue was not because of count(1) or count(*). It was just because of not having group by key word at the end of the sql query and Thanks for the support. I will look into this as well. Cheers – Tharindu Apr 29 '16 at 07:57