简体   繁体   中英

How Select top 2 values from each group in a table with SQL using this specific query

I have this query. It gives me multiple rows (1st col repeated) with its data on second and third columns.

Maybe I did something wrong on the query as it's a simple one with inner join.

Although I need the two top rows for each result row.

Tables: Jeans, Products

Jeans: CHG_I, JeanID, CHG_Date Products: CHG_I, Desc, Price

Query:

Select D.JeanID, P.Desc, P.Price
FROM Products P inner join Jeans D on D.CHG_I = P.CHGPI
Where D.CHG_Date=convert(date,sysdatetime())

This gives me this table:

+-----------------------+
¦ JeanID - Desc - Price ¦
¦-----------------------¦
¦ 3559 - 5234523 - 4.49 ¦
¦ 3559 - 6235523 - 4.49 ¦
¦ 3559 - 9823923 - 4.49 ¦
¦ 3559 - 0809833 - 3.99 ¦
¦ 3559 - 1231212 - 3.99 ¦
¦ 3552 - 2352354 - 3.99 ¦
¦ 3440 - 5235325 - 2.99 ¦
¦ 3440 - 5235233 - 2.99 ¦
¦ 3882 - 2352352 - 2.99 ¦
¦ 3990 - 2623532 - 3.99 ¦
+-----------------------+

I need to modify my query to get this:

+-----------------------+
¦ JeanID - Desc - Price ¦
¦-----------------------¦
¦ 3559 - 5234523 - 4.49 ¦
¦ 3559 - 6235523 - 4.49 ¦
¦ 3552 - 2352354 - 3.99 ¦
¦ 3440 - 5235325 - 2.99 ¦
¦ 3440 - 5235233 - 2.99 ¦
¦ 3882 - 2352352 - 2.99 ¦
¦ 3990 - 2623532 - 3.99 ¦
+-----------------------+

Been searching for a solution although I'm not able to get it when starting from this query. :(

;With Results
AS
 (
    Select D.JeanID, P.Desc
            , P.Price, rn = ROW_NUMBER() OVER (PARTITION BY D.JeanID ORDER BY P.Price DESC)
    FROM Products P inner join Jeans D 
    on D.CHG_I = P.CHGPI
    Where D.CHG_Date=convert(date,sysdatetime())
 )
SELECT JeanID, Desc, Price
FROM Results
WHERE rn <= 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM