希望有人能帮忙。我有两个表:
Users
-UserID
-UserName
UsersType
-UserTypeID
-UserID
UsersTypeID 的可能值为 1 到 6。在这种情况下,用户可能有多种类型,我需要为每个用户检索一个不同的行,其中的列如下所述。
UserName - Type1 - Type2 - Type3 - Type4
Joe 0 1 1 0
在这个场景中,Joe 有两个不同的用户类型 (2,3)
这可能像馅饼一样简单,但我已经解决这个问题太久了,以至于我一无所知。请有人帮忙。
最佳答案
这是一个标准的交叉表输出,您应该可以用谷歌搜索。尽管不建议在 SQL 中使用,但您可以执行以下操作:
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
(更新为最大值而不是最小值)
关于sql - 多次选择同一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2410066/