简体   繁体   中英

SQL first occurrence of a string

I have a query which returns results like

  • Jim 456
  • Joe 567
  • Joe 789
  • Jane 456

What I want to do is have 456 only appear once and take the first name (Jim).

Query looks like

select 
     p.id_id as num_id, p.FIRST_NAME || ' ' ||  p.LAST_NAME as Name_
from DWH.V_TABLE p
where p.id_id > 100

The reasons for this is I need each to have only one owner, not two

select p.id_id as num_id,
   p.FIRST_NAME || ' ' ||  p.LAST_NAME as Name_
        from DWH.V_TABLE p
         where p.id_id>100
   LIMIT 1

Does that what you need? It will return only the first result. Also see SQL Limit

Based on the comments above The ask is now I just need one person to take ownership of each result so that they can work on an assigned task. It doesn't matter which of the id's owners it is

the following Query will meet that need.

select  p.id_id as num_id
        ,MIN(p.FIRST_NAME || ' ' ||  p.LAST_NAME) as Name_
from    DWH.V_TABLE p
where   p.id_id > 100
GROUP BY
        p.id_id

Assuming the "456" is the value stored in the id_id column, then this should do it:

select num_id, 
       name_
from (
      select p.id_id as num_id,  
             p.first_name || ' ' ||  p.last_name as name_
             row_number() over (partition by p.id_id order by p.FIRST_NAME || ' ' ||  p.LAST_NAME) as rn 
      from dwh.v_table p
      where p.id_id > 100 
) t
where rn = 1;

Based on the comments and the question
Presuming you have a date field to check the real owner, or you can filter the records based on their occurrence in anothertable, I'd say that if you just want to get rid of the duplicates for the ID, use the "distinct" keyword.

select distinct p.id_id as num_id, p.FIRST_NAME || ' ' ||  p.LAST_NAME as Name_
from DWH.V_TABLE p
where p.id_id > 100

You can also make a self join table (table join to self using p.id_id) and filter the results where "First".name<"Second".name, "First" and "Second" being the aliases of the same table output. (This is only for the case, if you have any sorting criteria base on alphabetical precedence)

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