我有2张表,我试图选择,单位和Feed。
表unit
是包含
unitid, userid, guid, fields, createdat
和另一个表feed
包含
feedid, unitid, value, createdat
表格单元的示例数据:
1,1000,'0b243396-a015-11e6-8001-9cf387d90940','a','2016-11-04 21:36:32.71281' 2,1000,'0b243396-a015-11e6-8001-9cf387d90941','b','2016-11-04 21:40:32.71281' 3,1001,'0b243396-a015-11e6-8001-9cf387d90942','b','2016-11-04 21:47:32.71281' 4,1001,'0b243396-a015-11e6-8001-9cf387d90943','c','2016-11-04 21:50:32.71281'
和表格提要:
1,1,'0.0021','2016-11-05 00:50:32.71281' 2,1,'0.0025','2016-11-05 01:00:32.71281' 3,2,'0.0008','2016-11-05 00:51:22.71281' 4,2,'0.0018','2016-11-05 01:01:22.71281' ... 24,1,'0.0800','2016-11-05 23:55:32.71281' 25,2,'0.0540','2016-11-05 23:55:32.71281'
我想要得到的是选择userid = n注册的每个单位的MIN和MAX总和。
我已经尝试过了:
SELECT SUM(value::DOUBLE PRECISION)::text FROM
((SELECT f.value FROM feed f, unit u WHERE f.unitid = unit.id AND f.createdat >= now()::date + interval '1h' ORDER BY f.createdat DESC LIMIT 1)
UNION ALL
(SELECT f.value FROM feed f, unit u WHERE f.unitid = unit.id AND f.createdat >= now()::date + interval '1h' ORDER BY f.createdat ASC LIMIT 1)) t
但我不知道应该在哪里放置userid = n子句。
那么如何选择特定用户ID注册的每个单位的MIN和MAX总和? (每日间隔)
答案 0 :(得分:1)
这是你在找什么?
SELECT f.unitid,
min(f.value) + max(f.value)
FROM unit u
JOIN feed f ON u.id = f.unitid
WHERE u.userid = 1000
GROUP BY f.unitid;
┌────────┬──────────┐
│ unitid │ ?column? │
├────────┼──────────┤
│ 1 │ 0.0821 │
│ 2 │ 0.0548 │
└────────┴──────────┘
(2 rows)