2016-07-28 76 views
1

我有一個表,我需要在報告中總結。這是我的示例表。
Linq .GroupBy()與計數

   Orders 
_____________________________________ 
CustomerId | CustomerName | OrderType 
___________|______________|__________ 
1   |  Adam  | Shoe 
1   |  Adam  | Shoe 
1   |  Adam  | Shoe 
1   |  Adam  | Hat 
1   |  Adam  | Hat 
2   |  Bill  | Shoe 
2   |  Bill  | Hat 
3   |  Carl  | Sock 
3   |  Carl  | Hat 

我試圖總結本傳回在我的視圖模型沒有一個循環。這是我試圖實現的結果。

CustomerName | Shoe | Hat | Sock | Total Orders 
------------ | ---- | --- | ---- | ------------ 
Adam   | 3 | 2 | 0 |  5 
Bill   | 1 | 1 | 0 |  2 
Carl   | 0 | 1 | 1 |  2 

//var resultList = dbContext.Orders.OrderBy(o => o.CustomerId); 

如何使用GroupBy和Count來實現我想要的結果?這是最好的方法嗎?

+0

包括當前查詢你正在使用 –

+1

同意@不幸運..和你正在工作的數據庫 –

+2

請澄清項目列表是固定爲3還是你想要的列數根據不同的項目而有所不同 –

回答

6

group clause (C# Reference)

var summary = from order in dbContext.Orders 
       group order by order.CustomerId into g 
       select new { 
        CustomerName = g.First().CustomerName , 
        Shoe = g.Count(s => s.OrderType == "Shoe"), 
        Hat = g.Count(s => s.OrderType == "Hat"), 
        Sock = g.Count(s => s.OrderType == "Sock"), 
        TotalOrders = g.Count() 
       }; 
+0

不錯的解決方案。我將.First()更改爲.FirstOrDefault()。 – pacopicorico

3

如果項目是固定的:

public List<OrderViewModel> GetCustOrders() 
{ 
    var query = orders 
     .GroupBy(c => c.CustomerName) 
     .Select(o => new OrderViewModel{ 
      CustomerName = o.Key, 
      Shoe = o.Where(c => c.OrderType == "Shoe").Count(c => c.CustomerId), 
      Hat = o.Where(c => c.OrderType == "Hat").Count(c => c.CustomerId), 
      Sock = o.Where(c => c.OrderType == "Sock").Count(c => c.CustomerId), 
      Total = o.Count(c => c.CustomerId) 
     }); 

    return query; 
} 
0

使用SQL是一種選擇,我測試了它,並得到你想要什麼:

select p.*, t.total as 'Total Orders' from 
(
    select CustomerName, count(CustomerId) total from Orders group by CustomerName 
) as t inner join 
(
    select * from Orders 
    pivot(count(CustomerId) 
     for OrderType in ([Shoe], [Hat], [Sock]) 
     ) as piv 
)as p on p.CustomerName = t.CustomerName