简体   繁体   English

SQL查询-在不同条件下两次显示同一列

[英]SQL Query - Displaying the same column twice under different conditions

I am wondering if the following is possible. 我想知道以下情况是否可能。 Say I have the following table: 说我有下表:

ID | ID | NAME 名称
1 | 1 | John 约翰
2 | 2 | Bob 鲍勃
3 | 3 | John 约翰
4 | 4 | Bob 鲍勃


Is it possible to run a query that results in the following: 是否可以运行导致以下结果的查询:

NAME| NAME | ID1 | ID1 | ID2 ID2
John | 约翰| 1 | 1 | 3 3
Bob | 鲍勃| 2 | 2 | 4 4

EDIT 编辑

Sorry for the confusion. 对困惑感到抱歉。 My question addresses instances where I need to handle the possibility of 2 duplicates for a large data set. 我的问题针对的是我需要处理大型数据集重复2次的情况。

Assuming exactly 2 duplicates 假设正好有2个重复项

SELECT 
   NAME, 
   MIN(ID) as ID1,
   MAX(ID) as ID2
FROM Table t
GROUP BY NAME

This should work. 这应该工作。 Note that the subquery screens out all names that don't have exactly two id s. 请注意,子查询会筛选出所有不完全具有两个id的名称。

select name,min(id) as id1,max(id) as id2
from table
join(
    select name
    from table
    group by name
    having count(1)=2
)names
using(name)
group by name;

If there are exactly two rows with each name, then the following should work: 如果每个名称恰好有两行,则应执行以下操作:

 SELECT a.name,
        a.id as id1,
        b.id as id2
 FROM the_table a 
   JOIN the_table b ON a.name = b.name AND a.id <> b.id

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

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