如果您不能或不想使用 PIVOT/UNPIVOT,则另一种选择是将列一一加入用户:
DECLARE @Users TABLE(
UserID int NOT NULL
)
INSERT INTO @Users (UserID) VALUES (1)
INSERT INTO @Users (UserID) VALUES (2)
INSERT INTO @Users (UserID) VALUES (3)
DECLARE @AnyTable TABLE(
UserID int NOT NULL,
FieldNo int NOT NULL,
Value varchar(50) NULL
)
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (1, 1, 'abc')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (1, 2, 'def')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (1, 3, 'ghi')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (2, 1, '123')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (2, 3, '789')
SELECT u.UserID,
col1.Value as Column1,
col2.Value as Column2,
col3.Value as Column3
FROM @Users u
LEFT JOIN @AnyTable col1
ON col1.UserID = u.UserID
AND col1.FieldNo = 1
LEFT JOIN @AnyTable col2
ON col2.UserID = u.UserID
AND col2.FieldNo = 2
LEFT JOIN @AnyTable col3
ON col3.UserID = u.UserID
AND col3.FieldNo = 3
结果将是:
UserID Column1 Column2 Column3
1 abc def ghi
2 123 NULL 789
3 NULL NULL NULL