DISTINCT SQL命令

时间:2016-02-27 18:00:36

标签: sql

更新

qid = 1, nick=aa, value=13, time= 20:00:01
qid = 1, nick=bb, value=45, time= 20:00:50
qid = 2, nick=cc, value=77, time= 20:30:50

expected:
qid = 1, nick=bb, value=45, time= 20:00:50
qid = 2, nick=cc, value=77, time= 20:30:50

我试图执行这一行:

SELECT DISTINCT QID FROM "USERNAME"."ANSWER" WHERE Nickname =? ORDER BY Time DESC
OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY

我收到此错误消息:

  

自查询以来,ORDER BY子句可能不包含列' TIME'   指定DISTINCT,该列不会出现在查询中   结果

会出现什么问题?

3 个答案:

答案 0 :(得分:2)

如错误消息中所述,distinct

中的列不存在时,您无法使用Order by选择列表中的列
select * from 
(
select row_number()over(partition by qid Order by Time desc) as Rn,*
From yourtable
) A
Where RN =1 

或者如果您的数据库不支持ROW_NUMBER,请使用此

SELECT a.* 
FROM   yourtable a 
       INNER JOIN (SELECT qid, 
                          Max(time) AS time 
                   FROM   yourtable 
                   GROUP  BY qid) b 
               ON a.qid = b.qid 
                  AND a.time = b.time 

答案 1 :(得分:1)

根据您的要求,您不需要DISTINCT,只需要显示没有新行且具有相同QID的行;

SELECT * FROM answer
WHERE NOT EXISTS (
  SELECT 1 FROM answer a
  WHERE answer.qid = a.qid 
    AND answer.time < a.time
)

An SQLfiddle to test with

答案 2 :(得分:0)

也许可以帮助你THIS LINK

如果您想使用订单和不同的使用组。