2015-06-16 21 views
0

大家好我有什么似乎是一个简单的问题(至少在我的头上),但我还没有能够找到一个坚实的方式来解决这个查询。向排行榜的续集查询添加排名

下面是我正在运行的查询来获取我的应用程序的当前排行榜。我想也得到的回复是项目位置/等级以及属性就像我与赢,输等等

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 
); 
+1

是否也能提供你的数据库的架构? 例如,“CREATE TABLE Lunches ... CREATE TABLE Votes .. INSERT INTO Lunches ... INSERT INTO Votes” – ChrisGuest

+0

您使用的是哪个pg版本?还有为什么问题用mysql标记? –

回答

0

你可能会想rank()功能,具有某种窗口沿/划分。看看http://www.postgresql.org/docs/9.4/static/tutorial-window.html

你也许可以添加

rank() over (order by percent DESC, wins DESC, item.createdAt ASC) 

在查询一栏,让你在找什么。

您可能还可以使用Common Table Expressions轻松查看您的查询; http://www.postgresql.org/docs/9.4/static/queries-with.html

例如:

WITH vote_summary AS (
select votes.LunchId, sum((type='up')::int) as wins, 
     sum((type='down')::int) as losses 
    from votes 
where votes.scope = 'regional' 
group by votes.LunchId 
) 
... 

可以为您节省了一大堆子查询的

+0

我试图在我的例子中包含排名,但没有运气,因为胜利栏目还没有出现。你能否进一步解释你的例子? – corbanb