Question: I have the following query which gets the sum of defect quantity per Defect Type :

```
SELECT 
[Defect Type]
,YEAR([Date]) AS YearOfDefect
,SUM([Total Defect Qty]) AS [Sum] FROM SupplierQuality
GROUP BY [Defect Type],YEAR([Date])

```

This is the result :

[![enter image description here](https://i.stack.imgur.com/PNbtp.png)](https://i.stack.imgur.com/PNbtp.png)

I want to have the defect type with the maximum sum of total defect quantity like below :

```
DefectType  YearOfDefect Sum    
No Impact   2019         586780230
No Impact   2018         437989564

```

Answer: 
A simple option uses `with ties`:

```
SELECT TOP (1) WITH TIES
    [Defect Type],
    YEAR([Date]) AS YearOfDefect,
    SUM([Total Defect Qty]) AS [Sum] 
FROM SupplierQuality
GROUP BY [Defect Type], YEAR([Date])
ORDER BY RANK() OVER(PARTITION BY YEAR([Date]) ORDER BY SUM([Total Defect Qty]) DESC)

```

The downside is that this does not let you control the ordering of the resultset. If you really need that feature, then use a subquery:

```
SELECT *
FROM (
    SELECT
        [Defect Type],
        YEAR([Date]) AS YearOfDefect,
        SUM([Total Defect Qty]) AS [Sum],
         RANK() OVER(PARTITION BY YEAR([Date]) ORDER BY SUM([Total Defect Qty]) DESC) rn
    FROM SupplierQuality
    GROUP BY [Defect Type], YEAR([Date])
) t
WHERE rn = 1
ORDER BY YearOfDefect

```
Making the assumption I make in the comments, and this is per year, then you can use `ROW_NUMBER` to get the "top" row per group:

```sql
WITH CTE AS(
    SELECT [Defect Type],
           YEAR([Date]) AS YearOfDefect,
           SUM([Total Defect Qty]) AS [Sum]
    FROM SupplierQuality
    GROUP BY [Defect Type],
             YEAR([Date]))
SELECT TOP (1) WITH TIES
       [Defect Type],
       YearOfDefect,
       [Sum]
FROM CTE
ORDER BY ROW_NUMBER() OVER (PARTITION BY YearOfDefect ORDER BY [Sum] DESC);

```