简体   繁体   中英

SQL - how to retrieve unique value(nvarchar) in a join table?

I am trying to display all columns for two join table but only retrieve unique value from one of the columns (ie antsDescriptionCode ) which has a datatype of nvarchar .

Can anyone please help? Thanks.

My current query on allows me display all columns for two join table with some condition:

select c.*, a.* 
from cats c
join ants a on c.ctypeid = a.atypeid
where 
     (c.CatsNo like 'cat4%'
   or c.CatsNo like 'cat7%'
   or c.CatsNo like 'cat8%')
   and a.antsflagged = 0 
   and a.antsDescriptionCode in ('type a', 'type b', 'type  c')!

Refer to image for current get and expected output

I am using Microsoft SQL Server 2008.

Assuming you are using Microsoft SQL Server, you can do something like this:

select * from (
select 
    c.*, a.*,
    row_number() over (partition by a.antsDescriptionCode order by CatsNo) [row]
from cats c
join ants a on c.ctypeid = a.atypeid
where 
     (c.CatsNo like 'cat4%'
   or c.CatsNo like 'cat7%'
   or c.CatsNo like 'cat8%')
   and a.antsflagged = 0 
   and a.antsDescriptionCode in ('type a', 'type b', 'type  c')
) q where q.row=1

This will give you the first row (ordered by catsno ) for every distinct antsDescriptionCode .

It will also give you an extra column (called "row") of 1 values. To get rid of that, replace the first * with the actual list of columns.

Because you're joining on an arbitrary TypeID that is shared by multiple rows in both tables, you'll need to define your data further. What determines which of the many Ant rows is associated with that Cat besides its type? Do you only want to return the highest AntsID for a given type? Defining the relationship further will create for an easier, more robust solution. Without that defined, other answers to this question will certainly suffice.

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