简体   繁体   中英

select distinct but return other columns using ORACLE

I am trying to to do a select distinct on the 'url' field while pulling in the data for a few other fields. I tried the below but it gives me some error message 'missing expression'. I'm using ORACLE. Can anyone help me

SELECT distinct on url,
                is_aw_grp_id,
                is_aw_page_id,
                eppcm_contentid
  FROM ps_z_google_srch
 WHERE     url <> ' '
       AND EPPCM_CONT_TYPE = 'H'
       AND TO_CHAR (dttm_imported, 'dd-MON-yyyy HH:MM:SS') >=
              (SELECT TO_CHAR (LASTCHANGEDTTM, 'dd-MON-yyyy HH:MM:SS')
                 FROM PS_Z_CONT_LAST_CHG
                WHERE RECNAME = 'Z_GOOGLE_SRCH')

The 'on' is a keyword and is causing this error to be thrown; it's confusing the parser. It isn't needed or valid for distinct in Oracle (as I believe it is for PostgreSQL, so maybe other databases too), so remove that word:

SELECT distinct url,
                is_aw_grp_id,
                is_aw_page_id,
                eppcm_contentid
...

That will get all distinct combinations of those four fields. Assuming your URLs appear in multiple rows, if you only want to show each URL once then you'd need to decide which value you want for the other three fields - from all the rows for that URL - which could be done with aggregate or analytic functions, or a subquery, depending on the data and requirements.


Off-topic, but this looks odd:

TO_CHAR (dttm_imported, 'dd-MON-yyyy HH:MM:SS') >=
              (SELECT TO_CHAR (LASTCHANGEDTTM, 'dd-MON-yyyy HH:MM:SS')
...

You're converting two dates to strings, and then comparing them with string semantics; so '01-MAR-2015' would sort before '28-FEB-2015', as 1 comes before 2 in the character set. If you were going to compare as strings they should be in a form where comparison makes sense, like ISO format. But converting them both to strings doesn't make sense anyway, just compare them as dates:

dttm_imported >= (SELECT LASTCHANGEDTTM
...

You could also join the two tables rather than using a subquery.

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