如何按天将Linq分组为SQL结果并包括每组的计数?

时间:2012-09-18 14:18:44

标签: linq-to-sql group-by

我需要在一段时间内创建所有CustomerOrders,按天分组(无论当天的什么时间),然后还包括每天的CustomerOrders计数。我的ChartDateCount类有两个属性 - Date和Count。

所以,这是一些示例SQL数据:

OrderID     Created
1           1/1/2012 04:30:12  
2           1/1/2012 05:15:29  
3           1/1/2012 07:09:45  
4           1/3/2012 01:12:21  
5           1/4/2012 06:33:58  
6           1/4/2012 08:30:26  
7           1/5/2012 10:17:41  
8           1/5/2012 11:30:43  
9           1/6/2012 01:11:11  

我的输出应该是:

Date         Count
1/1/2012     3
1/3/2012     1
1/4/2012     2
1/5/2012     2
1/6/2012     1

这是我到目前为止所做的。

Dim chartData as List(Of ChartDateCount) = _
         ( _
            From co In dc.CustomerOrders _
            Where co.Created >= fromDate _
            And co.Created <= toDate _
            Select New ChartDateCount With {.Date = ???, .Count = ???} _
         ).ToList()

我有点接近这个,但我无法获得日期填充:

From co In CustomerOrders _
Where co.Created >= "1/1/2012" And co.Created <= "1/7/2012" _
Group co By co.Created.Value.Date Into g = Group _
        Select New ChartDateCount With {.Date = ????, .Count = g.Count()}

更新

这正是我想要做的事情(见下文),但我收到一个错误:The query operator 'ElementAtOrDefault' is not supported.

From co In CustomerOrders _
Where co.Created >= "1/1/2012" And co.Created <= "1/7/2012" _
Group co By co.Created.Value.Date Into g = Group _
        Select New ChartDateCount With {.Date = g(0).Created.Value.Date, .Count = g.Count()}

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找g.Key

 Select New ChartDateCount With {.Date = g.Key, .Count = g.Count()}

Key属性包含按您分组的值。

http://msdn.microsoft.com/en-us/library/bb343251.aspx

答案 1 :(得分:0)

我找到了一种方法,但如果有人有更有效的方法来解决这个问题,我肯定会给你信用......

Dim chartData as List(Of ChartDateCount) = _
    (
        From co In dc.CustomerOrders _
                Where co.Created > fromDate _
                   And co.Created < toDate _
            Group By co.Created.Value.Date Into g = Group _
                   Select New ChartNameValue With _
                   {
                      .Date = (From co2 As CustomerOrder In g).Take(1).Single().Created.Value.Date, _
                      .Count = g.Count()
                   }
     ).ToList()