每个用户的SELECT行,包含当天的最新时间

时间:2017-02-22 15:50:22

标签: sql postgresql greatest-n-per-group

我能够从DB获取我需要的数据,除了我每个日期只需要一行,所以例如下图中应该只有第二行而不是第一行。我不知何故需要能够从一个日期为一个用户只获得一行。

SELECT id_user, date_created || ' ' || time_created as placed
            FROM (
                        SELECT
                        b_objednavky.uzivatel AS id_uzivatele,
                        b_objednavky.vytvoreno::date AS date_created,
                        to_char(b_objednavky.vytvoreno, 'HH24:MI:SS') as time_created,
                        b_objednavky.created

                    FROM b_objednavky
                    INNER JOIN u_uzivatele ON b_objednavky.uzivatel = (
                     SELECT u_uzivatele.id from u_uzivatele JOIN bw_paid_orders
                           ON u_uzivatele.id = bw_paid_orders.user_id 
                     WHERE bw_paid_orders.active_thru < NOW() + interval '6 months'
                     ) uzivatele
                    INNER JOIN bc_stavy_objednavky ON b_objednavky.stav = bc_stavy_objednavky.id

                    WHERE bc_stavy_objednavky.sysid = 'nova' AND b_objednavky.vytvoreno <= NOW()
                    AND bc_staty.kod NOT IN (
                      'BR', 'CL', 'AR', 'MX'
                    )

                ) AS order
                 LEFT OUTER JOIN (
                  SELECT user_id, max(paid) as last_paid FROM bw_paid_orders
                GROUP BY user_id
                ) last_paid_by_user ON (id_user = user_id) 
                WHERE (created > last_paid OR last_paid IS NULL) AND created BETWEEN ('2017-02' || '-01')::date
            AND ('2017-02' || '-01')::DATE + '1 month'::interval 
            ORDER BY datum_objednani DESC, objednavajici, nazev, duration

1 个答案:

答案 0 :(得分:2)

使用Python

  

从一个日期为一个用户只获取一行

DISTINCT ON

要获取当天最新时间的行,请添加(在相同的查询级别):

SELECT DISTINCT ON (id_user, date_created) ...

详细说明: