LINQ to SQL - 시간 단위로 그룹화


11

열 유형이 DateTime 인 것으로 간주하여 시간별 LINQ to SQL 쿼리 결과를 그룹화하려면 어떻게합니까?

23

다음은 기술 지원 (상황에 맞지 않는) 솔루션입니다. 이 생성

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] 

여기 영업 시간 (상황에 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/플로트/물건 추한 확인하기 어렵다 밀리 초. 이 생성

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] 

을 그리고 것은 contextful 시간을하는 세 번째 방법입니다. 이것은 매우 친숙하지만, 문자열 로직이 데이터베이스에 있습니다 (yuck).

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] 
를 생성

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) });