【问题标题】:Count number of distinct locations served by the same vehicle postgresql计算由同一车辆 postgresql 服务的不同位置的数量
【发布时间】:2018-12-04 21:30:40
【问题描述】:

我有一张类似于以下的表格:

CREATE TABLE movements (
    "id" integer,
    "date" timestamp with time zone,
    "origin" character varying(255),
    "destination" character varying(255),
    "vehicle" character varying(255)   
);

INSERT INTO movements (id,date,origin,destination,vehicle)
 VALUES (1, '2017-11-01 00:00:00+00', 'loc_A', 'loc_B', 'V1'),
    (2, '2017-11-01 00:00:00+00', 'loc_C', 'loc_B', 'V1'),
    (3, '2017-11-01 00:00:00+00', 'loc_D', 'loc_B', 'V1'),
    (4, '2017-11-02 00:00:00+00', 'loc_E', 'loc_B', 'V1'),
    (5, '2017-11-02 00:00:00+00', 'loc_A', 'loc_B', 'V2'),
    (6, '2017-11-02 00:00:00+00', 'loc_F', 'loc_B', 'V2');

如何计算每个出发地使用相同车辆的不同出发地的数量,以及同一天每个出发地使用相同车辆的出发地的平均和最大数量?

在这种情况下会是这样的输出

location, total, daily_mean, daily_max
loc_A   ,     4,        1.5,        2
loc_C   ,     3,          2,        2
loc_D   ,     3,          2,        2
loc_E   ,     3,          0,        0
loc_F   ,     1,          1,        1

【问题讨论】:

  • 我只看到 loc_A 的两辆车作为原点(2017 年 11 月 1 日的 V1 和 2017 年 11 月 2 日的 V2) - 您的预期输出中总共 4 辆来自哪里? loc_C、loc_D 和 loc_E 类似 - 我只能看到一辆车,而不是 3。
  • @a_horse_with_no_name 我想知道的是使用相同车辆的起点位置的数量,这些车辆已被每个起点位置使用。 loc_A 使用过的车辆 V1 和 V2 已用于 loc_C、loc_D 和 loc_E (V1) 和 loc_F (V2)
  • 我还是不明白。
  • 也许一个不同的例子适用于相同的问题并且可能更容易理解,可能是使用同一辆超级汽车的不同人(而不是地点)的数量。人 3 个人使用的二手车 V1 和其他人使用的汽车 V2。
  • 也许标题中的“同一辆车”没有帮助,对此我深表歉意。 “相同的车辆”可能会更好。使用最后一个例子,这样你就可以更好地理解了,假设 A 人患有一种传染病,可以通过使用同一辆 uber 车传播,那么它可能已经将这种疾病传播给了另外 4 个人。

标签: postgresql subquery


【解决方案1】:

根据您的描述,我认为以下内容应该可行。它使用自连接来在公用表表达式中按天计算统计信息,然后在这些天中聚合以获得所需的列。为了获得整个列表,我们将各个日期的位置列表取消嵌套,然后再次将它们组合成一个数组,与在基表上使用子查询相比,这可能并不理想,但希望就足够了:

with day_values as (
    select m.origin, m.date
   , count(distinct m2.origin) as locations_with_shared_vehicle
   , array_agg(distinct m2.origin) as location_list
  from movements m
  join movements m2
   on m2.vehicle = m.vehicle
   and m2.date = m.date
   and m2.origin <> m.origin
  group by m.origin, m.date )

select t.origin as location
 , array_length( (select array( SELECT DISTINCT unnest(t2.location_list)  from day_values t2 WHERE t2.origin = t.origin) ), 1) AS total_locations
, avg(locations_with_shared_vehicle) as daily_mean
 , max(locations_with_shared_vehicle) as daily_max
from day_values t
 group by t.origin
 order by t.origin;

小提琴:http://sqlfiddle.com/#!17/00daa/1/0

【讨论】:

  • 谢谢!是这样吗,我也许可以从那里工作。也许我没有设法正确地提出问题,但是“total_locations”与当天无关,另外两个在同一天。无论如何,非常感谢您努力首先理解问题然后找到解决方案。在您的帮助下,我设法得到了我需要的结果。
猜你喜欢
  • 2020-04-17
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
相关资源
最近更新 更多