【问题标题】:PostgreSQL array_agg but with stop conditionPostgreSQL array_agg 但有停止条件
【发布时间】:2018-11-07 07:17:38
【问题描述】:

我有一个包含孩子记录的表格,我想按月降序获取逗号分隔的结果,但每个月的孩子状态都有一个中断条件。如果状态为 0 将其推送到数组,但如果状态为 1 则不要将其推送并打破它,也不要检查前几个月的记录。

表格

所需的输出:

我已经尝试过这种方式,这给了我几个月的时间。但我不知道如何在 status = 1 条件下为每个孩子打破它

SELECT name, ARRAY_AGG(month ORDER BY month DESC)
FROM children
GROUP BY name

【问题讨论】:

    标签: sql postgresql select gaps-and-islands array-agg


    【解决方案1】:

    我认为这是:

    SELECT name, ARRAY_AGG(month ORDER BY month DESC)
    FROM (SELECT c.*,
                 MAX(c.month) FILTER (c.status = 1) OVER (PARTITION BY c.name) as last_1_month
          FROM children c
         ) c
    WHERE month > last_1_month 
    GROUP BY name;
    

    这个逻辑只是获取status = 1 所在的最后一个月,然后选择后面的所有月份。

    如果月份实际上是连续的,没有间隔,那么您可以这样做:

    SELECT name,
           ARRAY_AGG(month ORDER BY month DESC)[1:MAX(month) - MAX(month) FILTER (c.status = 1)]
    FROM children c
    GROUP BY name;
    

    【讨论】:

      【解决方案2】:

      我会使用不存在的条件来过滤掉你不想要的记录:

      SELECT   name, ARRAY_AGG(month ORDER BY month DESC)
      FROM     children a
      WHERE    NOT EXISTS (SELECT *
                           FROM   children b
                           WHERE  a.name = b.name AND b.status = 1 and a.month <= b.month)
      GROUP BY name
      

      【讨论】:

        猜你喜欢
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        相关资源
        最近更新 更多