简体   繁体   中英

Pivot a joined query in MySQL Query

I think Pivot is the right term for what I am after. I have tried different variations of my main query without any luck. Below is SQL Fiddle of a simplified schema with my base query.

SQL Fiddle

Basically I have a Responses table that stores responses to a type of survey. Each question(metric) response is stored as new row in the response table. The last column in the response table is called response_session which stores a unique ID next to each response that was part of the same survey session.

So for example if I respond to a 3 question survey, the response_session column at the end of each of the 3 response rows would be the same, so know that each of those responses was part of the same session.

Below is my current query:

 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

You can see this query in action on the fiddle above. I need this one query to return 1 row based on the response_session . So the response should look like this:

| 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 |

As you can each of the individual responses is pivoted(?) up base on the response_session .

If any MySQL gurus out there can point me in the right direction I would be forever grateful.

Thanks

Try this:

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

Note : You can include alias names as column labels for whichever other columns you want.

Also on SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM