如何依靠PostgreSQL中的array_agg指望一个组

时间:2018-05-17 16:02:57

标签: sql postgresql group-by count array-agg

这是我的SQL: <script type="text/javascript"> function GetSelectedValue() { var e = document.getElementById('Analitycs'); var eValue = e.options[e.selectedIndex].value; var div = document.getElementById('addedBody'); switch (eValue) { case "1": div.innerHTML += '<text><label>Контрагент</label><select class="selectpicker" data-live-search="true" data-size="7" asp-items="@(new SelectList(@Model.Partners, "Name", "Name"))" asp-for="FilterModel.PartnerName"><option value="">Выберите контрагента</option></select></text>' break } } </script>

原点结果:
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的每个DISTINCT位置。 希望的结果:

|---------------|----------------------| | uid | place | |---------------|----------------------| | a01 | {hk, hk, jp} | |---------------|----------------------| | a02 | {jp, jp, jp, jp, uk} | |---------------|----------------------|
我尝试结合一些 |---------------|--------------------------------------| | uid | place | |---------------|--------------------------------------| | a01 | something like this: {hk,2, jp,1} | |---------------|--------------------------------------| | a02 | {jp:4, uk:1} | |---------------|--------------------------------------| sql查询但是没有工作..,如何做正确的查询?

PostgreSQL版本:10.3

1 个答案:

答案 0 :(得分:2)

聚合两次。一旦获得地点和他们的计数,然后再次列出......

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