2

O/pI want to join two rows into single row with multiple columns(dynamically) using SQL Query in PHP.

SQL Table tf4i

Desired Output

Output should be grouped by tf4hid and date.

SQL Query

Select tf4hid,tf4iid,date,product,planqty
from tf4i
group by date,product

This prints row by row but i need to generate columns based on the available products in the columns.

1 Answer 1

1

You can try to use condition aggregate function.

SELECT tf4hid,
       date,
       MAX(CASE WHEN product = 'MS(EURO-IV)' THEN planqty END) 'MS(EURO-IV)', 
       MAX(CASE WHEN product = 'HSD(Euro-IV)' THEN planqty END) 'HSD(Euro-IV)', 
       MAX(CASE WHEN product = 'Super_Petrol' THEN planqty END) 'Super_Petrol'  
FROM tf4i
GROUP BY tf4hid,date

EDIT

dynamic pivot version. create the sql then execute dynamically.

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      ' MAX(CASE WHEN product = ''',
      product,
      ''' THEN planqty END) ''',
      product , ''''
    )
  ) INTO @sql
FROM tf4i;



SET @sql = CONCAT('SELECT tf4hid,
                          date, ', @sql, ' 
                   FROM tf4i
                   GROUP BY tf4hid,date');

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

sqlfiddle

Sign up to request clarification or add additional context in comments.

5 Comments

It is working but Product needs to be fetched dynamically. Any idea for that by using php
@SriVathsan You can try to use dynamic pivot stackoverflow.com/questions/12598120/…
I have tried but i didn't understand it. could you please help me
I have added O/P error of result. Could you please figure it out
Any idea how to add this to php.

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.