0

I need to display summary of data stored in a MySQL database table

control_point_run

run_date    control_point   duration
10/10/2016  A   100
10/10/2016  B   200
10/10/2016  C   150
10/11/2016  A   160
10/11/2016  B   220
10/11/2016  C   180
10/12/2016  A   200
10/12/2016  B   120
10/12/2016  C   180

expected output

run_date    A   B   C
10/10/2016  100 200 150
10/11/2016  160 220 180
10/12/2016  200 120 180

Requirement image Please help me with MySQL query to get the expected result. I have no idea how to convert row data in to column headings [A,B,C].

Please note, the expected column names (A,B,C) need to be automatically generated based on the available data. the table contains more data than in this sample and more control_point values can be inserted in the future as well.

1
  • Have you tried google? Commented Nov 11, 2016 at 6:58

2 Answers 2

2

Use a pivot query:

SELECT run_date,
       MAX(CASE WHEN control_point = 'A' THEN duration END) AS A,
       MAX(CASE WHEN control_point = 'B' THEN duration END) AS B,
       MAX(CASE WHEN control_point = 'C' THEN duration END) AS C
FROM yourTable
GROUP BY run_date
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick response. the situation is bit complex than the sample data. I need columns like "A,B,C" to be automatically generated according to the available data. Because those data also can be changed,
Then you may need to use dynamic SQL in this case. Have you tried Googling around for this?
It tried google, but not for "dynamic SQL" I did not have that idea. And no idea in creating simple search term explaining this requirement. Will try the term "dynamic SQL" also.
Update your question with the real problem and maybe you will get an exact answer. Clearly, what you asked (and what I answered) is not this.
0

This may be right. Pls Check this also:

 SELECT run_date,
   (SELECT duration from tablename where control_point = 'A') as 'A',
   (SELECT duration from tablename where control_point = 'B') as 'B',
   (SELECT duration from tablename where control_point = 'C') as 'C' 
 FROM tablename
 GROUP BY run_date;

2 Comments

with this, the result does not display "duration".
Thanks for the suggestion, but the result of this contains duplicate data, displays wrong duration value for the positions that should be null. and, My requirement "column names (A,B,C) need to be automatically generated based on the available data" is not available as with your suggestion, I have to write sub select statements for all column. means if there is a new control_point in the table, it will not be in the result of this query until I add sub query for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.