我试图显示两个连接表的所有列,但仅从其中一个数据类型为nvarchar的列(即antsDescriptionCode)中检索唯一值。
有人能帮帮忙吗?谢谢。
我当前的查询on允许我显示符合以下条件的两个连接表的所有列:
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
我使用的是Microsoft SQL Server 2008。
发布于 2012-08-15 13:34:11
假设您使用的是Microsoft SQL Server,则可以执行以下操作:
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这将为每个不同的antsDescriptionCode提供第一行(按catsno排序)。
它还将为您提供一个额外的列(称为“行”)的1值。要消除这种情况,请将第一个*替换为实际的列列表。
发布于 2012-08-15 13:39:01
由于您连接的是由两个表中的多个行共享的任意TypeID,因此需要进一步定义数据。除了类型之外,是什么决定了许多Ant行中的哪一行与该Cat相关联?是否只想返回给定类型的最高AntsID?进一步定义关系将创建更简单、更健壮的解决方案。在没有定义的情况下,这个问题的其他答案肯定就足够了。
https://stackoverflow.com/questions/11963611
复制相似问题