【问题标题】:How can I convert this SQL Script to LINQ? And keep the Count()?如何将此 SQL 脚本转换为 LINQ?并保留 Count()?
【发布时间】:2015-03-14 09:22:13
【问题描述】:

我已经制作并测试了一个完美运行的 MS SQL 脚本。我一直在慢慢过渡到 LINQ,但在将脚本转换为 VB.Net 和 LINQ 时遇到问题。

SELECT DATEPART(dd,Generated) AS Day, count(ID) as Total
FROM Alarm
WHERE Generated >=CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()),0),120)
GROUP BY DATEPART(dd,Generated)

基本上,我要求表格提供该月每天分组的总行数。让它在本月的未来几天放置一个 0 真是太棒了。任何关于如何将计数转换为 LINQ 的建议都会很棒。

我的代码:

Dim ChartData = (From a In db.Alarms _
Where a.Generated >= FirstDayOfMonth(DateTimeNow) And a.Generated <= LastDayOfMonth(DateTimeNow) _
Group By Day = a.Generated Into Grp = Group, Count() _
Select Grp)

'Get the first day of the month
Public Function FirstDayOfMonth(ByVal sourceDate As DateTime) As DateTime
    Return New DateTime(sourceDate.Year, sourceDate.Month, 1)
End Function

'Get the last day of the month
Public Function LastDayOfMonth(ByVal sourceDate As DateTime) As DateTime
    Dim lastDay As DateTime = New DateTime(sourceDate.Year, sourceDate.Month, 1)
    Return lastDay.AddMonths(1).AddDays(-1)
End Function

搞定了,代码如下。

        Dim ChartData = (From a In db.Alarms _
        Where a.Generated >= FirstDayOfMonth(DateTimeNow) And a.Generated <= LastDayOfMonth(DateTimeNow) _
        Group a By CalendarDate = a.Generated.Value.Date Into g = Group _
        Select New With {CalendarDate, .AlarmCount = g.Count()})

【问题讨论】:

  • 我有,但由于语法问题无法编译。想我会问人们如何在这里使用 count 并从中学习。
  • 您的where 非常复杂。您只是想增加 120 个月到现在吗?
  • 那您为什么不发布您拥有的代码并寻求语法问题的帮助?
  • 我的目标是获取当前月份的当前日期范围。
  • 发布了我的代码,但我觉得它误导了我的真正目标。

标签: sql asp.net sql-server vb.net linq


【解决方案1】:

你可以做这样的事情。 (我认为dd 意味着一天...`)

var myDate = new DateTime(); //calculate your date...
Alarms
    .Where(x => x.Generated >= myDate)
    .GroupBy(x => x.Generated.Day)
    .Select (x => new {
        Day = x.Key,
        Total = x.Count()
    }

你可能无法在sql中按x.Generated.Day进行分组,如果是,则在Where()之后添加.AsEnumerable()以在内存中进行分组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2012-08-20
    相关资源
    最近更新 更多