多行,其中一些具有相同的ID,以分隔列

时间:2018-06-27 22:59:29

标签: sql ms-access

在Access 2013中工作。我有一个如下所示的Excel文件:

ID  | Name  | Major   | Email
----+-------+---------+-----------------------
005 | Bobby | English | coolEmail@email.com
006 | Sarah | Math    | email@email.com
006 | Sarah | Science | email@email.com
007 | James | Art     | badEmail@email.com

我希望它最终像这样

ID  | Name  | Major 1 | Major 2 | Email
----+-------+---------+---------+----------------------
005 | Bobby | English | (blank) | coolEmail@email.com
006 | Sarah | Math    | Science | email@email.com
007 | James | Art     | (blank) | badEmail@email.com

有人知道我会怎么做吗?

我在这里进行的任何搜索都没有给我任何有用的信息。我尝试this无济于事。我不知道我在做什么:(

3 个答案:

答案 0 :(得分:2)

可能在其中存在一些次要的Access语法问题,但我认为这应该可行。您基本上需要一个“临时”源表或直接查询Excel的功能。

insert into <destination> (ID, Name "Major 1", "Major 2", Email)
select
    ID, min(Name), min(Major), iif(max(Major) <> min(Major), max(Major), null), min(Email)
from <source>
group by ID

答案 1 :(得分:0)

只需测试此查询,它看起来就可以满足您的要求。将TABLENAME替换为您将在MS Access中引用的表的名称。

SELECT
    m1.ID
    ,m1.Name
    ,m1.major AS [Major 1]
    ,m2.major AS [Major 2]
    ,m1.Email

FROM
    TABLENAME AS m1
LEFT JOIN
    (
        SELECT
            *
        FROM
            (
                SELECT 
                    *
                    ,(
                        SELECT COUNT(*) 
                        FROM TABLENAME AS x 
                        WHERE x.major > y.major AND x.id = y.id
                    ) + 1 as rank_nbr 
                FROM 
                    TABLENAME AS y
            )
        WHERE
            rank_nbr = 2
    ) AS m2 ON m2.id = m1.id

WHERE
    m2.major IS NULL OR (m1.major IS NOT NULL AND m2.major <> m1.major)

答案 2 :(得分:0)

假设您将Excel数据链接为链接表,请尝试以下操作:

Select
    ID,
    [Name],
    Min([Major]) As [Major 1],
    Max([Major]) As [Major 2],
    Email
From
    YourLinkedTable
Group By
    ID,
    [Name],
    Email

要显示空白,请像这样展开:

Select
    ID,
    [Name],
    Min([Major]) As [Major 1],
    IIf(Max([Major]) = Min([Major]), Null, Max([Major])) As [Major 2],
    Email
From
    YourLinkedTable
Group By
    ID,
    [Name],
    Email