Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help for Cross Tab SQL Query

This is the source example table:

    UserID  UserNameType    UserName
    1       First Name      FN1
    1       Last Name       LN1
    2       First Name      FN2
    2       Last Name       LN2
    3       First Name      FN3
    3       Last Name       LN3
    4       First Name      FN4
    4       Last Name       LN4

I would like to have a SQL query to display my result like the given format below.

   
    UserID  FirstName   LastName
    1       FN1         LN1
    2       FN2         LN2
    3       FN3         LN3
    4       FN4         LN4

Need a little more help on this...

Need Help

Thanks, Yugal

like image 660
Yugal Avatar asked Mar 23 '26 11:03

Yugal


1 Answers

A simple cross-tab method (which I personally prefer) is to use the group by operator with MAX(CASE WHEN...) pattern to control the cross-tab fields. This is easy to understand IMO and easy to extend with more fields. I'm not sure about the performance.

select
    UserID,
    max(case when usernametype='First Name' then username end) as FirstName,
    max(case when usernametype='Last Name' then username end) as LastName
from
    MyTable T
group by
    UserID
like image 148
mellamokb Avatar answered Mar 25 '26 01:03

mellamokb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!