我在PostgreSQL中有一个像这样创建的表:
-- Table: myTable
-- DROP TABLE myTable;
CREATE TABLE myTable
(
"TimeStamp" double precision,
"Temperature" double precision,
"Pressure" double precision,
"Milligrams" double precision,
table_pkey serial NOT NULL,
CONSTRAINT myTable_pkey PRIMARY KEY (table_pkey)
);
其中TimeStamp是特定日期后经过的一些秒数。
我看到如何将一些表行平均在一起以生成压缩表。例如,
SELECT AVG("TimeStamp") "Seconds", AVG("Temperature") "Temperature",
AVG("Pressure") "Pressure", AVG("Milligrams") "Milligrams"
FROM (SELECT ROW_NUMBER() OVER(ORDER BY null) - 1 rn, * FROM myTable) t
GROUP BY (rn/120)
ORDER BY rn/120
将输出一个表,该表由每个输出行120个输入行的因子压缩。
我想要将TimeStamp的一些跨度放在一起,而不是将某些行平均在一起。例如,要生成一个表,其中每行包含一天中每小时的平均值。
修改
这与将timestamp列更改为typestamp类型相结合似乎有效:
SELECT date_trunc('hour', "Acquired"), AVG("Temperature"),
AVG("Pressure"), AVG("Milligrams")
FROM myTable
WHERE 1=1
GROUP BY date_trunc('hour', "Acquired")
ORDER BY 1
答案 0 :(得分:1)
我会将“TimeStamp”列类型更改为 timestamp 类型(并且可能会将列名更改为“已创建”以避免混淆),像这样:
SELECT date_part('hour', created), AVG("Temperature")
FROM myTable
WHERE ...
GROUP BY date_part('hour', created)
因此,要生成一个表,其中每行包含一天中每小时的平均值,您可以相应地使用date_part和group:
noun2 = input("Saw a ________ (Noun).").lower
答案 1 :(得分:1)
尝试DATE_TRUNC(),它会将截断的完整日期/时间返回到所需的精度,例如'小时'
PostgreSQL 9.3架构设置:
CREATE TABLE myTable
(Created timestamp)
;
INSERT INTO myTable
(Created)
VALUES
('2015-09-25 00:11:12'),
('2015-09-25 00:45:46'),
('2015-09-25 01:20:19'),
('2015-09-25 01:54:53'),
('2015-09-25 02:29:26'),
('2015-09-25 03:04:00'),
('2015-09-25 03:38:34'),
('2015-09-25 04:13:07'),
('2015-09-25 04:47:41'),
('2015-09-25 05:22:14'),
('2015-09-25 05:56:48'),
('2015-09-25 06:31:22'),
('2015-09-25 07:05:55'),
('2015-09-25 07:40:29'),
('2015-09-25 08:15:02'),
('2015-09-25 08:49:36'),
('2015-09-25 09:24:10'),
('2015-09-25 09:58:43'),
('2015-09-25 10:33:17'),
('2015-09-25 11:07:50'),
('2015-09-25 11:42:24'),
('2015-09-25 12:16:58'),
('2015-09-25 12:51:31'),
('2015-09-25 13:26:05'),
('2015-09-25 14:00:38'),
('2015-09-25 14:35:12'),
('2015-09-25 15:09:46'),
('2015-09-25 15:44:19'),
('2015-09-25 16:18:53'),
('2015-09-25 16:53:26')
;
查询1 :
SELECT date_trunc('hour', Created), COUNT(*)
FROM myTable
WHERE 1=1
GROUP BY date_trunc('hour', Created)
ORDER BY 1
<强> Results 强>:
| date_trunc | count |
|-----------------------------|-------|
| September, 25 2015 00:00:00 | 2 |
| September, 25 2015 01:00:00 | 2 |
| September, 25 2015 02:00:00 | 1 |
| September, 25 2015 03:00:00 | 2 |
| September, 25 2015 04:00:00 | 2 |
| September, 25 2015 05:00:00 | 2 |
| September, 25 2015 06:00:00 | 1 |
| September, 25 2015 07:00:00 | 2 |
| September, 25 2015 08:00:00 | 2 |
| September, 25 2015 09:00:00 | 2 |
| September, 25 2015 10:00:00 | 1 |
| September, 25 2015 11:00:00 | 2 |
| September, 25 2015 12:00:00 | 2 |
| September, 25 2015 13:00:00 | 1 |
| September, 25 2015 14:00:00 | 2 |
| September, 25 2015 15:00:00 | 2 |
| September, 25 2015 16:00:00 | 2 |