如何在 PostgreSQL 中按 array_agg 计算一个组

How to count on a group by array_agg in PostgreSQL

这是我的 SQL: SELECT t.uid, array_agg(t.place) FROM tour_tracking t WHERE (orderon::time BETWEEN '18:00:00' AND '20:00:00') GROUP BY t.uid;

原始结果:
|---------------|----------------------| | uid | place | |---------------|----------------------| | a01 | {hk, hk, jp} | |---------------|----------------------| | a02 | {jp, jp, jp, jp, uk} | |---------------|----------------------|

现在我想为每个 group-by-ed uid 计算每个 DISTINCT 位置。 有希望的结果:

|---------------|--------------------------------------| | uid | place | |---------------|--------------------------------------| | a01 | something like this: {hk,2, jp,1} | |---------------|--------------------------------------| | a02 | {jp:4, uk:1} | |---------------|--------------------------------------|
我尝试组合一些 count() sql 查询但不起作用..,如何进行正确的查询?

PostgreSQL 版本:10.3

聚合两次。一次获取地点及其计数,然后再次列出列表...

SELECT
  t.uid,
  array_agg(array[t.place, t.row_count])
FROM
(
  SELECT
    uid,
    place,
    COUNT(*)   AS row_count
  FROM
    tour_tracking
  WHERE
    orderon::time BETWEEN '18:00:00' AND '20:00:00'
  GROUP BY
    uid,
    place
)
  t
GROUP BY
  t.uid