简体   繁体   English

如何使用此特定查询使用SQL从表的每个组中选择前2个值

[英]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 牛仔裤:CHG_I,JeanID,CHG_Date产品:CHG_I,Desc,价格

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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