简体   繁体   中英

How do i fetch Badge details and User details while comparing two similar records in a Column

This is the table

+----+------+---------+
| ID | USER | PROFILE |
+----+------+---------+
| 1  |  A   |  Water  |
| 2  |  B   |  Fire   |
| 3  |  C   |  Air    |
| 4  |  A   |  Fire   |
| 5  |  B   |  Air    |
+----+------+---------+

How do i get my output as

+----+------+-----------+-----------+
| ID | USER | PROFILE-A | PROFILE-B |
+----+------+-----------+-----------+
| 1  |  A   |  Water    |   Fire    |
| 2  |  B   |  Fire     |   Air     |
+----+------+-----------+-----------+

I have tried this query and i am able to pull only the user ID details,

SELECT A.ID 
FROM  
       (SELECT ID 
        FROM   Sheet1 
        WHERE  Profile = 'Water') A, 
       (SELECT ID 
        FROM   Sheet1 
        WHERE  Profile = 'Air') B 
WHERE  A.ID=B.ID; 

From the example you have provided (Data at the start and expected data) this query will give you the exact ersult:

select min(t1.id) as 'ID'
       , t1.user as 'USER' 
       , max(t1.PROFILE) as 'PROFILE-A'
       , min(t2.PROFILE) as 'PROFILE-B'
from Sheet1 t1
left join Sheet1 t2 on t1.USER = t2.USER
and t1.PROFILE <> t2.PROFILE
group by t1.user
having count(t1.user) > 1

Here is a DEMO .

Following your logic, you can get your results by joining on user and filtering out same profiles:

SELECT A.id, A.user, A.profile, B.profile
FROM 
  (SELECT * FROM sheet1) as A, 
  (SELECT * FROM sheet1) as B
 WHERE 
  A.user = B.user 
  AND A.profile <> B.profile
 GROUP BY A.user;

The same thing can be written as (a bit newer syntax):

SELECT B.id, B.user, B.profile, A.profile
FROM sheet1 A
JOIN sheet1 B on A.user=B.user
WHERE A.profile <> B.profile
GROUP BY B.user
ORDER BY B.id;

However, note that these queries will be very inefficient if you table gets too large. An alternative to avoid the join would be:

SELECT id, user, GROUP_CONCAT(DISTINCT(profile))
FROM sheet1
GROUP BY user
HAVING COUNT(profile) > 1
ORDER BY id;

This way, you are not joining on anything and the query should be a lot faster on larger datasets. However, the 3rd column will be a comma-separated list of profile names for each user

Example: http://sqlfiddle.com/#!9/773959/46/0

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