Rifshan
Rifshan

Reputation: 153

Sort by Maximum Count in SQL C#

I'm using 2 tables, Employer and Jobs tables.

Employer Table has values like:

E_ID    e_name
1       john
2       rick
3       mike

Jobs table has values like:

J_ID        FK_eID     J_Title
1           1          Job1
2           1          Job2
3           3          Job3
4           2          Job4
5           3          Job5
6           1          Job6

So the jobs are created by employers,

What I want is to filter which employer has posted most number of jobs and display e_name in Maximum to Minimum order in a List...

The code I'm using (no clue about SQL part):

        SqlConnection myConn2;
        SqlCommand myCommand2;
        SqlDataReader myReader2;
        String SQL2,SQL, divjobs;
        myConn2 = new SqlConnection(WebConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
        divjobs = "<ul>";
        myConn2.Open();
        SQL2 = "";
        myCommand2 = new SqlCommand(SQL2, myConn2);
        myReader2 = myCommand2.ExecuteReader();

        while (myReader2.Read())
        {
            divjobs = divjobs + "<li>" + "<a href='employers/viewemployer.aspx?EID=" + myReader2["e_id"] + "'>" + myReader2["e_name"] + "</a>" + "</li>";
        }
        divjobs = divjobs + "</ul>";
        topemp.InnerHtml = divjobs;
        myConn2.Close();

Upvotes: 3

Views: 88

Answers (1)

juergen d
juergen d

Reputation: 204844

Group by the employer and order by the job count of each one

select e.e_name, count(j.j_id) as jobs
from employer e
left join jobs j on j.fk_eid = e.e_id
group by e_id, e.e_name
order by count(j.j_id) desc

Upvotes: 4

Related Questions