我正在对Stack Overflow转储进行分析。
问题陈述:我有4个表,并且要求给出格式的结果。
Table 1: UserID Year QuestionsOnTopicA
Table 2: UserID Year AnswersOnTopicA
Table 3: UserID Year QuestionsOnTopicB
Table 4: UserID Year AnswersOnTopicB
期望的输出:
UserID Year QuestionsOnTopicA AnswersOnTopicA QuestionsOnTopicB AnswersOnTopicB
UserID列应包含来自所有4个表的条目。
我尝试在表上执行内部和外部联接,但结果不正确。 内连接(仅返回第一个表1中存在的用户ID) 外连接(仅为表1中的userid返回其他列)
不确定联合在这种情况下是否有意义。
正在data.stackexchange.com/stackoverflow
上执行查询实施例
表1:1001,2010,5 || 1001,2011,3 || 1002,2010,4,
表2:1001,2010,10 || 1001,2011,7 || 1002,2010,5
表3:1002,2010,5
表4:1001,2010,10 || 1004,2011,5
输出:
1001,2010,5,10,0,10
1001,2011,3,7,0,0
1002,2010,4,5,5,0
1004,2011,0,0,0,5
答案 0 :(得分:1)
使用这个SQL可能是?
SELECT a.UserID, a.Year,
a.QuestionsOnTopicA,
b.AnswersOnTopicA,
c.QuestionsOnTopicB,
d.AnswersOnTopicB
FROM Table 1 a,
Table 2 b,
Table 3 c,
Table 4 d
WHERE a.UserID = b.UserID
AND b.UserID = c.UserID
AND c.UserID = d.UserID
AND d.UserID = a.UserID
答案 1 :(得分:1)
select coalesce(a.UserID, b.UserID, c.UserID, d.UserID),
coalesce(a.Year, b.Year, c.Year, d.Year),
a.QuestionsOnTopicA, b.AnswersOnTopicA,
c.QuestionsOnTopicB, d.AnswersOnTopicB
from Table1 a full outer join Table2 b on a.UserID = b.UserID and a.Year = b.Year
full outer join Table3 c on (c.UserID = b.UserID or c.UserID = a.UserID)
and (c.Year = b.Year or c.Year = a.Year)
full outer join Table4 d on (d.UserID = c.UserID or d.UserID = b.UserID or d.UserID = a.UserID)
and (d.Year = a.Year or d.Year = b.Year or d.Year = a.Year);
答案 2 :(得分:1)
好的,这可以按预期工作:
SELECT COALESCE(A.UserID,B.UserID,C.UserID,D.UserID) UserID,
COALESCE(A.[Year],B.[Year],C.[Year],D.[Year]) [Year],
ISNULL(A.QuestionsOnTopicA,0) QuestionsOnTopicA,
ISNULL(B.AnswersOnTopicA,0) AnswersOnTopicA,
ISNULL(C.QuestionsOnTopicB,0) QuestionsOnTopicB,
ISNULL(D.AnswersOnTopicB,0) AnswersOnTopicB
FROM Table1 A
FULL JOIN Table2 B
ON A.UserID = B.UserID
AND A.[Year] = B.[Year]
FULL JOIN Table3 C
ON COALESCE(A.UserID,B.UserID) = C.UserID
AND COALESCE(A.[Year],B.[Year]) = C.[Year]
FULL JOIN Table4 D
ON COALESCE(A.UserID,B.UserID,C.UserID) = D.UserID
AND COALESCE(A.[Year],B.[Year],C.[Year]) = D.[Year]
Here is a sqlfiddle及其演示。
结果是:
╔════════╦══════╦═══════════════════╦═════════════════╦═══════════════════╦═════════════════╗
║ UserID ║ Year ║ QuestionsOnTopicA ║ AnswersOnTopicA ║ QuestionsOnTopicB ║ AnswersOnTopicB ║
╠════════╬══════╬═══════════════════╬═════════════════╬═══════════════════╬═════════════════╣
║ 1001 ║ 2010 ║ 5 ║ 10 ║ 0 ║ 10 ║
║ 1001 ║ 2011 ║ 3 ║ 7 ║ 0 ║ 0 ║
║ 1002 ║ 2010 ║ 4 ║ 5 ║ 5 ║ 0 ║
║ 1004 ║ 2011 ║ 0 ║ 0 ║ 0 ║ 5 ║
╚════════╩══════╩═══════════════════╩═════════════════╩═══════════════════╩═════════════════╝
答案 3 :(得分:0)
首先,您应该使用内部联接从表中检索数据。 然后,您应该使用SQL Server Pivot,如此link。
所示