SQL - 每个 y,每个 z 的平均 x
SQL - Average x per y, per z
我有一个包含两列的数据集,一个 ID 和一个日期时间
我正在尝试每个 ID 平均 计数 小时。
到目前为止,我已经设法使用此代码来计算一天的小时数:
SELECT
id,
DATE(created),
DATE_PART(hour, created)::int AS "hour",
--Counts 15 minute windows of activity
FLOOR(DATE_PART(minute, created) / 15) AS "15 mins",
(COUNT(*) OVER (PARTITION BY id,
DATE(created)) / 4.0) AS "Online Hours"
FROM
--The temporary table I pulled the data into
#tempres
GROUP BY
id,
DATE(created),
DATE_PART(hour, created),
FLOOR(DATE_PART(minute, created) / 15)
ORDER BY
id DESC,
DATE(created),
"hour" ASC,
"15 mins" ASC;
但我一直无法弄清楚如何在窗口函数上应用 AVG 以获得月度结果。
这个 Mockaroo link 应该产生与我正在使用的相同类型的数据。
我知道这可能不是最精简的起点,所以我对任何其他想法都持开放态度!
好的,所以我提出了一个主要是功能性的查询。
通过将旧查询放入 CTE,我能够 运行 在每月的时间段内对其进行平均聚合函数。
仍然对更清洁的选项持开放态度,但我想我会把我有的放在这里。
WITH cte AS (
SELECT
id,
MAX(created) AS "created",
DATE_PART(month,
created) AS "month",
DATE(created) AS "day",
DATE_PART(hour,
created)::int AS "hour",
FLOOR(DATE_PART(minute,
created) / 15) AS "15_mins",
COUNT(id),
(COUNT(*) OVER (PARTITION BY id,
DATE(created)) / 4.0) AS "online_hours"
FROM
#tempres
GROUP BY
id,
DATE_PART(month,
created),
DATE(created),
DATE_PART(hour,
created),
FLOOR(DATE_PART(minute,
created) / 15)
ORDER BY
id DESC,
DATE(created),
"hour" ASC,
"15_mins" ASC
) SELECT
id,
DATE_PART(year, cte.created) AS "Year",
cte.month,
ROUND(AVG(online_hours), 2) AS "Average Hours"
FROM
cte
GROUP BY
id,
DATE_PART(year, cte.created),
cte.month
ORDER BY
id,
DATE_PART(year, cte.created),
cte.month;
我有一个包含两列的数据集,一个 ID 和一个日期时间
我正在尝试每个 ID 平均 计数 小时。
到目前为止,我已经设法使用此代码来计算一天的小时数:
SELECT
id,
DATE(created),
DATE_PART(hour, created)::int AS "hour",
--Counts 15 minute windows of activity
FLOOR(DATE_PART(minute, created) / 15) AS "15 mins",
(COUNT(*) OVER (PARTITION BY id,
DATE(created)) / 4.0) AS "Online Hours"
FROM
--The temporary table I pulled the data into
#tempres
GROUP BY
id,
DATE(created),
DATE_PART(hour, created),
FLOOR(DATE_PART(minute, created) / 15)
ORDER BY
id DESC,
DATE(created),
"hour" ASC,
"15 mins" ASC;
但我一直无法弄清楚如何在窗口函数上应用 AVG 以获得月度结果。
这个 Mockaroo link 应该产生与我正在使用的相同类型的数据。
我知道这可能不是最精简的起点,所以我对任何其他想法都持开放态度!
好的,所以我提出了一个主要是功能性的查询。
通过将旧查询放入 CTE,我能够 运行 在每月的时间段内对其进行平均聚合函数。
仍然对更清洁的选项持开放态度,但我想我会把我有的放在这里。
WITH cte AS (
SELECT
id,
MAX(created) AS "created",
DATE_PART(month,
created) AS "month",
DATE(created) AS "day",
DATE_PART(hour,
created)::int AS "hour",
FLOOR(DATE_PART(minute,
created) / 15) AS "15_mins",
COUNT(id),
(COUNT(*) OVER (PARTITION BY id,
DATE(created)) / 4.0) AS "online_hours"
FROM
#tempres
GROUP BY
id,
DATE_PART(month,
created),
DATE(created),
DATE_PART(hour,
created),
FLOOR(DATE_PART(minute,
created) / 15)
ORDER BY
id DESC,
DATE(created),
"hour" ASC,
"15_mins" ASC
) SELECT
id,
DATE_PART(year, cte.created) AS "Year",
cte.month,
ROUND(AVG(online_hours), 2) AS "Average Hours"
FROM
cte
GROUP BY
id,
DATE_PART(year, cte.created),
cte.month
ORDER BY
id,
DATE_PART(year, cte.created),
cte.month;