大家好我有什麼似乎是一個簡單的問題(至少在我的頭上),但我還沒有能夠找到一個堅實的方式來解決這個查詢。向排行榜的續集查詢添加排名
下面是我正在運行的查詢來獲取我的應用程序的當前排行榜。我想也得到的回覆是項目位置/等級以及屬性就像我與贏,輸等等
SELECT "Item"."id",
(SELECT COUNT("Votes"."id") FROM "Votes" WHERE type = 'up' AND "Votes"."LunchId" = "Item"."id" AND "Votes"."scope" = 'regional')::INTEGER AS "wins",
(SELECT COUNT("Votes"."id") FROM "Votes" WHERE type = 'down' AND "Votes"."LunchId" = "Item"."id" AND "Votes"."scope" = 'regional')::INTEGER AS "loses",
(SELECT COALESCE((SELECT round(100.0*sum(CASE WHEN "Votes"."type" = 'up' AND "Votes"."scope" = 'regional' THEN 1 ELSE 0 END)/sum(1), 3) FROM "Votes" WHERE "Votes"."LunchId" = "Item"."id" AND "Votes"."scope" = 'regional'),0))::DECIMAL AS "percent",
(SELECT count(*) FROM "Lunches" WHERE date("Lunches"."createdAt") = (SELECT date("createdAt") FROM "Lunches" WHERE "Lunches"."id" = "Item"."id") AND "Lunches"."region" = "Item"."region")::INTEGER AS "total"
FROM "Lunches" AS "Item"
WHERE "Item"."region" = 'east'
AND "Item"."createdAt" BETWEEN '2015-06-15T011:30:00-04:00' AND '2015-06-15T16:00:00-04:00'
ORDER BY "percent" DESC, "wins" DESC, "Item"."createdAt" ASC;
我想這樣的格式是我希望能夠理由也可以通過使用AND「Item」,「id」= 40來輕鬆提出要求,並快速找到它的等級。這是可行的嗎?
謝謝!
------ UPDATE -------
這裏是我的表的模式:
CREATE TABLE "Lunches" (
id integer NOT NULL,
region "enum_Lunches_region" NOT NULL,
timezone character varying(255),
description character varying(255),
"regionWinner" boolean DEFAULT false,
"nationalWinner" boolean DEFAULT false,
type character varying(30) DEFAULT 'restaurant'::character varying,
"createdAt" timestamp with time zone NOT NULL,
"updatedAt" timestamp with time zone NOT NULL,
"LocationId" integer,
"UserId" integer,
"PhotoId" integer
);
CREATE TABLE "Votes" (
id integer NOT NULL,
type "enum_Votes_type",
scope "enum_Votes_scope" DEFAULT 'regional'::"enum_Votes_scope",
region "enum_Votes_region" NOT NULL,
"createdAt" timestamp with time zone NOT NULL,
"updatedAt" timestamp with time zone NOT NULL,
"LunchId" integer,
"UserId" integer,
"CompetitorId" integer
);
是否也能提供你的數據庫的架構? 例如,「CREATE TABLE Lunches ... CREATE TABLE Votes .. INSERT INTO Lunches ... INSERT INTO Votes」 – ChrisGuest
您使用的是哪個pg版本?還有爲什麼問題用mysql標記? –