3

这是我的 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} | |---------------|----------------------|

现在我想为每个分组的 uid 计算每个 DISTINCT 位置。希望的结果:

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

PostgreSQL 版本:10.3

4

1 回答 1

7

聚合两次。一次是为了获得地点和他们的人数,然后再一次是为了列出清单……

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
于 2018-05-17T16:10:37.557 回答