用 Null 值填充字段

Filling fields with Null values

我在 SQL Server 2012

中有两个表

表 1

UserID Name
1 Joe
2 Mary

表 2

UserID Permission
1 P15
2 P5
2 P330

每个用户可以拥有 1 到 8 个权限。

我需要创建一个视图,该视图将向我提供具有 8 个权限条目的 UserID,以及任何包含空值的未使用条目,即条目的顺序无关紧要。

UserID Permit1 Permit2 Permit3 Permit4 Permit5 Permit6 Permit7 Permit8
1 P15 Null Null Null Null Null Null Null
2 P5 P330 Null Null Null Null Null Null

这让我很困惑,我什至不知道从哪里开始?

这应该可以满足您的要求。

SELECT f.UserID, (SELECT top(1) Permission from Table_2 t where t.UserID = f.UserID order by Permission desc) as Permit1
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 1 row FETCH NEXT 1 ROWS ONLY) as Permit2
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 2 row FETCH NEXT 1 ROWS ONLY) as Permit3
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 3 row FETCH NEXT 1 ROWS ONLY) as Permit4
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 4 row FETCH NEXT 1 ROWS ONLY) as Permit5
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 5 row FETCH NEXT 1 ROWS ONLY) as Permit6
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 6 row FETCH NEXT 1 ROWS ONLY) as Permit7
, (SELECT Permission from Table_2 t where t.UserID = f.UserID order by Permission desc offset 7 row FETCH NEXT 1 ROWS ONLY) as Permit8
from Table1 as f

我输入了你的数据,并为用户 id 2 添加了一个条目,它返回了这样的结果。

UserID   Permit1 Permit2 Permit3 Permit4 Permit5 Permit6 Permit7 Permit8
1        P15     NULL     NULL     NULL  NULL     NULL     NULL     NULL
2        P5      P330     P15      NULL  NULL     NULL     NULL     NULL

您可以使用条件聚合轻松地做到这一点。这已被询问和回答数百次,但如果这是一个新概念,则很难知道要使用哪些搜索词。这是完整的消耗性样本数据。

declare @Users table
(
    UserID int
    , Name varchar(10)
)

insert @Users values
(1, 'Joe')
, (2, 'Mary')

declare @Permissions table
(
    UserID int
    , Permission varchar(10)
)

insert @Permissions values
(1, 'P15')
, (2, 'P5')
, (2, 'P330')


select x.UserID
    , Permit1 = max(case when x.RowNum = 1 then x.Permission end)
    , Permit2 = max(case when x.RowNum = 2 then x.Permission end)
    , Permit3 = max(case when x.RowNum = 3 then x.Permission end)
    , Permit4 = max(case when x.RowNum = 4 then x.Permission end)
    , Permit5 = max(case when x.RowNum = 5 then x.Permission end)
    , Permit6 = max(case when x.RowNum = 6 then x.Permission end)
    , Permit7 = max(case when x.RowNum = 7 then x.Permission end)
    , Permit8 = max(case when x.RowNum = 8 then x.Permission end)
from
(
    select u.UserID
        , p.Permission
        , RowNum = ROW_NUMBER() over(partition by u.UserId order by p.Permission)
    from @Users u
    join @Permissions p on p.UserID = u.UserID
) x
group by x.UserID