在MySQL Query中透视连接的查询

时间:2014-02-13 12:16:15

标签: mysql database pivot

我认为Pivot是我追求的正确术语。我已经尝试了我的主要查询的不同变体,没有任何运气。下面是使用我的基本查询的简化模式的SQL Fiddle。

SQL Fiddle

基本上我有一个Responses表来存储对某种调查的回复。每个问题(度量标准)响应都存储为响应表中的新行。响应表中的最后一列称为response_session,它在每个响应旁边存储唯一ID,该响应属于同一调查会话。

因此,例如,如果我回答3个问题调查,则3个响应行中每个响应行末尾的response_session列将是相同的,因此请知道每个响应都是同一会话的一部分

以下是我当前的查询:

 SELECT T0.timestamp, T3.first_name AS 'First Name', T3.last_name AS 'Last Name', T3.email AS 'Email Address', T1.title AS 'Metric Title', T2.category AS 'Category', T0.answer AS 'Score', T0.response_session AS 'Response Session'
        FROM responses AS T0

        LEFT JOIN secondary_metrics AS T1
        ON T0.metric_id = T1.id

        LEFT JOIN default_categories AS T2
        ON T0.category = T2.id

        LEFT JOIN users AS T3
        ON T0.user = T3.user_id

您可以在上面的小提琴中看到此查询。我需要这一个查询根据response_session返回1行。因此响应应如下所示:

| Timestamp | First Name | Last Name | Email Address | Metric 1 Title | Metric 1 Score | Metric 2 Title | Metric 2 Score | Metric 3 Title | Metric 3 Score | Category |

您可以根据response_session向上调整每个回复(?)。

如果有任何MySQL专家可以指出我正确的方向,我将永远感激。

由于

1 个答案:

答案 0 :(得分:0)

试试这个:

select timestamp, first_name, last_name, email,
  max( case title when 'Helpful' then title end ) as 'Metric 1 Title',
  max( case title when 'Helpful' then answer end ) as 'Metric 1 Score',
  max( case title when 'Polite' then title end ) as 'Metric 2 Title',
  max( case title when 'Polite' then answer end ) as 'Metric 2 Score',
  max( case title when 'Clever' then title end ) as 'Metric 3 Title',
  max( case title when 'Clever' then answer end ) as 'Metric 3 Score',
  category
from(

SELECT 
  T0.timestamp, T3.first_name, T3.last_name,
  T3.email, T1.title, T2.category,
  T0.answer, T0.response_session
FROM responses AS T0
  LEFT JOIN secondary_metrics AS T1
    ON T0.metric_id = T1.id
  LEFT JOIN default_categories AS T2
    ON T0.category = T2.id
  LEFT JOIN users AS T3
    ON T0.user = T3.user_id
) tmp_tbl

注意:您可以将别名作为列标签包含在您想要的任何其他列中。

同样在SQL Fiddle