使用每周日期对用户进行排名并列出所有排名第一的用户

时间:2015-07-29 13:56:56

标签: sql postgresql aggregate-functions greatest-n-per-group window-functions

我有一张名为优惠券的桌子,图表如下:

CREATE TABLE "public"."coupons" (
   "id" int4 NOT NULL,
    "suprise" bool NOT NULL DEFAULT false,
    "user_id" int4 NOT NULL,
    "start" timestamp NOT NULL,
    "win_price" numeric(8,2) NOT NULL DEFAULT 0::numeric,
    "fold" int4 NOT NULL DEFAULT 3,
    "pay" numeric(8,2) NOT NULL DEFAULT 0::numeric,
    "rate" numeric(8,2) NOT NULL DEFAULT 0::numeric,
    "win" varchar(255) NOT NULL DEFAULT 'H'::character varying COLLATE "default",
    "end" timestamp NOT NULL,
    "win_count" int4 NOT NULL DEFAULT 0,
    "match_count" int4 NOT NULL DEFAULT 0,
    "played" bool NOT NULL DEFAULT false,
    "created_at" timestamp NOT NULL,
    "updated_at" timestamp NOT NULL
)
WITH (OIDS=FALSE);

要对用户进行排名win_price weekly我在下面写了一个查询,以便在2015年7月27日到2015年3月3日之间获得前5名:

SELECT ROW_NUMBER() OVER(ORDER BY sum(win_price) DESC) AS rnk,
       sum(win_price) AS win_price, user_id,
       min(created_at) min_create
FROM coupons
WHERE played = true AND win = 'Y'
AND created_at BETWEEN '27-07-2015' AND '03-08-2015'
GROUP BY user_id
ORDER BY rnk ASC
LIMIT 5;

我正在寻找一个新的查询,该查询列出了每周但在给定日期期间的第一个排名用户基础 即:2015年1月1日至2015年3月30日期间:

rnk - win_price - user_id - min_create  
 1  - 1.52      - 1       - ...........  (first week)
 1  - 10.92     - 2       - ...........  (send week)
 1  - 11.23     - 1       - ...........  (third week and so on)

1 个答案:

答案 0 :(得分:3)

SELECT *
FROM  (
   SELECT date_trunc('week', created_at) AS week
        , rank() OVER (PARTITION BY date_trunc('week', created_at)
                       ORDER BY sum(win_price) DESC NULLS LAST) AS rnk
        , sum(win_price) AS win_price
        , user_id
        , min(created_at) min_create
   FROM   coupons
   WHERE  played = true
   AND    win = 'Y' AND created_at BETWEEN '27-07-2015' AND '03-08-2015'
   GROUP  BY 1, 4  -- reference to 1st & 4th column
   ) sub
WHERE  rnk = 1
ORDER  BY week;

这会返回获胜用户每周 - 具有最高sum(win_price)的用户。

请注意,我使用rank() instead of row_number(),因为您没有为每周多个获胜者定义决胜局。

还要注意sort子句DESC NULLS LAST:这会阻止NULL值排序(如果你应该有NULL):

本周由开始时间戳表示,您可以使用to_char()以任何方式格式化。

查询的关键元素:您可以使用窗口函数而不是聚合函数。详细说明:

考虑SELECT查询中的事件序列: