2013-04-15 127 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好吧我覺得我現在明白了更好 - 看我更新的回答 –