postgreSQL在select语句中声明var if if语句

时间:2014-05-26 18:29:53

标签: sql postgresql window-functions

我有一个mySQL语句,我需要转换为postgreSQL但是当我在postgreSQL中运行以下SQL时,我得到错误:语法错误在或附近":="

从我发现的内容:=似乎是在postgreSQL中声明var的方法。

SELECT  memberid, conseq, displayname, foldername, apiloginid, countryid, members.email
            FROM    (   SELECT  MemberID,
                                Position,
                                CreateDat,
                                @r:=IF(@m = MemberID, @r + 1, 1) AS conseq,
                                @m:= MemberID
                        FROM    memberevents,
                                (SELECT @r:= 0) r,
                                (SELECT @m:= 0) m
                        where position=1        
                        group by eventid        
                        ORDER BY CreateDat DESC
                    ) t, members
            where members.id=t.memberid     
            ORDER BY Conseq DESC
            LIMIT 3;

1 个答案:

答案 0 :(得分:0)

不需要这样的黑客攻击,只需使用窗口函数:

SELECT  memberid, conseq, displayname, foldername, apiloginid, countryid, members.email
FROM (   
  SELECT  MemberID,
          Position,
          CreateDat,
          row_number() over (partition by memberID order by createDat) as AS conseq
  FROM  memberevents
  where position=1        
  group by eventid        
) t
  JOIN members ON members.id=t.memberid     
ORDER BY Conseq DESC
LIMIT 3;

我不确定派生表中的group by,但我不知道MySQL实际上如何在派生表中使用变量赋值。