MS-Access查询合并行

时间:2019-06-06 07:05:44

标签: sql ms-access

我希望查询将满足以下条件的两行中的每行合并到一个大表中:

  1. SurnameNameFatherName是重复的
  2. 12在其中一行中包含“ ---”,而34在另一行中包含“ ---”

示例数据:

Surname  Name   FatherName  Phone  Mobile   1     2     3     4
Smith    Alex   Nick        12345  00000   xxx   zzz   ---   ---
Smith    Alex   Nick        12345  00000   ---   ---   vvv   aaa
Jone     Mary   John        22222  11111   sss   eee   ---   ---
Pan      Peter  Peter       33333  22222   ttt   uuu   ---   ---
Bob      Nick   Nick        44444  77777   ---   ---   ppp   qqq
Mary     Maria  John        99999  00000   jjj   kkk   ---   ---
Mary     Maria  John        99999  00000   ---   ---   iii   ---

预期输出:

Surname  Name   FatherName  Phone  Mobile   1     2     3     4
Smith    Alex   Nick        12345  00000   xxx   zzz   vvv   aaa
Jone     Mary   John        22222  11111   sss   eee   ---   ---
Pan      Peter  Peter       33333  22222   ttt   uuu   ---   ---
Bob      Nick   Nick        44444  77777   ---   ---   ppp   qqq
Mary     Maria  John        99999  00000   jjj   kkk   iii   ---

2 个答案:

答案 0 :(得分:3)

尝试以下简单查询:

Select
    Surname,  
    Name,
    FatherName,
    Phone,
    Mobile,
    Max(T.[1]) As [1],
    Max(T.[2]) As [2],
    Max(T.[3]) As [3],
    Max(T.[4]) As [4]
From
    YourTable As T
Group By
    Surname,  
    Name,
    FatherName,
    Phone,
    Mobile

答案 1 :(得分:0)

这将适用于您的示例数据。
首先通过自我联接获得合并的行,然后对唯一行使用UNION ALL:

SELECT t1.Surname, t1.Name, t1.FatherName, t1.Phone, t1.Mobile,
t1.[1], t1.[2], t2.[3], t2.[4]
FROM tablename t1 INNER JOIN tablename t2
ON t1.Surname = t2.Surname AND t1.Name = t2.Name AND t1.FatherName = t2.FatherName
AND (
  (t1.[1] <> '---' OR t1.[2] <> '---')
  AND 
  (t1.[3] = '---' AND t1.[4] = '---')
  AND 
  (t2.[3] <> '---' OR t2.[4] <> '---')
  AND
  (t2.[1] = '---' AND t2.[2] = '---')
)
UNION ALL
SELECT * FROM tablename AS t1
WHERE NOT EXISTS (
  SELECT 1 FROM tablename AS t2
  WHERE t1.Surname = t2.Surname AND t1.Name = t2.Name AND t1.FatherName = t2.FatherName AND t1.[1] <> t2.[1]
)