Setting column values as column names in the SQL query result











up vote
9
down vote

favorite
6












I wanted to read a table which has values which will be the column names of the sql query result.
For example, I have table1 as ..



id    col1     col2
----------------------
0 name ax
0 name2 bx
0 name3 cx
1 name dx
1 name2 ex
1 name2 fx


If u see for id = 0, name has value of ax and name 2 - bx and name3 = cx
instead of this being rows it would be easier to show columns as id, name, name2, name3
Now I want the result of the query to look like this



id   name    name2     name3
0 ax bx cx
1 dx ex fx


Can someone help me in achieving this ?










share|improve this question
























  • It of course woudl be easier all around if you avoided storing column names as data and used a table where they were actual column names. Difficulty qquerying is one of the big disadvantages of using an EAV struture, along with performance. Do you really need that type of structure and can you redesign?
    – HLGEM
    Oct 9 '12 at 20:57















up vote
9
down vote

favorite
6












I wanted to read a table which has values which will be the column names of the sql query result.
For example, I have table1 as ..



id    col1     col2
----------------------
0 name ax
0 name2 bx
0 name3 cx
1 name dx
1 name2 ex
1 name2 fx


If u see for id = 0, name has value of ax and name 2 - bx and name3 = cx
instead of this being rows it would be easier to show columns as id, name, name2, name3
Now I want the result of the query to look like this



id   name    name2     name3
0 ax bx cx
1 dx ex fx


Can someone help me in achieving this ?










share|improve this question
























  • It of course woudl be easier all around if you avoided storing column names as data and used a table where they were actual column names. Difficulty qquerying is one of the big disadvantages of using an EAV struture, along with performance. Do you really need that type of structure and can you redesign?
    – HLGEM
    Oct 9 '12 at 20:57













up vote
9
down vote

favorite
6









up vote
9
down vote

favorite
6






6





I wanted to read a table which has values which will be the column names of the sql query result.
For example, I have table1 as ..



id    col1     col2
----------------------
0 name ax
0 name2 bx
0 name3 cx
1 name dx
1 name2 ex
1 name2 fx


If u see for id = 0, name has value of ax and name 2 - bx and name3 = cx
instead of this being rows it would be easier to show columns as id, name, name2, name3
Now I want the result of the query to look like this



id   name    name2     name3
0 ax bx cx
1 dx ex fx


Can someone help me in achieving this ?










share|improve this question















I wanted to read a table which has values which will be the column names of the sql query result.
For example, I have table1 as ..



id    col1     col2
----------------------
0 name ax
0 name2 bx
0 name3 cx
1 name dx
1 name2 ex
1 name2 fx


If u see for id = 0, name has value of ax and name 2 - bx and name3 = cx
instead of this being rows it would be easier to show columns as id, name, name2, name3
Now I want the result of the query to look like this



id   name    name2     name3
0 ax bx cx
1 dx ex fx


Can someone help me in achieving this ?







mysql sql pivot






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 5:52









jww

52.1k37214479




52.1k37214479










asked Oct 9 '12 at 20:47









ravi

61731943




61731943












  • It of course woudl be easier all around if you avoided storing column names as data and used a table where they were actual column names. Difficulty qquerying is one of the big disadvantages of using an EAV struture, along with performance. Do you really need that type of structure and can you redesign?
    – HLGEM
    Oct 9 '12 at 20:57


















  • It of course woudl be easier all around if you avoided storing column names as data and used a table where they were actual column names. Difficulty qquerying is one of the big disadvantages of using an EAV struture, along with performance. Do you really need that type of structure and can you redesign?
    – HLGEM
    Oct 9 '12 at 20:57
















It of course woudl be easier all around if you avoided storing column names as data and used a table where they were actual column names. Difficulty qquerying is one of the big disadvantages of using an EAV struture, along with performance. Do you really need that type of structure and can you redesign?
– HLGEM
Oct 9 '12 at 20:57




It of course woudl be easier all around if you avoided storing column names as data and used a table where they were actual column names. Difficulty qquerying is one of the big disadvantages of using an EAV struture, along with performance. Do you really need that type of structure and can you redesign?
– HLGEM
Oct 9 '12 at 20:57












3 Answers
3






active

oldest

votes

















up vote
12
down vote



accepted










This is done with a pivot table. Grouping by id, you issue CASE statements for each value you want to capture in a column and use something like a MAX() aggregate to eliminate the nulls and collapse down to one row.



