SQL Server Why alias in SQL is not remember a subquery as a new table? [duplicate]

sy5wg1nm  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(136)

This question already has answers here:

Create a view with ORDER BY clause (10 answers)
Order BY is not supported in view in sql server (3 answers)

How to sort within a sql view (4 answers)
Order by error in create view in SQL Server (2 answers)

Does order by in view guarantee order of select? (3 answers)
Closed 11 months ago.

I have a table SALE with 2 columns ID and Sales .

I have code like this:

SELECT TOP 100 PERCENT ID, Sales
FROM SALE
WHERE ProductID = 'IDN001'
ORDER BY Sales DESC;

And the result is here:

But if I put all the code above inside the SELECT * FROM , it shows me the original TABLE (before ordering):

SELECT *
FROM
    (SELECT TOP 100 PERCENT ID, Sales
     FROM SALE
     WHERE ProductID = 'IDN001'
     ORDER BY Sales DESC) AS NewQuery;

The new result is here:

How can I fix this?

Thank you.

3pvhb19x

3pvhb19x1#

The ordering of a subquery does not "stick" in a SQL Server query. You need to add an explicit ORDER BY clause to the outer query to get the sorting behavior you want:

SELECT *
FROM
(
    SELECT TOP 100 PERCENT ID, Sales
    FROM SALE
    WHERE ProductID = 'IDN001'
    ORDER BY Sales DESC
) AS NewQuery
ORDER BY Sales DESC;

相关问题