I have a table with the following structure ID DATE DEP_C that contains a lot of data.
I want to display in a Datalist for each month of the year a count of each DEP_C grouped by DEP_C

where A1.1, A1.2, A1.3 is DEP_C
I tried with
C#
protected void GetData()
{
int currentYear = DateTime.Now.Year;
using (SqlConnection conn = new SqlConnection(connString))
{
string sqlQuery1 = "SELECT Dep_C, DATEPART(MONTH, Data) AS Month, Count(Dep_C) AS CountDef FROM RCA_Import WHERE DATEPART(YEAR, RCA_Import.Data)=@CurrentYear GROUP BY Month";
using (SqlCommand cmd = new SqlCommand(sqlQuery1, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@CurrentYear", currentYear);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds);
DataList1.DataSource = ds.Tables[0];
DataList1.DataBind();
conn.Close();
}
}
}but luck. How it should be done, please?


Marius VasileRank #785 · 2.9K reputationPosted Sep 15, 2024, 4:06 AM EDT
I managed to do it with
SELECT DATEPART(MONTH, Data) AS Month, coalesce(sum(case when Dep_C='A1.1' then 1 end),0) 1, coalesce(sum(case when Dep_C='A1.2' then 1 end),0) 2, coalesce(sum(case when Dep_C='A1.3' then 1 end),0) 3, coalesce(sum(case when Dep_C='A1.4' then 1 end),0) 4, coalesce(sum(case when Dep_C='A1.5' then 1 end),0) 5 FROM RCA_Import r GROUP BY DATEPART(MONTH, Data)