嗨,如果对此的答案是在其他地方我很抱歉。我环顾四周,看不出简单的解决方案。我有一个想要运行的查询。我不关心联合集的顺序,只是内部查询返回正确的数据,这是“最大的区域”。
(SELECT TOP 5 * FROM [geo].[Areas] WHERE CountryID = @CountryID AND (TypeID = 'City')
ORDER BY [ShapeArea] DESC) as BiggestCities
UNION ALL
(SELECT TOP 5 * FROM [geo].[Areas] WHERE CountryID = @CountryID AND (TypeID = 'National park')
ORDER BY [ShapeArea] DESC) as BiggestParks
但是T-sql不会让我对子查询有ORDER BY,只对整个联盟...帮助赞赏!我真的不想创建临时表或类似的东西。
答案 0 :(得分:29)
试试这个
SELECT *
FROM (SELECT TOP 5 *
FROM [geo].[Areas]
WHERE CountryID = @CountryID
AND (TypeID = 'City')
ORDER BY [ShapeArea] DESC) as BiggestCities
UNION ALL
SELECT *
FROM (SELECT TOP 5 *
FROM [geo].[Areas]
WHERE CountryID = @CountryID
AND (TypeID = 'National park')
ORDER BY [ShapeArea] DESC) as BiggestParks
答案 1 :(得分:2)
SELECT t.* /* Excluding RowNum */
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY TypeID ORDER BY [ShapeArea] DESC) as RowNum
FROM [geo].[Areas]
WHERE CountryID = @CountryID
AND TypeID IN ('City', 'National park')
) t
WHERE t.RowNum <= 5