2013-04-15 120 views
2

我有三个表:CustomersOrigins和(映射表)CustomerOrigins。请注意,顾客可以从多个Origin(例如InternetAdvertisementNewsletter查询SQL Server的百分比

现在我想表明的在我的客户从发起饼图起源。

结果应该是List<string, double>

我完全失去了,即使在如何开始这整个查询...任何提示将不胜感激。

回答

2

您不能制作List<string, double>,因为List<T>只需要一个类型参数。试试这个:

var results = 
    (from c in db.Customers 
    from o in c.Origins 
    group o by o.DisplayName into g 
    let total = db.Customers.Count() 
    select new 
    { 
     Origin = g.Key, 
     Percent = ((double)g.Count()/(double)total) * 100 
    }) 
    .ToList(); 

这有(前各产地一次)计算单个客户多次的可能性,这样你就不会出来与合计100%的列表。

如果你想在CustomerOrigin记录的百分比,试试这个

var results = 
    (from c in db.Customers 
    from o in c.Origins 
    group o by o.DisplayName into g 
    let total = db.Customers.Sum(x => x.Origins.Count()) 
    select new 
    { 
     Origin = g.Key, 
     Percent = ((double)g.Count()/(double)total) * 100 
    }) 
    .ToList(); 
+0

哦,是的,正确的用'名单<字符串,双>'。在你的查询中,我得到了这个异常:'base {System.SystemException} = {“调用'GroupBy'方法的键选择器类型在底层存储提供者中没有可比性。'}' – SeToY

+0

'c.Origins '会是一个集合(n:m关系),这就是为什么在那里没有'OriginName'属性。我尝试c组由c.CustomerOrigins.Select(co => co.Origin)通过c.CustomerOrigins.Select(co => co.Origin).g选择(o => o.DisplayName)到g'但无济于事 – SeToY

+0

@SeToY好吧我觉得我现在明白了更好 - 看我更新的回答 –