This question already has answers here:
Get top 1 row of each group (19 answers)
SQL Query to select each row with max value per group (2 answers)
How to select a max row for each group in SQL (3 answers)
Closed 8 days ago.
I have a table "Article" [product in ENG] which contains as attributes (numArticle [PK], poids [weight in English], des_ [Designation], couleur [color]) and I want to select the designation of the products with highest weight from each color.
I tried this
SELECT des_
FROM Article
WHERE poids = ANY (SELECT MAX(poids) 'poidse'
FROM Article
GROUP BY couleur);
but didn't work and I didn't know why at first but figured it out later.
Simply put I want to assign to each weight of a product in subquery it's designation.
The subquery returns the highest weight of each color but doesn't give the designation since I can't use select designation without including it in GROUP BY
Clause because if I did that its gives unwanted result.
2条答案
按热度按时间qlckcl4x1#
You can use
ROW_NUMBER
to order the records for each color starting with the one with highest poids. Then,SELECT
only the first ones from each color usingTOP 1 WITH TIES
:fgw7neuy2#
My understanding of the question you raised is as follows:
select des_,max(weight),color from [table] gourp by color
SELECT couleur, MAX(poids) AS max_poids FROM Article GROUP BY couleur
to connect weight and colorSolution
PS:
In this query, the subquery uses GROUP BY to retrieve the maximum weight for each color and adds an alias to the maximum weight column using the AS keyword. Then, by using an INNER JOIN to connect the subquery result with the Article table, the desired Designation is retrieved by matching the color and weight.