创建一个视图以查找所有颜色类别中最昂贵的5件商品

时间:2018-11-26 13:01:05

标签: sql-server

所以我必须创建一个VIEW来查找每种颜色类别中最贵的前五种产品。

我知道必须创建一个VIEW,并且已经弄清楚如何使用查询的开头“ SELECT TOP 5”和查询结束的“ GROUP BY DESC”分别找到每个颜色组的前5个。

我正在努力的是将所有“颜色”的前五名放在同一张表中。

下面是我的代码和我得到的错误:

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

错误代码:(请注意,我没有运行create view部分,而只是运行查询)

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

1 个答案:

答案 0 :(得分:2)

您不需要工会。只需从表中选择并使用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。