【发布时间】:2021-04-10 04:23:24
【问题描述】:
我有这样的表:
p_id | store | createdat | device | deviceserial | application
------+-------+---------------------+---------+--------------+-------------
| z10 | 2020-09-02 08:02:39 | Android | 636363636890 | app-a
| z10 | 2020-09-02 08:08:18 | Android | 636363636890 | app-a
| z10 | 2020-09-02 08:10:10 | Android | 636363636890 | app-a
| z10 | 2020-09-02 08:20:10 | Android | 636363636890 | app-a
| z10 | 2020-09-02 10:40:11 | IOS | 6625839827 | app-b
| z10 | 2020-09-02 10:45:11 | IOS | 6625839827 | app-b
| z10 | 2020-09-02 10:50:11 | IOS | 6625839827 | app-b
| z11 | 2020-09-02 08:47:10 | Android | 636363636891 | app-a
| z11 | 2020-09-02 08:55:10 | Android | 636363636891 | app-a
| z11 | 2020-09-02 08:59:10 | Android | 636363636891 | app-a
| z11 | 2020-09-02 13:01:11 | IOS | 6625839828 | app-b
| z11 | 2020-09-02 13:15:11 | IOS | 6625839828 | app-b
| z10 | 2020-09-02 12:03:10 | Android | 636363636890 | app-a
| z10 | 2020-09-02 12:09:10 | Android | 636363636890 | app-a
| z10 | 2020-09-02 12:12:10 | Android | 636363636890 | app-a
| z10 | 2020-09-02 15:15:11 | IOS | 6625839827 | app-b
| z10 | 2020-09-02 15:20:11 | IOS | 6625839827 | app-b
| z11 | 2020-09-02 10:25:10 | Android | 636363636891 | app-a
| z11 | 2020-09-02 10:35:10 | Android | 636363636891 | app-a
我正在尝试向另一个表(device_usage_test1)插入一些查询。那是我的表:
create table if not exists device_usage_test1(id SERIAL,deviceserial VARCHAR(50) UNIQUE,device VARCHAR(50),deviceusage DOUBLE PRECISION)
这是我的插入命令:
insert into device_usage_test1(deviceserial,device,deviceusage) select deviceserial,device,sum(deviceusage) as deviceusage
from (
select deviceserial,device,
extract(epoch from (max(createdat)::timestamp - min(createdat)::timestamp)) as deviceusage,
date_trunc('hour', createdat) +
(((date_part('minute', createdat)::integer / 10::integer) * 10::integer)|| ' minutes')::interval AS hr
FROM datatable
group by deviceserial,hr,device
) t
group by deviceserial,device;
稍后我将对 device_usage_test1 进行 upsert 查询。所以我的设备序列号必须是唯一的。
但是当我尝试使用deviceserial(唯一)插入时。它给了我错误:
ERROR:duplicate key value violates unique constraint "device_usage_deviceserial_key""
DETAIL: Key (deviceserial)=(636363636890) already exists.
【问题讨论】:
标签: postgresql