具有不同where条件句子的聚合函数

时间:2016-04-19 11:07:59

标签: sql sql-server sql-server-2008 sql-server-2012

我有SQL查询给出了

中的6列表
using System;
...


namespace AccountSystem.Controllers
{
    public class ActivityLogController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: ActivityLog
        public ActionResult Index()
        {
            IEnumerable<ActivityLogViewData> model = null;
            List<ActivityLogViewData> verify = new List<ActivityLogViewData>();
            SqlConnection connection = new SqlConnection("xxx");
            connection.Open();
            SqlCommand command = new SqlCommand("", connection);
            command.CommandText = "select dbo.AspNetUsers.Email,dbo.AspNetUsers.UserName,dbo.ActivityLogModels.ID,dbo.ActivityLogModels.Acess,dbo.AspNetUsers.Id from dbo.ActivityLogModels inner join dbo.AspNetUsers on dbo.ActivityLogModels.userID=dbo.AspNetUsers.Id";
            SqlDataReader dr = command.ExecuteReader();
            while (dr.Read())
            {

                    verify.Add(new ActivityLogViewData { Email = dr[0].ToString(), UserName = dr[1].ToString(), accessID = Convert.ToInt32(dr[2].ToString()), Acess = Convert.ToDateTime(dr[3].ToString()), userID = dr[4].ToString()});

            }
            connection.Close();
            //return View(db.ActivityLog.ToList());
            return View(verify);
        }

这些列是聚合函数的结果。但每个人都有不同的where条件句子,以便从表格中选择。

我的查询是这样的:

mytable: 
TotalNumberOfRecords
TotalDurationOfCalls
AvgdurationPer
TotalCallednumbers
TotalCallednumbers
Ratiocalledtoallcalls

现在,我的问题是,如何在一个查询中执行此查询以获取一个表?

1 个答案:

答案 0 :(得分:4)

您需要条件聚合。您可以通过将case表达式作为聚合函数的参数来执行此操作:

select ID, count(*) as TotalNumberOfRecords,
       sum(case when condition1 then cast(duration as int) else 0 end) as TotalDurationOfCalls ,
       avg(case when condition2 then cast(duration as int) else 0 end) as AvgdurationPer,
       count(distinct case when condition3 then IDS end) as TotalCallednumbers,
       count(distinct case when condition4 then CGI end) as TotalOfLocations,
       cast(distinct count(case when condition5 then IDS end) as float)/cast(count(*) as float) as Ratiocalledtoallcalls
from Mytable
group by ID