On Denormalization. How can I make this query shorter or better? (SQL SERVER 2000) [closed]
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(开发者_Go百科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
You are doing a 'PIVOT' operation in SQL. There is no real better way to do, so you can't really make it better.
Maybe you can GROUP BY table1.userID instead of userName !
The question is : why do you need such a query ?
If you are doing the query for returning result in a View for a client, then the pivot operation must be the work of the View, not the DAL.
We need a little more context to answer you !
精彩评论