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 |
+----+--------------------------+-------------------+
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With