LINQ to SQL使用GROUP BY和COUNT with Date(CONVERT问题)

时间:2009-05-13 14:35:30

标签: linq-to-sql

我已阅读this question,但这并不是我想要的。 我的问题是我想做到这一点:

SELECT CONVERT(varchar(10), m.CreateDate, 103) as [Date] , count(*) as [Count] FROM MEMBERS as m
WHERE m.CreateDate >= '24/01/2008' and m.CreateDate <= '26/06/2009' 
Group by CONVERT(varchar(10), m.CreateDate, 103)

结果是:

 Date     Count 

 02/03/2009 4  
 24/02/2009 3   
 25/02/2009 3  
 26/02/2009 3

我正在这样做:

From m In Me.Members _
Where m.CreateDate >= "22/02/2008" And m.CreateDate <= "22/05/2009" _
Group m By m.CreateDate Into g = Group _
Select New With {CreateDate, .Count = g.Count()}

根据LINQPad在SQL中执行此操作:

SELECT COUNT(*) AS [Count], [t0].[CreateDate]
FROM [Members] AS [t0]
WHERE ([t0].[CreateDate] >= @p0) AND ([t0].[CreateDate] <= @p1)
GROUP BY [t0].[CreateDate]

结果是:

      Date          Count
24/02/2009 00:00:00  1
24/02/2009 07:07:10  1
24/02/2009 12:24:10  1
25/02/2009 03:43:05  1 
25/02/2009 03:48:36  1 
25/02/2009 04:25:11  1 
26/02/2009 01:51:24  1 
26/02/2009 09:54:55  1 
26/02/2009 09:55:31  1 
02/03/2009 05:29:22  1 
02/03/2009 05:45:50  1 
02/03/2009 06:15:31  1 
02/03/2009 06:59:07  1

所以我明白,差异是CONVERT部分。那么如何从Date或Datetime转换为SmallDate或LINQ中的类似内容?

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

From m In Me.Members _
Where m.CreateDate.Date >= new DateTime( 2009, 2, 22 ) And m.CreateDate.Date <= new DateTime( 2009, 5, 22) _
Group m By day = m.CreateDate.Date Into g = Group _
Select New With { .Date = day.ToString( "dd/MM/yyyy" ), .Count = g.Count()}

如果CreateDate可以为空,那么在提取Date之前,您需要使用Value参数。您也可以在WHERE查询中省略日期的提取,具体取决于结束日期检查的意义(包括它,然后使用日期,否则省略日期)。

相关问题