Return 1 列中的多个值

Return multiple values from 1 column

我有一个包含用户回复的 ResponseText 列和另一个名为 QuestionID 的列,它唯一标识每个问题。我正在使用的是:

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


我想根据这样的 QuestionID 在单独的列中显示 ResponseText(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'

但是这个 returns 一列名为 FName。我正在尝试做的事情是否可行?

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

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 的评论,您需要一个列来标识回答问题的人。为了便于说明,假设我们在 ResponseInstance.

上有一个 PersonID

示例数据

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

结果

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