Поэтому мне нужно создать ВИД, чтобы найти пятерку самых дорогих продуктов в каждой цветовой категории.
Я знаю, что нужно создать ВИД, и я понял, как найти 5 лучших для каждой цветовой группы отдельно, используя «SELECT TOP 5» в начале и «GROUP BY DESC» в конце запроса.
то, с чем я борюсь, - это поместить пятерку лучших по всем параметрам «Color» в одну и ту же таблицу.
ниже мой код и ошибка, которую я получаю:
create view
as
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Black'
order by [ListPrice] desc
union ALL
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Blue'
order by [ListPrice] desc
union ALL
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Grey'
order by [ListPrice] desc
union ALL
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Multi'
order by [ListPrice] desc
union ALL
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Red'
order by [ListPrice] desc
union ALL
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Silver'
order by [ListPrice] desc
union ALL
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Silver/Black'
order by [ListPrice] desc
union all
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'White'
order by [ListPrice] desc
union all
select top 5
[ProductID]
,[Color]
,[ListPrice]
from [Production].[Product]
where [Color] = 'Yellow'
order by [ListPrice] desc
go
код ошибки: (обратите внимание, что я еще не запускал часть создания представления, а только запрос)
Msg 156, Level 15, State 1, Line 303
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 312
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 321
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 330
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 339
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 348
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 357
Incorrect syntax near the keyword 'union'.
Msg 156, Level 15, State 1, Line 366
Incorrect syntax near the keyword 'union'.





Вам не нужен союз. Просто выберите из своей таблицы и используйте оконную функцию, например ROW_NUMBER, чтобы получить рейтинг для текущего цвета:
;with cte as (
select
[ProductID]
, [Color]
, [ListPrice]
, ROW_NUMBER() over(PARTITION BY [Color] ORDER BY [ListPrice] desc) as RowNo
from [Production].[Product]
)
select *
from cte
where RowNo <= 5
ОБНОВЛЕНИЕ: если есть продукты с одинаковой ценой, и вы хотите включить их все (т.е. чтобы какой-то цвет возвращал более 5 строк), используйте DENSE_RANK вместо ROW_NUMBER.
Вы получаете сообщение об ошибке, потому что у вас может быть только один
ORDER BY