3

Update:

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

i trying to execute this line:

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

And I get this error msg:

The ORDER BY clause may not contain column 'TIME', since the query specifies DISTINCT and that column does not appear in the query result.

What would be the problem?

user11001
  • 372
  • 3
  • 14

3 Answers3

2

As stated in error message you cannot use columns in distinct select list when the column is not present in Order by

select * from 
(
select row_number()over(partition by qid Order by Time desc) as Rn,*
From yourtable
) A
Where RN =1 

Or If your database does not support ROW_NUMBER then use this

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 
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
1

For your requirement you don't need DISTINCT, you just need to show rows where there exists no newer row with the same 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.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

Maybe can help you THIS LINK

If you want use order and distinct use group by.

Community
  • 1
  • 1
starko
  • 1,150
  • 11
  • 26