嘿,我有一个我无法理解的linq查询。它从表中提取以获取特定公司(商店集合)的销售数据。
销售表是各个销售商品的集合,多个销售商品可以在一个帐单上。我需要创建一个查询,按商店对一天的销售额进行排序,然后计算当天该商店的总票据数,并给出该商店当天的平均帐单。
这是我到目前为止的开始
//get list of all stores bill count/average bill
FactSales.Where(d => d.DateKey >= 20130920).Where(d => d.DateKey <= 20130920)
.Where(c => c.CompanyID == 4).GroupBy(g=>new{g.StoreID, g.BillID}).Select(g=>new{Store = g.Key.StoreID, Amount = g.Sum(a => a.Amount).Value })
这会为我提供所有单个账单的清单,但如何在列表中获取每个商店的平均和账单数量:storeID,Avg Bill(所有商店账单/账单的总和)和账单计数每个商店?
我已经在这一段时间阅读了许多帖子,我一定会错过一些非常明显的内容。
任何帮助将不胜感激!
答案 0 :(得分:1)
FactSales
// filter sale positions by day
.Where(d => d.DateKey >= 20130920 && d.DateKey <= 20130920)
// filter sale positions by company
.Where(c => c.CompanyID == 4)
// group values by store and bill so each row will contains all sales in one bill
.GroupBy(g=>new { g.StoreID, g.BillID })
// calculate total amount for each bill
.Select(g=>new { Store = g.Key.StoreID, Bill = g.Key.BillID, Amount = g.Sum(a => a.Amount).Value })
// group bills by store so each row will contains all bills with total amount for this store
.GroupBy(g => g.Store)
// calculate bills count and avg amount for this store
.Select(g => new { Store = g.Key, Bills = g.Count(), AvgBill = g.Average(x => x.Amount) });
我认为g.Sum(a => a.Amount).Value
不应包含Value
属性,您只能g.Sum(a => a.Amount)
。
答案 1 :(得分:0)
我知道这也会有效:
var result = FactSales
.Where(d => d.DateKey >= 20130920 && d.DateKey <= 20130920)
.Where(c => c.CompanyID == 4)
.GroupBy(t => new { t.StoreId })
.Select(X => new
{
Store = X.Key.StoreId,
Sum = X.Sum(t => t.Amount),
Bills = X.Count(),
average = X.Sum(t => t.Amount) / X.Count()
});
不是