根据两行之间的差异选择列

时间:2019-03-14 09:09:24

标签: database postgresql

我正在使用如下所示的PostgreSQL数据库:

   +--------------+---------------+---------------+---------------+
   | avg_speed_p0 | avg_speed_p25 | avg_speed_p50 | avg_speed_p75 |
   +--------------+---------------+---------------+---------------+
1  |     85.15    |     87.23     |     84.16     |     85.44     |
2  |     78.63    |     82.76     |     78.01     |     83.15     |
   +--------------+---------------+---------------+---------------+

在这里我计算了很多汽车之间在25米之间的点的日(1)和夜(2)的平均速度。

我已经使用以下方法制作了表格:

create table avg_speeds as
   select * from avg_speed_day
      union
   select * from avg_speed_night

我尝试通过以下方式将主键设置为daynight

alter table avg_speed_day add column time varchar

然后:

insert into avg_speed_day (time) values ('day')

但这不起作用,只能给我:

   +--------------+---------------+---------------+---------------+--------+
   | avg_speed_p0 | avg_speed_p25 | avg_speed_p50 | avg_speed_p75 |  time  |
   +--------------+---------------+---------------+---------------+--------+
1  |     85.15    |     87.23     |     84.16     |     85.44     | [null] |
2  |     [null]   |     [null]    |     [null]    |     [null]    |   day  |
   +--------------+---------------+---------------+---------------+--------+

我想得出一个表,该表计算出白天(1)和夜晚(2)之间的差,并且仅显示一次大于5的差。

赞:

   +---------------+----------------+
   | diff_speed_p0 | diff_speed_p50 |
   +---------------+----------------+
1  |      6.52     |      6.15      |
   +---------------+----------------+

1 个答案:

答案 0 :(得分:0)

您的评论表明您从其他表或视图中收到了这两行。

像这样直接使用它们:

WITH day   AS (SELECT avg_speed_p0, avg_speed_p25, avg_speed_p50, avg_speed_p75
               FROM avg_speed_day),
     night AS (SELECT avg_speed_p0, avg_speed_p25, avg_speed_p50, avg_speed_p75
               FROM avg_speed_night)
SELECT CASE WHEN abs(day.avg_speed_p0 - night.avg_speed_p0) > 5
            THEN day.avg_speed_p0 - night.avg_speed_p0
       END AS avg_speed_p0,
       CASE WHEN abs(day.avg_speed_p25 - night.avg_speed_p25) > 5
            THEN day.avg_speed_p25 - night.avg_speed_p25
       END AS avg_speed_p25,
       CASE WHEN abs(day.avg_speed_p50 - night.avg_speed_p50) > 5
            THEN day.avg_speed_p50 - night.avg_speed_p50
       END AS avg_speed_p50,
       CASE WHEN abs(day.avg_speed_p75 - night.avg_speed_p75) > 5
            THEN day.avg_speed_p75 - night.avg_speed_p75
       END AS avg_speed_p75
FROM day CROSS JOIN night;

SQL中无法动态省略列。