SQL Server How to query the last 5 records? [duplicate]

pbpqsu0x  于 2023-06-28  发布在  其他
关注(0)|答案(2)|浏览(153)

This question already has answers here:

How to write a (MySQL) "LIMIT" in SQL Server? (3 answers)
Closed 6 days ago.

create a sql query to display the last 5 records of the Sdelki table by Users.ID_user the Users table is linked to the Clients table by ID_User, and the Klients table is linked to the Sdelki table by ID_Klient

this query didn't work

SELECT Sdelki.*
FROM Sdelki
INNER JOIN Klients
ON Sdelki.ID_Klient = Klients.ID_Klient
INNER JOIN Users
ON Klients.ID_user = Users.ID_user
ORDER BY Sdelki.ID_sdelki DESC
LIMIT 5;

using SQL Server

eoigrqb6

eoigrqb61#

Sql Server doesn't use LIMIT , it uses TOP instead :

SELECT TOP (5) Sdelki.*
FROM Sdelki
INNER JOIN Klients
ON Sdelki.ID_Klient = Klients.ID_Klient
INNER JOIN Users
ON Klients.ID_user = Users.ID_user
ORDER BY Sdelki.ID_sdelki DESC
juud5qan

juud5qan2#

You need to use Klients.ID_user or Users.ID_user in order by clause to get the expected results.

SELECT
    TOP 5 Sdelki.*
FROM 
    Sdelki
INNER JOIN 
    Klients
ON 
    Sdelki.ID_Klient = Klients.ID_Klient
INNER JOIN 
    Users
ON 
    Klients.ID_user = Users.ID_user
ORDER BY 
    Klients.ID_user DESC;

This is the updated query

EDIT: removed LIMIT 5 and used TOP 5 in the query, since LIMIT isn't supported in SQL Server.

相关问题