1

我有两张桌子:

create table sales (
    unitcode int ,
    categorycode smallint ,
    ddate varchar(10) ,
    price float
)

create table timetable (
    year varchar(4) ,
    month varchar(11) ,
    ddate varchar(10)
)

我想写一个子查询来查找:在每年的每个月中,哪 2 个产品(unitcode,categorycode)的价格最高?

4

1 回答 1

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
于 2012-10-30T18:56:13.157 回答