简体   繁体   中英

How to pivot table and combine rows based on a condition

I have the following table produced by the following SQL:

select userid, name, sirname, age from Users

在此处输入图像描述

I am wondering what would the best way be to convert this to something that looks like:

在此处输入图像描述

Would partition by + distinct be the most efficient way of doing this?

SELECT userid, [0] AS name, [1] AS sirname, age
FROM users 
PIVOT
(MAX(name)
FOR sirname IN ([0],[1]))AS p

I would just suggest aggregation:

select userid, max(case when simame = 0 then name end) as name,
       max(case when simmame = 1 then name end) as simame,
       age
from t
group by userid, age;

I'd like to suggest, that the most natural solution would be:

SELECT
    u1.id
    ,u1.name
    ,u2.name as sirname
    ,u1.age
FROM users u1
INNER JOIN users u2 ON u1.id=u2.id and u2.sirname=1
WHERE
  u1.sirname=0

even more so, as this approach can easily be modelled to cope with situations where one of the two names may be missing.

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