SQL Server Selecting results from subquery [duplicate]

db2dz4w8  于 2023-04-19  发布在  其他
关注(0)|答案(2)|浏览(99)

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.

qlckcl4x

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 using TOP 1 WITH TIES :

SELECT TOP 1 WITH TIES 
        numArticle,
        poids,
        des_,
        couleur
FROM Article
ORDER BY ROW_NUMBER() OVER (PARTITION BY couleur ORDER BY poids DESC)
fgw7neuy

fgw7neuy2#

My understanding of the question you raised is as follows:

  • you want to group by color and MAX in weight at the same time,but you can't do like this select des_,max(weight),color from [table] gourp by color
  • so you need construct a subquery like this SELECT couleur, MAX(poids) AS max_poids FROM Article GROUP BY couleur to connect weight and color
  • You can use a join to solve this problem. Specifically, you can use an inner join to join the Article table with the subquery that groups by maximum weight and color, and retrieve the desired result by using the maximum weight of each color from the subquery and the corresponding designation from the article table.

Solution

SELECT Article.des_
FROM Article
INNER JOIN (
    SELECT couleur, MAX(poids) AS max_poids
    FROM Article
    GROUP BY couleur
) AS max_poids_coul
ON Article.couleur = max_poids_coul.couleur AND Article.poids = max_poids_coul.max_poids;

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.

相关问题