SQL Server TOP(1) with distinct

只谈情不闲聊 提交于 2019-12-04 10:45:26
D Stanley

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;

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).

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