语法错误附近(

时间:2016-04-12 11:24:34

标签: mysql

我正在尝试查询一些东西而且我对Mysql不太好,所以我想知道是否有人可以告诉我这里的问题是什么。这是我的表:

 create table #transfers (
     sender varchar not null,
     recipient varchar not null,
          date date not null,
          amount integer not null
      );


INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Smith','Williams','2000-01-01',200);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Smith','Taylor','2002-09-27',1024);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Smith','Johnson','2005-06-26',512);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Williams','Johnson','2010-12-17',100);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Williams','Johnson','2004-03-22',10);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Brown','Johnson','2013-03-20',500);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Johnson','Williams','2007-06-02',400);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Johnson','Williams','2005-06-26',400);
INSERT INTO #transfers(sender,recipient,date,amount) VALUES ('Johnson','Williams','2005-06-26',200);

这是查询:

WITH cte AS
(
  SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY recipient ORDER BY amount DESC)
  FROM #transfers
)
SELECT recipient
FROM cte
WHERE rn <= 3
GROUP BY recipient
HAVING SUM(amount) >= 1024
ORDER BY recipient

但是我收到了这个错误:

near“(”:语法错误

2 个答案:

答案 0 :(得分:1)

MySQL中没有

CTEsROW_NUMBER

尝试使用子查询:

SELECT recipient
FROM 
(
     SELECT t.*, @rownum := @rownum + 1 AS rank
     FROM #transfers t, (SELECT @rownum := 0) r
)X
WHERE rank <= 3
GROUP BY recipient
HAVING SUM(amount) >= 1024
ORDER BY recipient

Fiddle Demo

答案 1 :(得分:1)

使用此创建表查询

{{1}}