SQL AVERAGE TIME

2019-03-01 05:20发布

I have the following query in MSSQL:

select 
TRANSACTION_TYPE_ID
,COUNT(TRANSACTION_TYPE_ID)AS NUMBER_OF_TRANSACTIONS
,CAST(SUM(AMOUNT)AS DECIMAL (30,2)) AS TOTAL
FROM 
    [ONLINE_TRANSACTION] 
WHERE CONVERT(CHAR(8), CREATED_ON, 114) >='17:30' AND AMOUNT IS NOT NULL AND     
TRANSACTION_TYPE_ID !='CHEQUE-STOP-TRANS-TYPE' 
GROUP BY TRANSACTION_TYPE_ID
ORDER BY TRANSACTION_TYPE_ID

I want to show the type of transactions TRANSATION_TYPE_ID as above the total amount of each type of transaction as above BUT also the average time these transactions occurred CREATED_ON which is datetime I still have not find a good way of doing this?

4条回答
smile是对你的礼貌
2楼-- · 2019-03-01 05:56

If your talking about the time of day and not looking to get a specific date, ie. 5:32 instead of Jan 4, 2012 5:32, the below could help. Sorry about the caps, it's the way I'm used to writing SQL.

CONVERT(VARCHAR,AVG(DATEPART(HH,CREATED_ON)*60 + DATEPART(MI,CREATED_ON)) / 60) + ':' + 
CASE WHEN CONVERT(VARCHAR,AVG(DATEPART(HH,CREATED_ON)*60 + DATEPART(MI,CREATED_ON)) % 60) < 10
    THEN '0'+CONVERT(VARCHAR,AVG(DATEPART(HH,CREATED_ON)*60 + DATEPART(MI,CREATED_ON)) % 60)
    ELSE CONVERT(VARCHAR,AVG(DATEPART(HH,CREATED_ON)*60 + DATEPART(MI,CREATED_ON)) % 60)
END AS AVG_CREATED_ON
查看更多
一纸荒年 Trace。
3楼-- · 2019-03-01 05:57

One way would be to convert the time to seconds, calculate the average, and then convert it back to hours, minutes and seconds for the result.

查看更多
贪生不怕死
4楼-- · 2019-03-01 05:59

Based on Randolph Potter's answer, you can find the average time like:

avg(DATEPART(hh,created_on)*60 + DATEPART(mi,created_on)) % 24 as AvgHour,
avg(DATEPART(hh,created_on)*60 + DATEPART(mi,created_on)) / 24 as AvgMinute
查看更多
贪生不怕死
5楼-- · 2019-03-01 06:14
SELECT FROM_UNIXTIME( ( ROUND((UNIX_TIMESTAMP( floor(timestamp_column)) /   60 ),0) *   60 ) ) rounded_time
FROM mysql_table
WHERE timestamp_column BETWEEN STR_TO_DATE('31/07/2012','%d/%m/%Y') 
AND STR_TO_DATE('01/08/2012','%d/%m/%Y')
查看更多
登录 后发表回答