sql server中的子查询

时间:2012-10-30 07:35:22

标签: sql-server-2008

我有两张桌子:

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

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

我想写一个子查询来查找:  在每年的每个月,哪两种产品(单位代码,类别代码)具有最高价格?

1 个答案:

答案 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