SQL以分钟计算平均下载量

时间:2016-11-12 02:30:09

标签: sql impala

我无法从示例记录中获得平均下载分钟,如ANSI-92 SQL或Impala SQL标准中所示。

  • login_id,starttimestamp,stoptimestamp,download_bytes
  • abc@fcc.com,2015-12-31 23:59:50,2016-01-01 00:00:20 ,438.0
  • abc@fcc.com,2016-01-01 00:00:28 ,2016-01-01 00:01:13 ,2190.0
  • abc@fcc.com,2016-01-01 00:01:21 ,2016-01-01 00:01:54,876.0
  • abc@fcc.com,2016-01-01 00:01:59,2016-01-01 00:02:34 ,1168.0
  • abc@fcc.com,2016-01-01 00:02:43 ,2016-01-01 00:03:34,1179.0

以粗体显示的时间分享starttimestamp和stoptimestamp的时间空间(以分钟为单位)。如何获得平均下载

  • 00:00:00分钟(00:00:20 - 00:00:28)
  • 00:01:00分钟(00:01:13 - 00:01:21)
  • 00:02:00分钟(00:02:34 - 00:02:43)

等等。

有什么建议吗?非常感谢你提前!

此致

Pozy

1 个答案:

答案 0 :(得分:1)

select
    (unix_timestamp(stoptimestamp)-unix_timestamp(starttimestamp)) / 60.0 diff_minutes
from your_table

使用unix_timestamp()计算以秒为单位的差值,然后除以60或60.0,具体取决于结果中所需的精度。

要计算多行的平均下载量,您需要使用SUM()来聚合字节,并使用时间单位。 您可能希望使用秒进行初始计算,然后除以60.0

以下示例是针对SQL Sever编写的,因为我没有使用Impala

declare  @mytable table
    ([login_id] varchar(11), [starttimestamp_] datetime, [stoptimestamp_] datetime, [download_bytes] decimal(12,1))
;

INSERT INTO @mytable
    ([login_id], [starttimestamp_], [stoptimestamp_], [download_bytes])
VALUES
    ('abc@fcc.com', '2015-12-31 23:59:50', '2016-01-01 00:00:20', 438.0),
    ('abc@fcc.com', '2016-01-01 00:00:28', '2016-01-01 00:01:13', 2190.0),
    ('abc@fcc.com', '2016-01-01 00:01:21', '2016-01-01 00:01:54', 876.0),
    ('abc@fcc.com', '2016-01-01 00:01:59', '2016-01-01 00:02:34', 1168.0),
    ('abc@fcc.com', '2016-01-01 00:02:43', '2016-01-01 00:03:34', 1179.0)
;

select
  sum(download_bytes) sum_bytes
, sum(datediff(second,starttimestamp_,stoptimestamp_)) sum_time_unit
, sum(download_bytes)/sum(datediff(second,starttimestamp_,stoptimestamp_)) avg_bytes_sec
, (sum(download_bytes)/sum(datediff(second,starttimestamp_,stoptimestamp_)))/60.0 avg_bytes_min
from @mytable
-- WHERE ...
-- GROUP BY ...

+===========+===============+===============+===============+
| sum_bytes | sum_time_unit | avg_bytes_sec | avg_bytes_min |
+===========+===============+===============+===============+
| 5851      | 194           | 30.159793     | 0.502663      |
+-----------+---------------+---------------+---------------+

请参阅:http://data.stackexchange.com/stackoverflow/query/576857/sql-to-calculate-average-download-in-minutes