Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL getting first full row matching each result in subquery

Tags:

sql

subquery

So the question is this. I have a table with n columns of data, but I want to list one row for each unique set of 3 columns.

For example, say the table is structured as below

ID | data1 | data2 | data3 | description | price | handler | creationTime | etc...

What I'm trying to do, is to use this subquery:

SELECT distinct data1, data2, data3 FROM Table_1

... to get each unique variation for the 3 columns. But then I want to select ONE full row from the table for each such result.

This query is meant for rather heavy use and needs to be optimized, which is kind of why I can't use table variables or while loops. Any hints?

like image 508
Kahn Avatar asked Mar 06 '26 00:03

Kahn


1 Answers

if you are using SQL Server, you can do this with a common table expression:

with minRow(ID) as 
    (select min(ID)
    from    Table_1
    group by data1, data2, data3)
select  t1.*
from    Table_1 t1 join minRow m1 on t1.ID = m1.ID
like image 57
paul Avatar answered Mar 07 '26 16:03

paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!