.net – LINQ to SQL – 按小时分组

前端之家收集整理的这篇文章主要介绍了.net – LINQ to SQL – 按小时分组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑到列类型是DateTime,如何将LINQ到SQL查询的结果分组?

解决方法

这是解决技术小时(上下文)的一个解决方案.
var query = myDC.Orders
    .GroupBy(x => x.OrderDate.Hour)
    .Select(g => new {
        Hour = g.Key,Amount = g.Sum(x => x.OrderAmount)
    });

哪个产生这个:

SELECT SUM([t1].[OrderAmount]) AS [Amount],[t1].[value] AS [Hour]
FROM (
    SELECT DATEPART(Hour,[t0].[OrderDate]) AS [value],[t0].[OrderAmount]
    FROM [dbo].[Orders] AS [t0]
    ) AS [t1]
GROUP BY [t1].[value]

这是一个营业时间的解决方案(上下文).

DateTime zeroDate = new DateTime(2008,1,1);

var query = myDC.Orders
    .GroupBy(x => System.Data.Linq.sqlClient.sqlMethods.DateDiffHour(zeroDate,x.OrderDate)
    )
    .Select(g => new { Hours = g.Key,Amount = g.Sum(x => x.OrderAmount) })
    .Select(x => new { Hour = zeroDate.AddHours(x.Hours),Amount = x.Amount});

哪个产生这个:

SELECT DATEADD(ms,(CONVERT(BigInt,(CONVERT(Float,[t2].[value2])) * 3600000)) % 86400000,DATEADD(day,[t2].[value2])) * 3600000)) / 86400000,@p1)) AS [Hour],[t2].[value] AS [Amount]
FROM (
    SELECT SUM([t1].[OrderAmount]) AS [value],[t1].[value] AS [value2]
    FROM (
        SELECT DATEDIFF(Hour,@p0,[t0].[OrderAmount]
        FROM [dbo].[Orders] AS [t0]
        ) AS [t1]
    GROUP BY [t1].[value]
    ) AS [t2]

嗯 – 那个bigint / float /毫秒的东西是丑陋和难以验证.我更喜欢在客户端添加

var results = myDC.Orders
    .GroupBy(x => System.Data.Linq.sqlClient.sqlMethods.DateDiffHour(zeroDate,Amount = g.Sum(x => x.OrderAmount) })
    .ToList()
    .Select(x => new { Hour = zeroDate.AddHours(x.Hours),Amount = x.Amount});

哪个产生这个:

SELECT SUM([t1].[OrderAmount]) AS [Amount],[t1].[value] AS [Hours]
FROM (
    SELECT DATEDIFF(Hour,[t0].[OrderAmount]
    FROM [dbo].[Orders] AS [t0]
    ) AS [t1]
GROUP BY [t1].[value]

这是做上下文时间的第三种方式.这个非常c#友好,但数据库中有字符串逻辑(yuck).

var query = myDC.Orders
    .GroupBy(x => new DateTime(x.OrderDate.Year,x.OrderDate.Month,x.OrderDate.Day,x.OrderDate.Hour,0))
    .Select(g => new { Hour = g.Key,Amount = g.Sum(x => x.OrderAmount) });

哪个生成

SELECT SUM([t1].[OrderAmount]) AS [Amount],[t1].[value] AS [Hour]
FROM (
    SELECT CONVERT(DATETIME,(CONVERT(NCHAR(4),DATEPART(Year,[t0].[OrderDate])) + ('-' + (CONVERT(NCHAR(2),DATEPART(Month,[t0].[OrderDate])) + ('-' + CONVERT(NCHAR(2),DATEPART(Day,[t0].[OrderDate])))))) + (' ' + (CONVERT(NCHAR(2),DATEPART(Hour,[t0].[OrderDate])) + (':' + (CONVERT(NCHAR(2),@p0) + (':' + CONVERT(NCHAR(2),@p1)))))),120) AS [value],[t0].[OrderAmount]
    FROM [dbo].[Orders] AS [t0]
    ) AS [t1]
GROUP BY [t1].[value]
原文链接:/mssql/79235.html

猜你在找的MsSQL相关文章