gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:39:04 26 4
gpt4 key购买 nike

考虑到列类型是 DateTime,如何按小时对 LINQ to 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]

这是营业时间 (context-ful) 的解决方案。

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, (CONVERT(BigInt,(CONVERT(Float,[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].[OrderDate]) AS [value], [t0].[OrderAmount]
FROM [dbo].[Orders] AS [t0]
) AS [t1]
GROUP BY [t1].[value]
) AS [t2]

呃 - bigint/float/milliseconds 的东西很难看而且很难验证。我更喜欢在客户端进行添加:
var results = 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) })
.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, @p0, [t0].[OrderDate]) AS [value], [t0].[OrderAmount]
FROM [dbo].[Orders] AS [t0]
) AS [t1]
GROUP BY [t1].[value]

这是进行上下文时间的第三种方式。这个是非常 C# 友好的,但是数据库中有字符串逻辑(糟糕)。

var query = myDC.Orders
.GroupBy(x => new DateTime(x.OrderDate.Year, x.OrderDate.Month, x.OrderDate.Day, x.OrderDate.Hour, 0, 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]

关于.net - LINQ to SQL - 按小时分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/575042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com