简体   繁体   English

Ms-access查询以合并行

[英]Ms-access query to merge rows

I want a query to merge each of two rows meeting the following conditions in a large table: 我想要一个查询在大表中合并满足以下条件的两行中的每一行:

  1. Surname , Name , FatherName are duplicates SurnameNameFatherName Surname是重复的
  2. 1 , 2 contain "---" on one of the rows and 3 , 4 contain "---" on the other row 12含有“---”的行中的一个和34含有“---”在另一行

Example data: 示例数据:

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

Expected output: 预期产量:

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

Try this simple query: 试试这个简单的查询:

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

This will work for your sample data. 这适用于您的样本数据。
First with a self join I get the merged rows and then with UNION ALL for the unique rows: 首先使用自联接,我获取合并的行,然后使用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]
)

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

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