Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server TOP(1) with distinct

I am trying to extract the first row I get after ordering the result by i_version_id. If I do not use TOP(2), my query works as expected ans returns all results sorted by i_version_id. But when I add the TOP(2) (as shown below), it says that there is a syntax error near distinct. Please let me know what I am doing wrong.

SELECT TOP(2) 
    distinct(i_version_id) 
FROM 
    [PaymentGateway_2006].[dbo].[merchant] 
WHERE 
    dt_updated_datetime > '2013-11-11'
GROUP BY
    i_version_id 
ORDER BY 
    i_version_id;
like image 969
Darth.Vader Avatar asked Nov 20 '13 02:11

Darth.Vader


People also ask

What is a distinct top 10 in SQL Server?

Notice that the query “DISTINCT TOP 10” includes the first 10 rows from the query from the “DISTINCT” query. From this we know a DISTINCT list is first created, and then the TOP 10 items returned.

How do I perform a distinct query in SQL?

To do so, select Query -> Include Actual Query Plan from the menu before executing the query. The “Stream Aggregate” icon is for the DISTINCT operation and “Top” for the TOP 10 one. It may seem somewhat counterintuitive to see DISTINCT listed first within the SELECT statement.

How to use select distinctclause in SQL?

Introduction to SQL Server SELECT DISTINCTclause Sometimes, you may want to get only distinct values in a specified column of a table. To do this, you use the SELECT DISTINCTclause as follows: SELECTDISTINCTcolumn_name FROMtable_name; Code language:SQL (Structured Query Language)(sql) The query returns only distinct values in the specified column.

What is the difference between order by and distinct in SQL?

ORDER BY items must appear in the select list if SELECT DISTINCT is specified. Because of this you must keep in mind, when using ORDER BY, that the ORDER BY items must appear in the select list when using Distinct. Good post with great examples.


1 Answers

If you're only getting the TOP 1 then distinct is irrelevant. It's also irrelevant since grouping by the column will give you distinct values,

However, If you want more than one just remove the parentheses:

SELECT DISTINCT TOP(2) 
    i_version_id
FROM 
    [PaymentGateway_2006].[dbo].[merchant] 
WHERE 
    dt_updated_datetime > '2013-11-11'
GROUP BY
    i_version_id 
ORDER BY 
    i_version_id;
like image 139
D Stanley Avatar answered Oct 26 '22 17:10

D Stanley