2011-06-14 39 views
-6
INSERT INTO 
denormalizedTable 

SELECT 
table1.userName, 
MAX(CASE WHEN table2.Type = 1 THEN table2.Question END) AS question_1, 
MAX(CASE WHEN table2.Type = 1 THEN table2.Answer END) AS answer_1, 
MAX(CASE WHEN table2.Type = 2 THEN table2.Question END) AS question_2, 
MAX(CASE WHEN table2.Type = 2 THEN table2.Answer END) AS answer_2, 
MAX(CASE WHEN table2.Type = 3 THEN table2.Question END) AS question_3, 
MAX(CASE WHEN table2.Type = 3 THEN table2.Answer END) AS answer_3, 
MAX(CASE WHEN table2.Type = 4 THEN table2.Question END) AS question_4, 
MAX(CASE WHEN table2.Type = 4 THEN table2.Answer END) AS answer_4, 
MAX(CASE WHEN table2.Type = 5 THEN table2.Question END) AS question_5, 
MAX(CASE WHEN table2.Type = 5 THEN table2.Answer END) AS answer_5, 
MAX(CASE WHEN table2.Type = 6 THEN table2.Question END) AS question_6, 
MAX(CASE WHEN table2.Type = 6 THEN table2.Answer END) AS answer_6, 
MAX(CASE WHEN table2.Type = 7 THEN table2.Question END) AS question_7, 
MAX(CASE WHEN table2.Type = 7 THEN table2.Answer END) AS answer_7, 
MAX(CASE WHEN table2.Type = 8 THEN table2.Question END) AS question_8, 
MAX(CASE WHEN table2.Type = 8 THEN table2.Answer END) AS answer_8 

FROM 
table1 
JOIN 
table2 
ON 
table1.userID = table2.userID 

GROUP BY table1.userName 
+2

相反,你必須保持一個新的表的,你有沒有考慮過這是一個索引視圖? http://technet.microsoft.com/en-us/library/cc917717.aspx – 2011-06-14 05:24:10

+0

你認爲'denormalizedTable'在哪個正常形式? – onedaywhen 2011-06-14 14:12:05

回答

2

您正在SQL中執行'PIVOT'操作。沒有真正的更好的辦法,所以你不能真正做得更好。

也許你可以GROUP BY table1.userID而不是userName!

問題是:爲什麼你需要這樣的查詢?

如果你正在做的查詢的信息查看客戶端返回的結果,然後轉動操作時一定要查看的工作,而不是DAL。

我們需要更多的上下文來回答您!

+0

這甚至不是答案。爲什麼這個表決和誰刪除了評論? – JohnCoSystem 2011-06-14 16:57:59

相關問題