我有两张桌子:
create table sales (
unitcode int ,
categorycode smallint ,
ddate varchar(10) ,
price float
)
和
create table timetable (
year varchar(4) ,
month varchar(11) ,
ddate varchar(10)
)
我想写一个子查询来查找: 在每年的每个月,哪两种产品(单位代码,类别代码)具有最高价格?
答案 0 :(得分:0)
试试这个
;WITH cte AS (
SELECT unitcode,categorycode,t.ddate,price,ROW_NUMBER() OVER (PARTITION BY t.[year],t.[month] ORDER BY price desc) AS price_order,t.[year],t.[month]
FROM sales s
INNER JOIN timetable t
ON t.ddate = s.ddate
)
SELECT *
FROM cte
WHERE price_order <= 2
ORDER BY [year] ASC,[month] ASC,price DESC