【发布时间】:2015-10-20 13:27:33
【问题描述】:
我有一个名为 coupons 的表,其架构如下:
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 的用户进行排名,我编写了下面的查询以获得 27-07-2015 和 03-08-2015 之间的前 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 月 9 日至 2015 年 9 月 30 日期间:
【问题讨论】:
标签: sql postgresql aggregate-functions greatest-n-per-group window-functions