0

thanks for all your help in Advance.

I have a table called 'data' in MySQL PHPmyAdmin, like this;

Primary | Date| User | Response
   1      Mon   Tom      Yes
   2      Mon   Terry    No
   3      Mon   Lucas    Yes
   4      Tue   Tom      No
   5      Tue   Terry    No
   6      Tue   Lucas    Yes
   7      Wed   Tom      Yes
   8      Wed   Terry    Yes
   9      Wed   Lucas    No

How do i output into a table, via most probably SQL query or Pivot / php arrays, into this ready for HTML table output;

Date | Tom | Terry | Lucas
Mon    Yes   No      Yes
Tue    No    No      Yes
Wed    Yes   Yes     No

1 Answer 1

1
SELECT  Date,
        MAX(CASE WHEN user = 'Tom' THEN Response ELSE NULL END) Tom,
        MAX(CASE WHEN user = 'Terry' THEN Response ELSE NULL END) Terry ,
        MAX(CASE WHEN user = 'Lucas' THEN Response ELSE NULL END) Lucas
FROM    tableName
GROUP   BY Date

if you have unknown number of days, a dynamic sql is more preferred,

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(case when user = ''',
      user,
      ''' then Response end) AS ',
      user
    )
  ) INTO @sql
FROM tableName;

SET @sql = CONCAT('SELECT  Date, ', @sql, ' 
                  FROM    tableName
                  GROUP   BY Date');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
0

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.