简体   繁体   中英

Distinct records by column value

Let's say I have a query which its output is the given table:

Number    Data   Info
123    data1   info1
456    data2   info2
789    data3   info3
123    data4   info4

I want to get the same table with the columns, but without records which their Number column was gotten(Not the best phrasing there, sorry) . So its like a distinct.

It does not matter for me which record with the Number I keep in the result.

So the output I am looking for is:

 Number    Data   Info
    123    data1   info1
    456    data2   info2
    789    data3   info3

I am using oracle sql.

Thanks in advance!

You can change the aggregate function from MAX to others to get different values for Data and Info

SELECT Number, Max(Data) AS Data, Max(Info) as Info
FROM Table
GROUP BY Number

FIRST() might make sense for you. Here is the oracle docs on aggregate functions: https://docs.oracle.com/database/121/SQLRF/functions003.htm#SQLRF20035

GROUPING would fetch you either MAX() or MIN() .. but If you want the entire row, you have to use the below Analytical Approach. Which generates a sequence for every NUMBER. When there is 2 NUMBERs of same value, it generates seq, 1 ..2

So, by selecting 1 always, you get what you. The priority of row to be chosen has to be explicitly provided.

SELECT NUMBER,DATA,INFO
FROM
(
   SELECT NUMBER,DATA,INFO,ROW_NUMBER() OVER(PARTITION BY  NUMBER ORDER BY <ordering column>) identifier
   FROM YOUR_TABLE
)
WHERE identifier = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM