选择sql表行作为调查应用程序的列

时间:2014-12-15 16:23:04

标签: asp.net sql-server pivot

我正在开发一个调查应用程序,一个非常简单的应用程序,有两个表。

table_survey_answers

+------------+------------+----------------+
| customerid | questionID |     answer     |
+------------+------------+----------------+
|          1 |        100 | Good           |
|          1 |        101 | Acceptable     |
|          1 |        102 | Excellent      |
|          2 |        100 | Not acceptable |
|          2 |        101 | Acceptable     |
|          2 |        102 | Good           |
+------------+------------+----------------+

table_questions

+------------+-----------------------------------+
| QuestionID |             Question              |
+------------+-----------------------------------+
|        100 | Kindly rate our customer service? |
|        101 | How fast is our product delivery? |
|        102 | Quality of the Product A?         |
+------------+-----------------------------------+

现在我想在asp.net gridview中显示调查结果如下。

+------------+-----------------------------------+-----------------------------------+---------------------------+
| CustomerID | Kindly rate our customer service? | How fast is our product delivery? | Quality of the Product A? |
+------------+-----------------------------------+-----------------------------------+---------------------------+
|          1 | Good                              | Acceptable                        | Excellent                 |
|          2 | Not Acceptable                    | acceptable                        | Good                      |
+------------+-----------------------------------+-----------------------------------+---------------------------+

我已经创建了表格来获取调查回复。我只想按照上面的格式将结果导出到gridview中。

1 个答案:

答案 0 :(得分:0)

使用 Pivot 将您的行转置为列

SELECT *
FROM   (SELECT customerid,
               answer,
               Question
        FROM   table_questions a
               JOIN table_survey_answers b
                 ON a.QuestionID = b.questionID) a
       PIVOT (Max(answer)
             FOR Question IN([Kindly rate our customer service?],
                             [How fast is our product delivery?],
                             [Quality of the Product A?])) piv 

SQL FIDDLE DEMO