//获取入的数量
var query = from i in ins
//分组
group i by new { i.PId, i.Time.Date } into s
select new
{
InAmount = s.Sum(r => r.InsNumber),//数量
time = s.Key.Date
};
//获取出的数量
var query1 = from i in outs
group i by new { i.PId, i.Time.Date } into s
select new
{
OutAmount = s.Sum(r => r.OutsNumber),//数量
time = s.Key.Date
};
List<Comblin> comblins = new List<Comblin>();
var list1 = from s in query
where s.time > DateTime.Now.AddDays(-7) && s.time < DateTime.Now.AddDays(-1)
select new Comblin
{
InsNumber = s.InAmount,//数量
OutsNumber = query1.Where(m => m.time == s.time).FirstOrDefault().OutAmount,//数量
Time = s.time.ToString("yyyy-MM-dd")
};
这样写出是出来结果了,但是这种写法是以入表为主,如果入是0的话,出的数据也不会查询出来,不是我们想要的结果
换种写法
判断一下出和入的数量
List<Comblin> comblins = new List<Comblin>();
if (query.Where(s => s.InAmount != 0).Any())//当入的数量不等于0的时候以入表为主查询出数据
{
var list1 = from s in query
where s.time > DateTime.Now.AddDays(-7) && s.time < DateTime.Now.AddDays(-1)
select new Comblin
{
InsNumber = s.InAmount,
OutsNumber = query1.Where(m => m.time == s.time).FirstOrDefault().OutAmount,
Time = s.time.ToString("yyyy-MM-dd")
};
comblins.AddRange(list1);
if (query1.Where(s => s.OutAmount != 0).Any())//当出的数量不等于0的时候以出表为主查询出数据
{
var list2 = from s in query1
where s.time > DateTime.Now.AddDays(-7) && s.time < DateTime.Now.AddDays(-1)
select new Comblin
{
OutsNumber = s.OutAmount,
InsNumber = query.Where(m => m.time == s.time).FirstOrDefault().InAmount,
Time = s.time.ToString("yyyy-MM-dd")
};
comblins.AddRange(list2);
}
}
这种写法数据是出来了,这时候数据变换了一下,出现了报错 subquery uses ungrouped column "time" from outer query
说是未用time分组,但是我明明分组了啊,换种思路:先分组条件判断后进行总合
最终代码就是:
//获取入的数量
var query = from i in ins
where i.Time > DateTime.Now.AddDays(-7) && i.Time < DateTime.Now.AddDays(-1)
//分组
group i by new { i.PId, i.Time.Date } into s
select new
{
InAmount = s.Sum(r => r.InsNumber),
time = s.Key.Date
};
//获取出的数量
var query1 = from i in outs
where i.Time > DateTime.Now.AddDays(-7) && i.Time < DateTime.Now.AddDays(-1)
group i by new { i.PId, i.Time.Date } into s
select new
{
OutAmount = s.Sum(r => r.OutsNumber),
time = s.Key.Date
};
List<Comblin> comblins = new List<Comblin>();
if (query.Where(s => s.InAmount != 0).Any())
{
var list1 = from s in query
select new Comblin
{
InsNumber = s.InAmount,
OutsNumber = query1.Where(m => m.time == s.time).FirstOrDefault().OutAmount,
Time = s.time.ToString("yyyy-MM-dd")
};
comblins.AddRange(list1);
if (query1.Where(s => s.OutAmount != 0).Any())
{
var list2 = from s in query1
where s.time > DateTime.Now.AddDays(-7) && s.time < DateTime.Now.AddDays(-1)
select new Comblin
{
OutsNumber = s.OutAmount,
InsNumber = query.Where(m => m.time == s.time).FirstOrDefault().InAmount,
Time = s.time.ToString("yyyy-MM-dd")
};
comblins.AddRange(list2);
}
}
原文:https://www.cnblogs.com/July07/p/14808680.html