0

再会!

List<TotalServiseCalls> TSC = (
    from scall in contextOMNIDB.UserFields698.AsEnumerable()
    where scall.f2_creationd >= referenceDate
    group scall by scall.f2_creationd.Month into scalls
    select new TotalServiseCalls
    {
        mountN = (from sc in contextOMNIDB.UserFields698.AsEnumerable()
            where sc.f2_creationd.Month == scalls.Key
            select sc.f2_creationd).FirstOrDefault(),
        date = (from sc in contextOMNIDB.UserFields698.AsEnumerable()
            where sc.f2_creationd.Month == scalls.Key
            select sc.f2_creationd.ToString("MMMM yyyy")).FirstOrDefault(),
        totalCount = scalls.Count()
     }).OrderBy(p => p.mountN).ToList();

MSSQL 服务器有很多应用程序,它的负载非常高。此查询执行四十秒。这是因为服务器上的拥塞还是查询的复杂性?

这些表有大约一万条记录,大小为 1 兆字节。

4

2 回答 2

1

从你提供的信息很难说是查询还是拥塞。您可以改进的两件事:

  1. 放入contextOMNIDB.UserFields698.AsEnumerable()变量
  2. 也将其放入可重用的形式:from sc in contextOMNIDB.UserFields698.AsEnumerable() where sc.f2_creationd.Month == scalls.Key select sc.f2_creationd

这是一个可能的重构版本:

var userFields = contextOMNIDB.UserFields698.AsEnumerable();
List<TotalServiseCalls> TSC = (
    from scall in userFields
    where scall.f2_creationd >= referenceDate
    group scall by scall.f2_creationd.Month into scalls
    select new TotalServiseCalls
    {
      mountN = Helper(userFields, scalls.Key).FirstOrDefault(),
      date = Helper(userFields, scalls.Key).Select(o => o.ToString("MMMM yyyy")).FirstOrDefault(),
      totalCount = scalls.Count()
    }).OrderBy(p => p.mountN).ToList();

使用辅助方法(我不得不使用object,因为我对您的业务对象做得不够):

private IEnumerable<object> Helper(IEnumerable<object> userFields, object key)
{
  return from sc in userFields
         where sc.f2_creationd.Month == key
         select sc.f2_creationd;
}
于 2013-09-22T11:53:23.180 回答
1

您不必查询contextOMNIDB.UserFields698.AsEnumerable()3次,您可以从组中获取第一条记录,您可以获得月份作为分组的Key:

List<TotalServiseCalls> TSC = (
    from scall in contextOMNIDB.UserFields698.AsEnumerable()
    where scall.f2_creationd >= referenceDate
    group scall by scall.f2_creationd.Month into scalls
    select new {
        mountN = scalls.Key,
        date = scalls.Select(x => x.ToString("MMMM yyyy").First(),
        // You can use scalls.OrderBy(x => x (or any other order)).First()
        // if you want to get specific date
        totalCount = scalls.Count()
    }
).OrderBy(p => p.mountN).ToList();

这是一个简单的例子:

var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("test1", "2"));
list.Add(new Tuple<string, string>("test1", "1"));
list.Add(new Tuple<string, string>("test2", "1"));
list.Add(new Tuple<string, string>("test2", "6"));
list.GroupBy(x => x.Item1)
    .Select(x => 
            new {
                a = x.Key,
                b = x.OrderByDescending(y => y).First(),
                c = x.Count()
            }
    ).ToList()
于 2013-09-22T11:53:31.103 回答