SQL Server TOP(1) with distinct

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-23 01:16:27

问题


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;

回答1:


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;



回答2:


Would this work?

SELECT
*
FROM
(
SELECT i_version_id,
    ROW_NUMBER() OVER (PARTITION BY i_version_id ASC) [counter]
FROM 
    [PaymentGateway_2006].[dbo].[merchant] 
WHERE 
    dt_updated_datetime > '2013-11-11'
GROUP BY
    i_version_id 
ORDER BY 
    i_version_id
) a
WHERE [counter] <= 2

This will give a row counter for each record. Using GROUP BY and DISTINCT in your example above is pointless as your GROUP BY is already restricting your records. Putting in the DISTINCT is just going to effect performance.

As for your error, you can't use TOP and DISTINCT together AFAIK. You could try this if you wanted too:

SELECT
TOP 2 i_version_id
FROM
(
SELECT 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
) a

(I haven't tested this as I don't have your Db, but I can't see why this wouldn't do what you need).



来源:https://stackoverflow.com/questions/20086243/sql-server-top1-with-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!