从1列返回多个值

时间:2015-01-12 06:35:49

标签: sql-server

我有一个ResponseText列,其中包含用户的响应以及另一个名为QuestionID的列,该列唯一标识每个问题。我正在使用的是:

|  QuestionID  |  ResponseText  |
---------------------------------
|      32      |     Billson    |  <- First Name
|      33      |     Thorn      |  <- Last Name
|      34      |   0422949333   |  <- Ph Number
|      35      |  bt@thorn.com  |  <- Email


我想在单独的列中显示ResponseText,具体取决于QuestionID(QuestionID 33将始终是姓氏等):

|  FName   |  LName   |  Ph Number   |  Email      |
----------------------------------------------------
| Billson  |  Thorn   |  0422949333  | bt@thorn.com|

现在,我有

SELECT dbo.ResponseInstance.ResponseText as 'FName'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '32'
UNION
SELECT dbo.ResponseInstance.ResponseText as 'LName'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '33'   
UNION
SELECT dbo.ResponseInstance.ResponseText as 'Phone'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '34'
UNION
SELECT dbo.ResponseInstance.ResponseText as 'Email'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '35'

但是,这会返回一个名为FName的列。我想做什么甚至可能?

1 个答案:

答案 0 :(得分:-1)

您可以使用条件聚合执行此操作:

SELECT
    FName = MAX(CASE WHEN QuestionID = 32 THEN ResponseText END),
    LName = MAX(CASE WHEN QuestionID = 33 THEN ResponseText END),
    [Ph Number] = MAX(CASE WHEN QuestionID = 34 THEN ResponseText END),
    Email = MAX(CASE WHEN QuestionID = 35 THEN ResponseText END)
FROM ResponseInstance

编辑:

根据Eric的评论,您需要一个标识回答问题的人的专栏。为了便于说明,我们假设PersonID上有ResponseInstance列。

示例数据

CREATE TABLE ResponseInstance(
    PersonID    INT,
    QuestionID  INT,
    ResponseText VARCHAR(50),
)
INSERT INTO ResponseInstance VALUES
(1, 32, 'Billson'),
(1, 33, 'Thorn'),
(1, 34, '0422949333'),
(1, 35, 'bt@thorn.com'),
(2, 32, 'John'),
(2, 33, 'Doe'),
(2, 34, '999999999'),
(2, 35, 'johndoe@email.com')

您仍然可以使用条件聚合,但这一次,您需要按PersonID对它们进行分组。

SELECT
    PersonID,
    FName = MAX(CASE WHEN QuestionID = 32 THEN ResponseText END),
    LName = MAX(CASE WHEN QuestionID = 33 THEN ResponseText END),
    [Ph Number] = MAX(CASE WHEN QuestionID = 34 THEN ResponseText END),
    Email = MAX(CASE WHEN QuestionID = 35 THEN ResponseText END)
FROM ResponseInstance
GROUP BY PersonID

<强> RESULT

PersonID    FName       LName       Ph Number       Email
--------- ------------ ----------- --------------- ----------------------
1           Billson     Thorn       0422949333      bt@thorn.com
2           John        Doe         999999999       johndoe@email.com