简体   繁体   中英

Combine records in one row with SQL

How do I combine two records into one row in my SQL query? My data looks like this:

Name    | Address     | Address_Type
--------------------------------------
Smith   | 123 Main St | P

Smith   | PO Box 123  | M

I need to get a result that looks like this:

Name    | P_Address   | M_Address
---------------------------------------
Smith   | 123 Main St | PO Box 123

Use conditional Aggregate to do this

select Name,
       Max(case when Address_Type = 'P' then Address End) as P_Address,
       Max(case when Address_Type = 'M' then Address End) as M_Address
From Yourtable
Group by Name

If you know that every person always has exactly one "P" address and never more than one "M" address then the following would work:

SELECT
    P.name,
    P.address AS p_address,
    M.address AS m_address
FROM
    My_Table P
LEFT OUTER JOIN My_Table M ON
    M.name = P.name AND
    M.address_type = 'M'
WHERE
    P.address_type = 'P'

If that's the case, then I would also make sure that those business rules are enforced through database constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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