시간 또는 10 분 단위로 시간을 그룹화하는 방법
내가 할 때처럼
SELECT [Date]
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY [Date]
그룹 기간을 어떻게 지정할 수 있습니까?
MS SQL 2008
2 차 편집
노력하고있어
SELECT MIN([Date]) AS RecT, AVG(Value)
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY (DATEPART(MINUTE, [Date]) / 10)
ORDER BY RecT
% 10을 / 10으로 변경했습니다. 밀리 초없이 날짜를 출력 할 수 있습니까?
마지막으로 완료
GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)
나는 파티에 늦었지만, 기존 답변에는 나타나지 않습니다.
GROUP BY DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', date_column) / 10 * 10, '2000')
10
및MINUTE
조건은 임의의 숫자로 변경 될 수 있습니다DATEPART
각각.- 이는
DATETIME
값 을 의미합니다.- 오랜 시간 동안 잘 작동합니다. (연도간에 충돌이 없습니다.)
SELECT
명령문에 포함하면 출력이 지정한 레벨에서 잘린 출력 열이 제공됩니다.
'2000'
SQL이 날짜 계산을 수행 할 "고정 날짜"입니다. Jereonh 는0
최근 날짜를 초 또는 밀리 초 단위로 그룹화 할 때 이전 앵커 ( ) 에서 정수 오버 플로우가 발생한다는 것을 발견했습니다 . †
SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', aa.[date]) / 10 * 10, '2000')
AS [date_truncated],
COUNT(*) AS [records_in_interval],
AVG(aa.[value]) AS [average_value]
FROM [friib].[dbo].[archive_analog] AS aa
GROUP BY DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', aa.[date]) / 10 * 10, '2000')
ORDER BY [date_truncated]
데이터가 수 세기에 걸쳐있는 경우 ‡ 초 또는 밀리 초 그룹화에 단일 앵커 날짜를 사용하면 여전히 오버플로가 발생합니다. 이 경우 각 행에 비닝 비교를 해당 날짜의 자정에 고정하도록 요청할 수 있습니다.
위에 나타난 곳
DATEADD(DAY, DATEDIFF(DAY, 0, aa.[date]), 0)
대신에 사용하십시오'2000'
. 쿼리를 완전히 읽을 수는 없지만 작동합니다.대안이 대안이 될 수 있습니다
CONVERT(DATETIME, CONVERT(DATE, aa.[date]))
.
† 이 32 ≈ 4.29E + 9, 그래서 당신의 경우 DATEPART
IS SECOND
, 당신은 양쪽에 43억초를 얻을, 또는 "앵커 ± 1백36년." 마찬가지로 2 32 밀리 초는 9.7 49.7 일입니다.
‡ 데이터가 실제로 수세기 또는 백만년에 걸쳐 있고 여전히 초 또는 밀리 초 까지 정확하다면… 축하합니다! 당신이 무엇을 하든지 계속하십시오.
T-SQL에서는 다음을 수행 할 수 있습니다.
SELECT [Date]
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY [Date], DATEPART(hh, [Date])
또는
분 단위로 DATEPART(mi, [Date])
또는
10 분 사용 DATEPART(mi, [Date]) / 10
(티모시가 제안한 것처럼)
10 분 간격으로
GROUP BY (DATEPART(MINUTE, [Date]) / 10)
tzup과 Pieter888에서 이미 언급했듯이 한 시간 간격으로
GROUP BY DATEPART(HOUR, [Date])
같은 것이어야합니다
select timeslot, count(*)
from
(
select datepart('hh', date) timeslot
FROM [FRIIB].[dbo].[ArchiveAnalog]
)
group by timeslot
(구문에 대해 100 % 확신 할 수는 없습니다. 저는 오라클에 더 가깝습니다.)
Oracle에서 :
SELECT timeslot, COUNT(*)
FROM
(
SELECT to_char(l_time, 'YYYY-MM-DD hh24') timeslot
FROM
(
SELECT l_time FROM mytab
)
) GROUP BY timeslot
The original answer the author gave works pretty well. Just to extend this idea, you can do something like
group by datediff(minute, 0, [Date])/10
which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.
For MySql:
GROUP BY
DATE(`your_date_field`),
HOUR(`your_date_field`),
FLOOR( MINUTE(`your_date_field`) / 10);
declare @interval tinyint
set @interval = 30
select dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0), sum(Value_Transaction)
from Transactions
group by dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0)
My solution is to use a function to create a table with the date intervals and then join this table to the data I want to group using the date interval in the table. The date interval can then be easily selected when presenting the data.
CREATE FUNCTION [dbo].[fn_MinuteIntervals]
(
@startDate SMALLDATETIME ,
@endDate SMALLDATETIME ,
@interval INT = 1
)
RETURNS @returnDates TABLE
(
[date] SMALLDATETIME PRIMARY KEY NOT NULL
)
AS
BEGIN
DECLARE @counter SMALLDATETIME
SET @counter = @startDate
WHILE @counter <= @endDate
BEGIN
INSERT INTO @returnDates VALUES ( @counter )
SET @counter = DATEADD(n, @interval, @counter)
END
RETURN
END
For SQL Server 2012, though I believe it would work in SQL Server 2008R2, I use the following approach to get time slicing down to the millisecond:
DATEADD(MILLISECOND, -DATEDIFF(MILLISECOND, CAST(time AS DATE), time) % @msPerSlice, time)
This works by:
- Getting the number of milliseconds between a fixed point and target time:
@ms = DATEDIFF(MILLISECOND, CAST(time AS DATE), time)
- Taking the remainder of dividing those milliseconds into time slices:
@rms = @ms % @msPerSlice
- Adding the negative of that remainder to the target time to get the slice time:
DATEADD(MILLISECOND, -@rms, time)
Unfortunately, as is this overflows with microseconds and smaller units, so larger, finer data sets would need to use a less convenient fixed point.
I have not rigorously benchmarked this and I am not in big data, so your mileage may vary, but performance was not noticeably worse than the other methods tried on our equipment and data sets, and the payout in developer convenience for arbitrary slicing makes it worthwhile for us.
select from_unixtime( 600 * ( unix_timestamp( [Date] ) % 600 ) ) AS RecT, avg(Value)
from [FRIIB].[dbo].[ArchiveAnalog]
group by RecT
order by RecT;
replace the two 600 by any number of seconds you want to group.
If you need this often and the table doesn't change, as the name Archive suggests, it would probably be a bit faster to convert and store the date (& time) as a unixtime in the table.
I know I am late to the show with this one, but I used this - pretty simple approach. This allows you to get the 60 minute slices without any rounding issues.
Select
CONCAT(
Format(endtime,'yyyy-MM-dd_HH:'),
LEFT(Format(endtime,'mm'),1),
'0'
) as [Time-Slice]
참고URL : https://stackoverflow.com/questions/5002661/how-to-group-time-by-hour-or-by-10-minutes
'Programming' 카테고리의 다른 글
C #에서 명명 된 문자열 형식 (0) | 2020.06.07 |
---|---|
Chrome의 Greasemonkey 스크립트에서 jQuery를 사용하려면 어떻게해야하나요? (0) | 2020.06.07 |
변경 불가능한 컬렉션과 수정 불가능한 컬렉션 (0) | 2020.06.07 |
CultureInfo.InvariantCulture은 무슨 뜻인가요? (0) | 2020.06.07 |
Java 스위치 명령문 : 상수 표현식이 필요하지만 상수입니다. (0) | 2020.06.07 |