我正在尝试合并几个表以获得输出,如下图所示。
我的问题是我不确定使用什么类型的连接来实现
有人可以帮我解释语法。
答案 0 :(得分:3)
你可以做这样的事情,它可以作为动态支点,因为你可能会添加/带走用户?
CREATE TABLE #Tests (
Test_ID INT,
TestName VARCHAR(50));
INSERT INTO #Tests VALUES (1, 'SQL Test');
INSERT INTO #Tests VALUES (2, 'C# Test');
INSERT INTO #Tests VALUES (3, 'Java Test');
CREATE TABLE #Users (
[User_ID] INT,
UserName VARCHAR(50));
INSERT INTO #Users VALUES (1, 'Joe');
INSERT INTO #Users VALUES (2, 'Jack');
INSERT INTO #Users VALUES (3, 'Jane');
CREATE TABLE #UserTests (
ID INT,
[User_ID] INT,
Test_ID INT,
Completed INT);
INSERT INTO #UserTests VALUES (1, 1, 1, 0);
INSERT INTO #UserTests VALUES (2, 1, 2, 1);
INSERT INTO #UserTests VALUES (3, 1, 3, 1);
INSERT INTO #UserTests VALUES (4, 2, 1, 0);
INSERT INTO #UserTests VALUES (5, 2, 2, 0);
INSERT INTO #UserTests VALUES (6, 2, 3, 0);
INSERT INTO #UserTests VALUES (7, 3, 1, 1);
INSERT INTO #UserTests VALUES (8, 3, 2, 1);
INSERT INTO #UserTests VALUES (9, 3, 3, 1);
DECLARE @Cols VARCHAR(MAX);
SELECT @Cols = STUFF((SELECT distinct ',' + QUOTENAME(u.UserName)
FROM #Users u
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
DECLARE @Query NVARCHAR(MAX);
SELECT @Query = 'SELECT TestName, ' + @Cols + ' FROM
(
SELECT
t.TestName,
u.UserName,
ut.Completed
FROM
#Tests t
INNER JOIN #UserTests ut ON ut.Test_ID = t.Test_ID
INNER JOIN #Users u ON u.[User_ID] = ut.[User_ID]) x
PIVOT (
MAX(Completed)
FOR UserName IN (' + @Cols + ')
) AS pt';
EXEC(@Query);
结果是:
TestName Jack Jane Joe
C# Test 0 1 1
Java Test 0 1 1
SQL Test 0 1 0
(与您的结果相同,但排序顺序不同。)