简体   繁体   English

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

[英]Get same column twice with different conditions in SQL

I would like to retrive same columns twice but with different conditions. 我想两次检索相同的列,但条件不同。

my Query is like this but the following Query retrives two different columns. 我的查询是这样的,但以下查询检索两个不同的列。 But I want to get the same column twice, How can I achieve this? 但是我想两次获得同一列,如何实现呢?

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 has two columns: tbCustomer有两列:
ID name 身份证
1 aaa 1 aaa
2 bbb 2桶
3 ccc 3 cc
4 ddd 4天

tbOldCustomer has two columns: tbOldCustomer有两列:

ID oldID 编号 oldID
1 2 1 2
2 1 2 1
3 1 3 1
4 2 4 2
4 1 4 1

would like to get name where oldID in (1, 2) and the output should be the follwing: 想要获取(1,2)中oldID的名称,并且输出应为以下内容:

name name1 名称 name1
bbb aaa bbb aaa
ccc ddd ccddd
ddd ddd

use exists 存在使用

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

I think you can achieve that by using simply JOIN 我认为您可以通过简单地使用JOIN来实现

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

you can try using conditional aggregation with case when expression 您可以尝试case when expression使用conditional aggregation

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

You have to try 你得试试

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

Please try this. 请尝试这个。

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

OR 要么

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

Try this 尝试这个

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM