Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the longest string when using GROUP BY for multiple columns in Sql Server

I have below tables with duplicates values. i want to take only max length text from it.

+----+---------------------------------+-------------------+
| ID | Text                            | no                |
+----+---------------------------------+-------------------+
| 1  | lorem ipsum ipsum               | 8955\5445         |
+----+---------------------------------+-------------------+
| 1  | ipsum                           | 1879668\4554\4554 |
+----+---------------------------------+-------------------+
| 1  | lorem ipsum ipsum               | 5464              |
+----+---------------------------------+-------------------+
| 2  | lorem ipsum ipsum derome        | 13465465\54555\45 |
+----+---------------------------------+-------------------+
| 2  | lorem ipsum derome ipsum derome | 555454            |
+----+---------------------------------+-------------------+

My Query:

select id,MAX(text),MAX(no) from table1 group by id

Result:

    +----+--------------------------+-----------+
| id | Text                     | no        |
+----+--------------------------+-----------+
| 1  | lorem ipsum ipsum        | 8955\5445 |
+----+--------------------------+-----------+
| 2  | lorem ipsum ipsum derome | 555454    |
+----+--------------------------+-----------+

Expected Output:

   +----+--------------------------+-------------------+
| id | Text                     | no                |
+----+--------------------------+-------------------+
| 1  | lorem ipsum ipsum        | 1879668\4554\4554 |
+----+--------------------------+-------------------+
| 2  | lorem ipsum ipsum derome | 13465465\54555\45 |
+----+--------------------------+-------------------+
like image 319
irfan patel Avatar asked Oct 24 '25 15:10

irfan patel


1 Answers

You can do it by combining a RANK function with a CTE. Someting like this:

WITH cte AS (
SELECT 
  id
  ,text
  ,no
  ,RANK() OVER(PARTITION BY id ORDER BY LEN(text) DESC) AS pos
)
SELECT *
FROM cte
WHERE pos = 1
like image 165
Dave Sexton Avatar answered Oct 27 '25 05:10

Dave Sexton