SELECT
id,
/* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
/* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
FROM
yourtable
GROUP BY id
ORDER BY id


Here's a working sample



Note: This only works as is for a finite and known number of possible values for col1. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.






share|improve this answer





















  • that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
    – ravi
    Oct 9 '12 at 20:55


















up vote
6
down vote













What you are attempting to do is a PIVOT MySQL does not have a PIVOT function so you can replicate this using a CASE and an aggregate function.



If you have a known number of columns, then you can use a static version and hard-code the values. Similar to this (See SQL Fiddle with demo):



select id,
max(case when col1='name' then col2 end) name,
max(case when col1='name2' then col2 end) name2,
max(case when col1='name3' then col2 end) name3
from yourtable
group by id


But if you have an unknown number of columns, then you can use a prepared statement and create this dynamically:



SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when col1 = ''',
col1,
''' then col2 end) AS ',
col1
)
) INTO @sql
FROM yourtable;

SET @sql = CONCAT('SELECT id, ', @sql, '
FROM yourtable
GROUP BY id');

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


See SQL Fiddle with Demo






share|improve this answer




























    up vote
    0
    down vote













    select id,
    max(if(tablename.columnname = 'name',tablename.columnname,null)) as namealise,
    max(if(tablename.columnname = 'name1',tablename.columnname,null)) as namealise1
    from table1, table2
    where table1.id = table2.id
    group by table1.id
    order by table1.id





    share|improve this answer























    • An explanation would be helpful. And consider using code formatting for improved readability.
      – Michael_B
      Oct 26 '16 at 17:46











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f12808189%2fsetting-column-values-as-column-names-in-the-sql-query-result%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    12
    down vote



    accepted










    This is done with a pivot table. Grouping by id, you issue CASE statements for each value you want to capture in a column and use something like a MAX() aggregate to eliminate the nulls and collapse down to one row.



    SELECT
    id,
    /* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
    /* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
    MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
    MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
    MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
    FROM
    yourtable
    GROUP BY id
    ORDER BY id


    Here's a working sample



    Note: This only works as is for a finite and known number of possible values for col1. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.






    share|improve this answer





















    • that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
      – ravi
      Oct 9 '12 at 20:55















    up vote
    12
    down vote



    accepted










    This is done with a pivot table. Grouping by id, you issue CASE statements for each value you want to capture in a column and use something like a MAX() aggregate to eliminate the nulls and collapse down to one row.



    SELECT
    id,
    /* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
    /* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
    MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
    MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
    MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
    FROM
    yourtable
    GROUP BY id
    ORDER BY id


    Here's a working sample



    Note: This only works as is for a finite and known number of possible values for col1. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.






    share|improve this answer





















    • that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
      – ravi
      Oct 9 '12 at 20:55













    up vote
    12
    down vote



    accepted







    up vote
    12
    down vote



    accepted






    This is done with a pivot table. Grouping by id, you issue CASE statements for each value you want to capture in a column and use something like a MAX() aggregate to eliminate the nulls and collapse down to one row.



    SELECT
    id,
    /* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
    /* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
    MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
    MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
    MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
    FROM
    yourtable
    GROUP BY id
    ORDER BY id


    Here's a working sample



    Note: This only works as is for a finite and known number of possible values for col1. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.






    share|improve this answer












    This is done with a pivot table. Grouping by id, you issue CASE statements for each value you want to capture in a column and use something like a MAX() aggregate to eliminate the nulls and collapse down to one row.



    SELECT
    id,
    /* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
    /* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
    MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
    MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
    MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
    FROM
    yourtable
    GROUP BY id
    ORDER BY id


    Here's a working sample



    Note: This only works as is for a finite and known number of possible values for col1. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Oct 9 '12 at 20:50









    Michael Berkowski

    221k34370339




    221k34370339












    • that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
      – ravi
      Oct 9 '12 at 20:55


















    • that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
      – ravi
      Oct 9 '12 at 20:55
















    that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
    – ravi
    Oct 9 '12 at 20:55




    that was a very quick response and thank you very much .... that works like a charm and this is what i was expecting to do. Awesome ... I appreciate ur quick help.
    – ravi
    Oct 9 '12 at 20:55












    up vote
    6
    down vote













    What you are attempting to do is a PIVOT MySQL does not have a PIVOT function so you can replicate this using a CASE and an aggregate function.



    If you have a known number of columns, then you can use a static version and hard-code the values. Similar to this (See SQL Fiddle with demo):



    select id,
    max(case when col1='name' then col2 end) name,
    max(case when col1='name2' then col2 end) name2,
    max(case when col1='name3' then col2 end) name3
    from yourtable
    group by id


    But if you have an unknown number of columns, then you can use a prepared statement and create this dynamically:



    SET @sql = NULL;
    SELECT
    GROUP_CONCAT(DISTINCT
    CONCAT(
    'max(case when col1 = ''',
    col1,
    ''' then col2 end) AS ',
    col1
    )
    ) INTO @sql
    FROM yourtable;

    SET @sql = CONCAT('SELECT id, ', @sql, '
    FROM yourtable
    GROUP BY id');

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


    See SQL Fiddle with Demo






    share|improve this answer

























      up vote
      6
      down vote













      What you are attempting to do is a PIVOT MySQL does not have a PIVOT function so you can replicate this using a CASE and an aggregate function.



      If you have a known number of columns, then you can use a static version and hard-code the values. Similar to this (See SQL Fiddle with demo):



      select id,
      max(case when col1='name' then col2 end) name,
      max(case when col1='name2' then col2 end) name2,
      max(case when col1='name3' then col2 end) name3
      from yourtable
      group by id


      But if you have an unknown number of columns, then you can use a prepared statement and create this dynamically:



      SET @sql = NULL;
      SELECT
      GROUP_CONCAT(DISTINCT
      CONCAT(
      'max(case when col1 = ''',
      col1,
      ''' then col2 end) AS ',
      col1
      )
      ) INTO @sql
      FROM yourtable;

      SET @sql = CONCAT('SELECT id, ', @sql, '
      FROM yourtable
      GROUP BY id');

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


      See SQL Fiddle with Demo






      share|improve this answer























        up vote
        6
        down vote










        up vote
        6
        down vote









        What you are attempting to do is a PIVOT MySQL does not have a PIVOT function so you can replicate this using a CASE and an aggregate function.



        If you have a known number of columns, then you can use a static version and hard-code the values. Similar to this (See SQL Fiddle with demo):



        select id,
        max(case when col1='name' then col2 end) name,
        max(case when col1='name2' then col2 end) name2,
        max(case when col1='name3' then col2 end) name3
        from yourtable
        group by id


        But if you have an unknown number of columns, then you can use a prepared statement and create this dynamically:



        SET @sql = NULL;
        SELECT
        GROUP_CONCAT(DISTINCT
        CONCAT(
        'max(case when col1 = ''',
        col1,
        ''' then col2 end) AS ',
        col1
        )
        ) INTO @sql
        FROM yourtable;

        SET @sql = CONCAT('SELECT id, ', @sql, '
        FROM yourtable
        GROUP BY id');

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


        See SQL Fiddle with Demo






        share|improve this answer












        What you are attempting to do is a PIVOT MySQL does not have a PIVOT function so you can replicate this using a CASE and an aggregate function.



        If you have a known number of columns, then you can use a static version and hard-code the values. Similar to this (See SQL Fiddle with demo):



        select id,
        max(case when col1='name' then col2 end) name,
        max(case when col1='name2' then col2 end) name2,
        max(case when col1='name3' then col2 end) name3
        from yourtable
        group by id


        But if you have an unknown number of columns, then you can use a prepared statement and create this dynamically:



        SET @sql = NULL;
        SELECT
        GROUP_CONCAT(DISTINCT
        CONCAT(
        'max(case when col1 = ''',
        col1,
        ''' then col2 end) AS ',
        col1
        )
        ) INTO @sql
        FROM yourtable;

        SET @sql = CONCAT('SELECT id, ', @sql, '
        FROM yourtable
        GROUP BY id');

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


        See SQL Fiddle with Demo







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 9 '12 at 20:54









        Taryn

        187k45284348




        187k45284348






















            up vote
            0
            down vote













            select id,
            max(if(tablename.columnname = 'name',tablename.columnname,null)) as namealise,
            max(if(tablename.columnname = 'name1',tablename.columnname,null)) as namealise1
            from table1, table2
            where table1.id = table2.id
            group by table1.id
            order by table1.id





            share|improve this answer























            • An explanation would be helpful. And consider using code formatting for improved readability.
              – Michael_B
              Oct 26 '16 at 17:46















            up vote
            0
            down vote













            select id,
            max(if(tablename.columnname = 'name',tablename.columnname,null)) as namealise,
            max(if(tablename.columnname = 'name1',tablename.columnname,null)) as namealise1
            from table1, table2
            where table1.id = table2.id
            group by table1.id
            order by table1.id





            share|improve this answer























            • An explanation would be helpful. And consider using code formatting for improved readability.
              – Michael_B
              Oct 26 '16 at 17:46













            up vote
            0
            down vote










            up vote
            0
            down vote









            select id,
            max(if(tablename.columnname = 'name',tablename.columnname,null)) as namealise,
            max(if(tablename.columnname = 'name1',tablename.columnname,null)) as namealise1
            from table1, table2
            where table1.id = table2.id
            group by table1.id
            order by table1.id





            share|improve this answer














            select id,
            max(if(tablename.columnname = 'name',tablename.columnname,null)) as namealise,
            max(if(tablename.columnname = 'name1',tablename.columnname,null)) as namealise1
            from table1, table2
            where table1.id = table2.id
            group by table1.id
            order by table1.id






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 24 '17 at 2:23









            Pang

            6,8191563101




            6,8191563101










            answered Oct 26 '16 at 17:22









            Shaneshwar Makone

            11




            11












            • An explanation would be helpful. And consider using code formatting for improved readability.
              – Michael_B
              Oct 26 '16 at 17:46


















            • An explanation would be helpful. And consider using code formatting for improved readability.
              – Michael_B
              Oct 26 '16 at 17:46
















            An explanation would be helpful. And consider using code formatting for improved readability.
            – Michael_B
            Oct 26 '16 at 17:46




            An explanation would be helpful. And consider using code formatting for improved readability.
            – Michael_B
            Oct 26 '16 at 17:46


















             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f12808189%2fsetting-column-values-as-column-names-in-the-sql-query-result%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Coverage of Google Street View

            Full-time equivalent

            Surfing