问题
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