简体   繁体   中英

Select all columns with 1 being distinct

Alright, so I have a table with the following columns

| id | release_id | publish_date | category | title |

Based on this structure, a release can have multiple categories , which gives it a new line in the table. One of my page views lists the latest x releases (all categories). When I run a query like so:

select * 
from (select * 
      from TABLE 
      order by PUBLISH_DATE DESC) 
where rownum <= 10

If one of the latest, 10 in this case, releases has multiple categories, it'll returned twice, so I'm trying to add either UNIQUE or DISTINCT (or any other proper way) so that the RELEASE_ID is different for row returned.

When I run select DISTINCT RELEASE_ID , only that column is returned, but I still need the data from the other columns . Any help is appreciated.

Since oracle supports ROW_NUMBER() and window functions, try the following if it suits your needs.

SELECT id, release_id, publish_date, category, title
FROM
(
    SELECT  id, release_id, publish_date, category, title,
            ROW_NUMBER() OVER
           (PARTITION BY category ORDER BY Publish_DATE DESC) rn
    FROM tableName
) x
WHERE rn = 1

How about

select * from TABLE 
where release_id in (select release_id from 
                      (select distinct(release_id) from TABLE order by PUBLISH_DATE DESC)
                      where rownum <= 10)

You cannot do this, Because relese_id has 1 to many relationship with category. If you want distinct release_id , how can you get “other columns” data ? (like category.) You only can do aggregate functions operating on any other columns.

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