开发者

On Denormalization. How can I make this query shorter or better? (SQL SERVER 2000) [closed]

开发者 https://www.devze.com 2023-03-12 12:21 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.
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 !

0

精彩评论

暂无评论...
验证码 换一张
取 消