Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the same column multiple times

Tags:

sql

select

hope someone can help. I have two tables:

Users
  -UserID
  -UserName

UsersType
  -UserTypeID
  -UserID

Possible values for UsersTypeID is 1 to 6. In that scenario Users may have multiple types and I need to retrieve a distinct row for each user with the columns described below.

UserName - Type1 - Type2 - Type3 - Type4
Joe            0       1       1       0

In this scenario, Joe has two different User type (2,3)

This might be easy as pie but I have been working around this for so long that I am clueless. Can some one help please.

like image 239
Mario Avatar asked Jan 24 '26 04:01

Mario


2 Answers

This is a standard crosstab output which you should be able to google. Although not recommended in SQL you can do something like:

Select Users.Username
    , Max( Case When UsersType.UserTypeId = 1 Then 1 Else 0 End ) As Type1
    , Max( Case When UsersType.UserTypeId = 2 Then 1 Else 0 End ) As Type2
    , Max( Case When UsersType.UserTypeId = 3 Then 1 Else 0 End ) As Type3
    , Max( Case When UsersType.UserTypeId = 4 Then 1 Else 0 End ) As Type4
From Users
        Join UsersType
            On UsersType.UserId = Users.UserId
Group By Users.UserName

(Updated to Max instead of Min)

like image 149
Thomas Avatar answered Jan 25 '26 22:01

Thomas


SELECT U.[UserName]
    , AVG(CASE WHEN UT.[UserTypeID] IS 1 THEN 1 ELSE NULL END) AS N'Type 1'
    , AVG(CASE WHEN UT.[UserTypeID] IS 2 THEN 2 ELSE NULL END) AS N'Type 2'
    , AVG(CASE WHEN UT.[UserTypeID] IS 3 THEN 3 ELSE NULL END) AS N'Type 3'
    , AVG(CASE WHEN UT.[UserTypeID] IS 4 THEN 4 ELSE NULL END) AS N'Type 4'
    , AVG(CASE WHEN UT.[UserTypeID] IS 5 THEN 5 ELSE NULL END) AS N'Type 5'
    , AVG(CASE WHEN UT.[UserTypeID] IS 6 THEN 6 ELSE NULL END) AS N'Type 6'
FROM [Users] U
    INNER JOIN [UserType] UT ON UT.[UserID] = U.[UserID]
GROUP BY U.[UserName]
ORDER BY U.[UserName]
like image 43
Will Marcouiller Avatar answered Jan 25 '26 20:01

Will Marcouiller



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!