尽管我在主题中提到“多个聚合级别”,但我不确定该叫什么问题。
我想汇总呈现的数据的不同维度。在此示例中,我尝试通过import csv, json, sys
input = open(sys.argv[1])
data = json.load(input)
input.close()
output = csv.writer(sys.stdout)
output.writerow(data[0].keys()) # header row
for item in data:
output.writerow(item.values())
获取聚合数据,并通过SalesCode
获取详细聚合。因此,基本上,我可以获取与“销售汇总级别”相关联的帐户。
因此我应该得到的输出应该是这样的:
我的要求是将数据映射到以下类:
AccountId
根据以下数据:
public class Earning
{
public string EntityId
{
get;
set;
}
public string EntityName
{
get;
set;
}
public string EntityType
{
get;
set;
}
public int TradeCount
{
get;
set;
}
public int OrderCount
{
get;
set;
}
public decimal PrincipalAmount
{
get;
set;
}
public decimal GrossBrokerage
{
get;
set;
}
public decimal NetBrokerage
{
get;
set;
}
public List<Earning> Detail
{
get;
set;
}
}
直到现在,我在下面提到的工作中都尝试了以下方式,但是我不了解要使用AccountId进行第二级聚合。
DotNetFiddle:https://dotnetfiddle.net/SxGdDD
贸易舱如下:
List<Trade> Trades = new List<Trade>(){
new Trade{
AccountId = "ACT01",
SalesCode = "STEVES",
PrincipalAmount = 100,
GrossBrokerage = 0.64M,
NetBrokerage = 0.64M
},
new Trade{
AccountId = "ACT02",
SalesCode = "STEVES",
PrincipalAmount = 100,
GrossBrokerage = 0.64M,
NetBrokerage = 0.64M
},
new Trade{
AccountId = "ACT01",
SalesCode = "STEVES",
PrincipalAmount = 50,
GrossBrokerage = 0.32M,
NetBrokerage = 0.32M
},
new Trade{
AccountId = "ACT03",
SalesCode = "GRAHAMS",
PrincipalAmount = 100,
GrossBrokerage = 0.64M,
NetBrokerage = 0.64M
},
};
答案 0 :(得分:1)
您需要另一个GroupBy
。
var results = (
from r in Trades
group r by r.SalesCode
into g
select new Earning()
{
EntityId = g.Key.ToString(),
EntityName = g.Key.ToString(),
TradeCount = g.Count(),
OrderCount = g.Count(),
PrincipalAmount = g.Sum(c => c.PrincipalAmount),
GrossBrokerage = g.Sum(c => c.GrossBrokerage),
NetBrokerage = g.Sum(c => c.NetBrokerage),
Detail = g.GroupBy(c=>c.AccountId).Select(c => new Earning()
// Added GroupBy ---^^
{
EntityId = c.Key,
EntityName = c.Key,
TradeCount = c.Count(),
OrderCount = c.Count(),
PrincipalAmount = c.Sum(p=>p.PrincipalAmount),
GrossBrokerage = c.Sum(p=>p.GrossBrokerage),
NetBrokerage = c.Sum(p=>p.NetBrokerage),
}).ToList(),
}).ToList();
foreach (var item in results)
{
Console.WriteLine(item.EntityId);
Console.WriteLine(string.Format("Total Principal Amount: {0}", item.PrincipalAmount.ToString()));
Console.WriteLine(string.Format("Total Gross Brokerage Amount: {0}", item.GrossBrokerage.ToString()));
Console.WriteLine(string.Format("Total Net Brokerage Amount: {0}", item.NetBrokerage.ToString()));
foreach (Earning detail in item.Detail)
{
Console.WriteLine(string.Format("-- Detail {0}/{1}", detail.EntityId, detail.EntityName));
}
}