如何在postgres中进行计算

时间:2015-02-02 20:45:19

标签: sql postgresql

我有两个不同的表值,一个有15分钟的间隔,一个有小时值。 我想创建一个包含PHF列的新表 其中PHF =每小时值/ 4 *(该小时最长15分钟间隔) 如何为此编写查询?

TABLE1-15 min interval

ID    PHASE       STARTIME               COUNT
1201; 1;     "2015-01-05 12:15:00-06";    234
1201; 1;     "2015-01-05 12:30:00-06";     344
1201; 1;     "2015-01-05 12:45:00-06";     755
1202; 2;     "2015-01-05 01:00:00-06";     234
1202; 2;     "2015-01-05 01:15:00-06";     244
1202; 2;     "2015-01-05 01:30:00-06";     245
1202; 2;     "2015-01-05 01:45:00-06";     246

TABLE2-上表每小时间隔

ID   PHASE   STARTIME                      COUNT
1201; 1;     "2015-01-05 12:00:00";        1333
1202; 2;     "2015-01-05 01:00:00";        969

输出

ID   PHASE   STARTIME                      COUNT     PHF
1201; 1;     "2015-01-05 12:00:00";        1333;     0.44
1202; 2;     "2015-01-05 01:00:00";        969;       0.9847

PHF定义为:每小时值/(4 *最大值(15分钟值)

所以从上面的例子来看,phf1 = 1333 /(4 * 755)=。44

和phf2 =(969 /(4 * 246)=。9847

1 个答案:

答案 0 :(得分:0)

<强> SQL Fiddle Example

SELECT a.id,
  a.phase,
  b.starttime,
  b.count/cast((4 * a.count) as numeric) AS "PHF"
FROM TableA a
JOIN TableB b on a.id = b.id
JOIN (SELECT id, phase, max(starttime) as "starttime" 
      FROM TableA GROUP BY id, phase) c on a.id = c.id and a.starttime = c.starttime