在SQL中使用不同的条件两次获取相同的列

问题描述 投票:0回答:6

我想两次检索相同的列,但条件不同。

我的查询是这样的,但以下查询将检索两个不同的列。但我希望两次获得同一列,我怎样才能实现这一目标?

Select name from tbCustomer where ID in (select ID from tbOldCustomer where oldID= 1)
Select name from tbCustomer where ID in (select ID from tbOldCustomer where oldID= 2)

tbCustomer有两列: ID名称 1 aaa 2 bbb 3 ccc 4 ddd

tbOldCustomer有两列:

ID oldID 1 2 2 1 3 1 4 2 4 1

想得到名称,其中oldID在(1,2)中,输出应该是以下内容:

名称1 bbb aaa ccc ddd DDD

sql condition
6个回答
1
投票

我认为你可以通过使用简单的JOIN实现这一目标

Select name 
from tbCustomer tc 
inner join tbOldCustomer toc On toc.id = tc.id
where toc.oldID IN (1,2)

1
投票

使用存在

select t1.name 
from tbCustomer t1 
exists( select 1 from  tbOldCustomer t2  where  t1.id = t2.id
                                       and t2.oldid in (1,2)
        )

0
投票

你可以尝试使用conditional aggregationcase when expression

select max(case when oldID= 1 then name end) as name1,
       max(case when oldID= 2 then name end) as name2
from tbCustomer join tbOldCustomer on ID=oldID where oldid in (1,2)
group by oldid

0
投票

你得试试

Select tc.name, toc.name from tbCustomer tc inner join 
tbOldCustomer toc On toc.id = c.id where toc.oldID IN (1,2)

0
投票

请试试这个。

Select name from tbCustomer where ID in (select ID from tbOldCustomer where oldID IN(1,2))

要么

Select A.name from tbCustomer A
INNER JOIN tbOldCustomer  B
ON A.id = B.Id
AND B.OldId In (1,2)

0
投票

试试这个

SELECT  name 
FROM tbCustomer tb1 
JOIN (SELECT ID FROM tbOldCustomer WHERE oldID = 1 OR oldID= 2) tb2
     ON tb1.ID = tb2.ID
WHERE tb1.ID IN (SELCT ID from tbOldCustomer where oldID in (1, 2))
© www.soinside.com 2019 - 2024. All rights reserved.