How can I do Join two tables and do Pivot dynamically











up vote
1
down vote

favorite












I have two tables, A and B



A ( id, name )

B ( a_id, key, value )



table with some values



**A table**

-----------------------------
id | name
-----------------------------
1 | sorabh
2 | john
-----------------------------

**B table**

-------------------------------------------------
a_id | key | value
-------------------------------------------------
1 | looks | handsome
1 | lazy | yes
1 | car | honda
2 | phone | 948373221
1 | email | some@ccid.com
-------------------------------------------------


Now what i am trying to achieve is a follow, with single query, inner join, cross join, etc.



SELECT * FROM A
CROSS JOIN B WHERE A.id=1


and result must be something like



--------------------------------------------------------------------
id | name | looks | lazy | car | email
--------------------------------------------------------------------
1 | sorabh | handsome | yes | honda | some@ccid.com
--------------------------------------------------------------------









share|improve this question
























  • you need to use pivot
    – user4321
    Nov 9 at 16:56










  • It is left join. Result would be row wise (columns would be id, name, a_id, key, value). Your output is called as a cross tab, pivot table. How to do that is based on the backend you are using. For example for postgreSQL check tablefunc extension (this type of data is more suited to NoSQL).
    – Cetin Basoz
    Nov 9 at 16:57










  • Consider handling display issues in application code
    – Strawberry
    Nov 9 at 17:03










  • The problem with this is that your Table B is going to have a dynamic value. Your resultset for proposed query would therefore have to have a column for each distinct "key" row value for each Id. So ID 1 would have a "phone" column but a null value. As your database grows, so will the null values.
    – Lucky
    Nov 9 at 18:44















up vote
1
down vote

favorite












I have two tables, A and B



A ( id, name )

B ( a_id, key, value )



table with some values



**A table**

-----------------------------
id | name
-----------------------------
1 | sorabh
2 | john
-----------------------------

**B table**

-------------------------------------------------
a_id | key | value
-------------------------------------------------
1 | looks | handsome
1 | lazy | yes
1 | car | honda
2 | phone | 948373221
1 | email | some@ccid.com
-------------------------------------------------


Now what i am trying to achieve is a follow, with single query, inner join, cross join, etc.



SELECT * FROM A
CROSS JOIN B WHERE A.id=1


and result must be something like



--------------------------------------------------------------------
id | name | looks | lazy | car | email
--------------------------------------------------------------------
1 | sorabh | handsome | yes | honda | some@ccid.com
--------------------------------------------------------------------









share|improve this question
























  • you need to use pivot
    – user4321
    Nov 9 at 16:56










  • It is left join. Result would be row wise (columns would be id, name, a_id, key, value). Your output is called as a cross tab, pivot table. How to do that is based on the backend you are using. For example for postgreSQL check tablefunc extension (this type of data is more suited to NoSQL).
    – Cetin Basoz
    Nov 9 at 16:57










  • Consider handling display issues in application code
    – Strawberry
    Nov 9 at 17:03










  • The problem with this is that your Table B is going to have a dynamic value. Your resultset for proposed query would therefore have to have a column for each distinct "key" row value for each Id. So ID 1 would have a "phone" column but a null value. As your database grows, so will the null values.
    – Lucky
    Nov 9 at 18:44













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have two tables, A and B



A ( id, name )

B ( a_id, key, value )



table with some values



**A table**

-----------------------------
id | name
-----------------------------
1 | sorabh
2 | john
-----------------------------

**B table**

-------------------------------------------------
a_id | key | value
-------------------------------------------------
1 | looks | handsome
1 | lazy | yes
1 | car | honda
2 | phone | 948373221
1 | email | some@ccid.com
-------------------------------------------------


Now what i am trying to achieve is a follow, with single query, inner join, cross join, etc.



SELECT * FROM A
CROSS JOIN B WHERE A.id=1


and result must be something like



--------------------------------------------------------------------
id | name | looks | lazy | car | email
--------------------------------------------------------------------
1 | sorabh | handsome | yes | honda | some@ccid.com
--------------------------------------------------------------------









share|improve this question















I have two tables, A and B



A ( id, name )

B ( a_id, key, value )



table with some values



**A table**

-----------------------------
id | name
-----------------------------
1 | sorabh
2 | john
-----------------------------

**B table**

-------------------------------------------------
a_id | key | value
-------------------------------------------------
1 | looks | handsome
1 | lazy | yes
1 | car | honda
2 | phone | 948373221
1 | email | some@ccid.com
-------------------------------------------------


Now what i am trying to achieve is a follow, with single query, inner join, cross join, etc.



SELECT * FROM A
CROSS JOIN B WHERE A.id=1


and result must be something like



--------------------------------------------------------------------
id | name | looks | lazy | car | email
--------------------------------------------------------------------
1 | sorabh | handsome | yes | honda | some@ccid.com
--------------------------------------------------------------------






mysql sql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 23:19









D-Shih

24.4k61431




24.4k61431










asked Nov 9 at 16:52









sorabh86

266211




266211












  • you need to use pivot
    – user4321
    Nov 9 at 16:56










  • It is left join. Result would be row wise (columns would be id, name, a_id, key, value). Your output is called as a cross tab, pivot table. How to do that is based on the backend you are using. For example for postgreSQL check tablefunc extension (this type of data is more suited to NoSQL).
    – Cetin Basoz
    Nov 9 at 16:57










  • Consider handling display issues in application code
    – Strawberry
    Nov 9 at 17:03










  • The problem with this is that your Table B is going to have a dynamic value. Your resultset for proposed query would therefore have to have a column for each distinct "key" row value for each Id. So ID 1 would have a "phone" column but a null value. As your database grows, so will the null values.
    – Lucky
    Nov 9 at 18:44


















  • you need to use pivot
    – user4321
    Nov 9 at 16:56










  • It is left join. Result would be row wise (columns would be id, name, a_id, key, value). Your output is called as a cross tab, pivot table. How to do that is based on the backend you are using. For example for postgreSQL check tablefunc extension (this type of data is more suited to NoSQL).
    – Cetin Basoz
    Nov 9 at 16:57










  • Consider handling display issues in application code
    – Strawberry
    Nov 9 at 17:03










  • The problem with this is that your Table B is going to have a dynamic value. Your resultset for proposed query would therefore have to have a column for each distinct "key" row value for each Id. So ID 1 would have a "phone" column but a null value. As your database grows, so will the null values.
    – Lucky
    Nov 9 at 18:44
















you need to use pivot
– user4321
Nov 9 at 16:56




you need to use pivot
– user4321
Nov 9 at 16:56












It is left join. Result would be row wise (columns would be id, name, a_id, key, value). Your output is called as a cross tab, pivot table. How to do that is based on the backend you are using. For example for postgreSQL check tablefunc extension (this type of data is more suited to NoSQL).
– Cetin Basoz
Nov 9 at 16:57




It is left join. Result would be row wise (columns would be id, name, a_id, key, value). Your output is called as a cross tab, pivot table. How to do that is based on the backend you are using. For example for postgreSQL check tablefunc extension (this type of data is more suited to NoSQL).
– Cetin Basoz
Nov 9 at 16:57












Consider handling display issues in application code
– Strawberry
Nov 9 at 17:03




Consider handling display issues in application code
– Strawberry
Nov 9 at 17:03












The problem with this is that your Table B is going to have a dynamic value. Your resultset for proposed query would therefore have to have a column for each distinct "key" row value for each Id. So ID 1 would have a "phone" column but a null value. As your database grows, so will the null values.
– Lucky
Nov 9 at 18:44




The problem with this is that your Table B is going to have a dynamic value. Your resultset for proposed query would therefore have to have a column for each distinct "key" row value for each Id. So ID 1 would have a "phone" column but a null value. As your database grows, so will the null values.
– Lucky
Nov 9 at 18:44












5 Answers
5






active

oldest

votes

















up vote
5
down vote













Assuming the id column of table a is a primary key column and table b has a composite unique key for a_id, key column-combination or has no duplicates even if there's no such constraint, a correlated subquery may be used as :



select a.*,
( select value from b where b.a_id = a.id and b.key = 'looks' ) as looks,
( select value from b where b.a_id = a.id and b.key = 'lazy' ) as lazy,
( select value from b where b.a_id = a.id and b.key = 'car' ) as car,
( select value from b where b.a_id = a.id and b.key = 'email' ) as email
from a
where a.id = 1;





share|improve this answer























  • That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
    – sorabh86
    Nov 9 at 18:33






  • 1




    @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
    – Barbaros Özhan
    Nov 9 at 18:36




















up vote
3
down vote













You can try to use mysql dynamic pivot to make you expect.



Do pivot with condition aggregate function



Prepared your SQL statements and use to execute your SQL EXECUTE stmt; dynamically.



SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when `key`= ''',
`key`,
''' then `value` end) AS ',
`key`
)
) INTO @sql
FROM A join B on a.id=b.a_id
WHERE b.a_id = 1;

SET @sql = CONCAT('select a.id,a.name, ', @sql, '
FROM A join B on a.id=b.a_id
WHERE b.a_id = 1
group by a.name');

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


sqlfiddle



Result



id  name    looks       laz   car   email
1 sorabh handsome yes honda some@ccid.com


Refer



Dynamic pivot tables






share|improve this answer






























    up vote
    2
    down vote













    use case when with max()



    select a.name,
    max(case when key='looks' then value end) as looks,
    max(case when key='lazy' then value end) as yes,
    max(case when key='car' then value end) as car,
    max(case when key='email' then value end) as email,
    tablea a join tableb b on a.id=b.a_id
    group by a.name





    share|improve this answer





















    • What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
      – sorabh86
      Nov 9 at 17:22


















    up vote
    2
    down vote













    Try this



    WITH CTE_A AS (
    SELECT
    A.id,
    A.name,
    B.key,
    B.value
    FROM A
    INNER JOIN B ON A.id = B.a_id
    )
    SELECT *
    FROM
    CTE_A
    PIVOT (max(value) FOR key IN (looks, lazy, car,phone,email)) P
    ;


    if the key and value are dynamic use the below



    DECLARE @colsToPivot AS NVARCHAR(MAX),
    @sqlStmt AS NVARCHAR(MAX)
    select @colsToPivot = STUFF((SELECT distinct ',' + QUOTENAME(key)
    from B
    FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')


    set @sqlStmt = 'WITH CTE_A AS (
    SELECT
    A.id,
    A.name,
    B.key,
    B.value
    FROM A
    INNER JOIN B ON A.id = B.a_id
    )
    SELECT *
    FROM
    CTE_A
    PIVOT (max(value) FOR key IN (' + @colsToPivot +')) P'

    execute(@sqlStmt)





    share|improve this answer






























      up vote
      -3
      down vote













      SELECT * FROM B LEFT JOIN A WHERE A.id=B.a_id AND A.id=1





      share|improve this answer























        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%2f53230096%2fhow-can-i-do-join-two-tables-and-do-pivot-dynamically%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        5
        down vote













        Assuming the id column of table a is a primary key column and table b has a composite unique key for a_id, key column-combination or has no duplicates even if there's no such constraint, a correlated subquery may be used as :



        select a.*,
        ( select value from b where b.a_id = a.id and b.key = 'looks' ) as looks,
        ( select value from b where b.a_id = a.id and b.key = 'lazy' ) as lazy,
        ( select value from b where b.a_id = a.id and b.key = 'car' ) as car,
        ( select value from b where b.a_id = a.id and b.key = 'email' ) as email
        from a
        where a.id = 1;





        share|improve this answer























        • That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
          – sorabh86
          Nov 9 at 18:33






        • 1




          @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
          – Barbaros Özhan
          Nov 9 at 18:36

















        up vote
        5
        down vote













        Assuming the id column of table a is a primary key column and table b has a composite unique key for a_id, key column-combination or has no duplicates even if there's no such constraint, a correlated subquery may be used as :



        select a.*,
        ( select value from b where b.a_id = a.id and b.key = 'looks' ) as looks,
        ( select value from b where b.a_id = a.id and b.key = 'lazy' ) as lazy,
        ( select value from b where b.a_id = a.id and b.key = 'car' ) as car,
        ( select value from b where b.a_id = a.id and b.key = 'email' ) as email
        from a
        where a.id = 1;





        share|improve this answer























        • That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
          – sorabh86
          Nov 9 at 18:33






        • 1




          @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
          – Barbaros Özhan
          Nov 9 at 18:36















        up vote
        5
        down vote










        up vote
        5
        down vote









        Assuming the id column of table a is a primary key column and table b has a composite unique key for a_id, key column-combination or has no duplicates even if there's no such constraint, a correlated subquery may be used as :



        select a.*,
        ( select value from b where b.a_id = a.id and b.key = 'looks' ) as looks,
        ( select value from b where b.a_id = a.id and b.key = 'lazy' ) as lazy,
        ( select value from b where b.a_id = a.id and b.key = 'car' ) as car,
        ( select value from b where b.a_id = a.id and b.key = 'email' ) as email
        from a
        where a.id = 1;





        share|improve this answer














        Assuming the id column of table a is a primary key column and table b has a composite unique key for a_id, key column-combination or has no duplicates even if there's no such constraint, a correlated subquery may be used as :



        select a.*,
        ( select value from b where b.a_id = a.id and b.key = 'looks' ) as looks,
        ( select value from b where b.a_id = a.id and b.key = 'lazy' ) as lazy,
        ( select value from b where b.a_id = a.id and b.key = 'car' ) as car,
        ( select value from b where b.a_id = a.id and b.key = 'email' ) as email
        from a
        where a.id = 1;






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 9 at 18:30

























        answered Nov 9 at 17:59









        Barbaros Özhan

        11.4k71530




        11.4k71530












        • That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
          – sorabh86
          Nov 9 at 18:33






        • 1




          @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
          – Barbaros Özhan
          Nov 9 at 18:36




















        • That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
          – sorabh86
          Nov 9 at 18:33






        • 1




          @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
          – Barbaros Özhan
          Nov 9 at 18:36


















        That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
        – sorabh86
        Nov 9 at 18:33




        That is going to exactly worked, but i want to know, here we know what are the key and values, but is that possible in single query where we don't know looks, lazy, car, email, etc, could be anything and could be multiple or single entry related to it, to query in a single statement with sub statement, to add columns based on key ?
        – sorabh86
        Nov 9 at 18:33




        1




        1




        @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
        – Barbaros Özhan
        Nov 9 at 18:36






        @sorabh86 I understand what you mean, I've never met such a fully dynamical way, and I believe there's no, unfortunately.
        – Barbaros Özhan
        Nov 9 at 18:36














        up vote
        3
        down vote













        You can try to use mysql dynamic pivot to make you expect.



        Do pivot with condition aggregate function



        Prepared your SQL statements and use to execute your SQL EXECUTE stmt; dynamically.



        SET @sql = NULL;
        SELECT
        GROUP_CONCAT(DISTINCT
        CONCAT(
        'max(case when `key`= ''',
        `key`,
        ''' then `value` end) AS ',
        `key`
        )
        ) INTO @sql
        FROM A join B on a.id=b.a_id
        WHERE b.a_id = 1;

        SET @sql = CONCAT('select a.id,a.name, ', @sql, '
        FROM A join B on a.id=b.a_id
        WHERE b.a_id = 1
        group by a.name');

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


        sqlfiddle



        Result



        id  name    looks       laz   car   email
        1 sorabh handsome yes honda some@ccid.com


        Refer



        Dynamic pivot tables






        share|improve this answer



























          up vote
          3
          down vote













          You can try to use mysql dynamic pivot to make you expect.



          Do pivot with condition aggregate function



          Prepared your SQL statements and use to execute your SQL EXECUTE stmt; dynamically.



          SET @sql = NULL;
          SELECT
          GROUP_CONCAT(DISTINCT
          CONCAT(
          'max(case when `key`= ''',
          `key`,
          ''' then `value` end) AS ',
          `key`
          )
          ) INTO @sql
          FROM A join B on a.id=b.a_id
          WHERE b.a_id = 1;

          SET @sql = CONCAT('select a.id,a.name, ', @sql, '
          FROM A join B on a.id=b.a_id
          WHERE b.a_id = 1
          group by a.name');

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


          sqlfiddle



          Result



          id  name    looks       laz   car   email
          1 sorabh handsome yes honda some@ccid.com


          Refer



          Dynamic pivot tables






          share|improve this answer

























            up vote
            3
            down vote










            up vote
            3
            down vote









            You can try to use mysql dynamic pivot to make you expect.



            Do pivot with condition aggregate function



            Prepared your SQL statements and use to execute your SQL EXECUTE stmt; dynamically.



            SET @sql = NULL;
            SELECT
            GROUP_CONCAT(DISTINCT
            CONCAT(
            'max(case when `key`= ''',
            `key`,
            ''' then `value` end) AS ',
            `key`
            )
            ) INTO @sql
            FROM A join B on a.id=b.a_id
            WHERE b.a_id = 1;

            SET @sql = CONCAT('select a.id,a.name, ', @sql, '
            FROM A join B on a.id=b.a_id
            WHERE b.a_id = 1
            group by a.name');

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


            sqlfiddle



            Result



            id  name    looks       laz   car   email
            1 sorabh handsome yes honda some@ccid.com


            Refer



            Dynamic pivot tables






            share|improve this answer














            You can try to use mysql dynamic pivot to make you expect.



            Do pivot with condition aggregate function



            Prepared your SQL statements and use to execute your SQL EXECUTE stmt; dynamically.



            SET @sql = NULL;
            SELECT
            GROUP_CONCAT(DISTINCT
            CONCAT(
            'max(case when `key`= ''',
            `key`,
            ''' then `value` end) AS ',
            `key`
            )
            ) INTO @sql
            FROM A join B on a.id=b.a_id
            WHERE b.a_id = 1;

            SET @sql = CONCAT('select a.id,a.name, ', @sql, '
            FROM A join B on a.id=b.a_id
            WHERE b.a_id = 1
            group by a.name');

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


            sqlfiddle



            Result



            id  name    looks       laz   car   email
            1 sorabh handsome yes honda some@ccid.com


            Refer



            Dynamic pivot tables







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 9 at 23:14

























            answered Nov 9 at 23:09









            D-Shih

            24.4k61431




            24.4k61431






















                up vote
                2
                down vote













                use case when with max()



                select a.name,
                max(case when key='looks' then value end) as looks,
                max(case when key='lazy' then value end) as yes,
                max(case when key='car' then value end) as car,
                max(case when key='email' then value end) as email,
                tablea a join tableb b on a.id=b.a_id
                group by a.name





                share|improve this answer





















                • What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
                  – sorabh86
                  Nov 9 at 17:22















                up vote
                2
                down vote













                use case when with max()



                select a.name,
                max(case when key='looks' then value end) as looks,
                max(case when key='lazy' then value end) as yes,
                max(case when key='car' then value end) as car,
                max(case when key='email' then value end) as email,
                tablea a join tableb b on a.id=b.a_id
                group by a.name





                share|improve this answer





















                • What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
                  – sorabh86
                  Nov 9 at 17:22













                up vote
                2
                down vote










                up vote
                2
                down vote









                use case when with max()



                select a.name,
                max(case when key='looks' then value end) as looks,
                max(case when key='lazy' then value end) as yes,
                max(case when key='car' then value end) as car,
                max(case when key='email' then value end) as email,
                tablea a join tableb b on a.id=b.a_id
                group by a.name





                share|improve this answer












                use case when with max()



                select a.name,
                max(case when key='looks' then value end) as looks,
                max(case when key='lazy' then value end) as yes,
                max(case when key='car' then value end) as car,
                max(case when key='email' then value end) as email,
                tablea a join tableb b on a.id=b.a_id
                group by a.name






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 9 at 17:05









                Zaynul Abadin Tuhin

                10.8k2731




                10.8k2731












                • What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
                  – sorabh86
                  Nov 9 at 17:22


















                • What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
                  – sorabh86
                  Nov 9 at 17:22
















                What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
                – sorabh86
                Nov 9 at 17:22




                What if key and value are dynamic, by the way it didn't worked. Thanks anyways.
                – sorabh86
                Nov 9 at 17:22










                up vote
                2
                down vote













                Try this



                WITH CTE_A AS (
                SELECT
                A.id,
                A.name,
                B.key,
                B.value
                FROM A
                INNER JOIN B ON A.id = B.a_id
                )
                SELECT *
                FROM
                CTE_A
                PIVOT (max(value) FOR key IN (looks, lazy, car,phone,email)) P
                ;


                if the key and value are dynamic use the below



                DECLARE @colsToPivot AS NVARCHAR(MAX),
                @sqlStmt AS NVARCHAR(MAX)
                select @colsToPivot = STUFF((SELECT distinct ',' + QUOTENAME(key)
                from B
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)')
                ,1,1,'')


                set @sqlStmt = 'WITH CTE_A AS (
                SELECT
                A.id,
                A.name,
                B.key,
                B.value
                FROM A
                INNER JOIN B ON A.id = B.a_id
                )
                SELECT *
                FROM
                CTE_A
                PIVOT (max(value) FOR key IN (' + @colsToPivot +')) P'

                execute(@sqlStmt)





                share|improve this answer



























                  up vote
                  2
                  down vote













                  Try this



                  WITH CTE_A AS (
                  SELECT
                  A.id,
                  A.name,
                  B.key,
                  B.value
                  FROM A
                  INNER JOIN B ON A.id = B.a_id
                  )
                  SELECT *
                  FROM
                  CTE_A
                  PIVOT (max(value) FOR key IN (looks, lazy, car,phone,email)) P
                  ;


                  if the key and value are dynamic use the below



                  DECLARE @colsToPivot AS NVARCHAR(MAX),
                  @sqlStmt AS NVARCHAR(MAX)
                  select @colsToPivot = STUFF((SELECT distinct ',' + QUOTENAME(key)
                  from B
                  FOR XML PATH(''), TYPE
                  ).value('.', 'NVARCHAR(MAX)')
                  ,1,1,'')


                  set @sqlStmt = 'WITH CTE_A AS (
                  SELECT
                  A.id,
                  A.name,
                  B.key,
                  B.value
                  FROM A
                  INNER JOIN B ON A.id = B.a_id
                  )
                  SELECT *
                  FROM
                  CTE_A
                  PIVOT (max(value) FOR key IN (' + @colsToPivot +')) P'

                  execute(@sqlStmt)





                  share|improve this answer

























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    Try this



                    WITH CTE_A AS (
                    SELECT
                    A.id,
                    A.name,
                    B.key,
                    B.value
                    FROM A
                    INNER JOIN B ON A.id = B.a_id
                    )
                    SELECT *
                    FROM
                    CTE_A
                    PIVOT (max(value) FOR key IN (looks, lazy, car,phone,email)) P
                    ;


                    if the key and value are dynamic use the below



                    DECLARE @colsToPivot AS NVARCHAR(MAX),
                    @sqlStmt AS NVARCHAR(MAX)
                    select @colsToPivot = STUFF((SELECT distinct ',' + QUOTENAME(key)
                    from B
                    FOR XML PATH(''), TYPE
                    ).value('.', 'NVARCHAR(MAX)')
                    ,1,1,'')


                    set @sqlStmt = 'WITH CTE_A AS (
                    SELECT
                    A.id,
                    A.name,
                    B.key,
                    B.value
                    FROM A
                    INNER JOIN B ON A.id = B.a_id
                    )
                    SELECT *
                    FROM
                    CTE_A
                    PIVOT (max(value) FOR key IN (' + @colsToPivot +')) P'

                    execute(@sqlStmt)





                    share|improve this answer














                    Try this



                    WITH CTE_A AS (
                    SELECT
                    A.id,
                    A.name,
                    B.key,
                    B.value
                    FROM A
                    INNER JOIN B ON A.id = B.a_id
                    )
                    SELECT *
                    FROM
                    CTE_A
                    PIVOT (max(value) FOR key IN (looks, lazy, car,phone,email)) P
                    ;


                    if the key and value are dynamic use the below



                    DECLARE @colsToPivot AS NVARCHAR(MAX),
                    @sqlStmt AS NVARCHAR(MAX)
                    select @colsToPivot = STUFF((SELECT distinct ',' + QUOTENAME(key)
                    from B
                    FOR XML PATH(''), TYPE
                    ).value('.', 'NVARCHAR(MAX)')
                    ,1,1,'')


                    set @sqlStmt = 'WITH CTE_A AS (
                    SELECT
                    A.id,
                    A.name,
                    B.key,
                    B.value
                    FROM A
                    INNER JOIN B ON A.id = B.a_id
                    )
                    SELECT *
                    FROM
                    CTE_A
                    PIVOT (max(value) FOR key IN (' + @colsToPivot +')) P'

                    execute(@sqlStmt)






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 9 at 17:57

























                    answered Nov 9 at 17:07









                    user4321

                    387722




                    387722






















                        up vote
                        -3
                        down vote













                        SELECT * FROM B LEFT JOIN A WHERE A.id=B.a_id AND A.id=1





                        share|improve this answer



























                          up vote
                          -3
                          down vote













                          SELECT * FROM B LEFT JOIN A WHERE A.id=B.a_id AND A.id=1





                          share|improve this answer

























                            up vote
                            -3
                            down vote










                            up vote
                            -3
                            down vote









                            SELECT * FROM B LEFT JOIN A WHERE A.id=B.a_id AND A.id=1





                            share|improve this answer














                            SELECT * FROM B LEFT JOIN A WHERE A.id=B.a_id AND A.id=1






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 9 at 22:56









                            Lee Mac

                            3,05021136




                            3,05021136










                            answered Nov 9 at 17:02









                            JIm Rolt

                            11




                            11






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53230096%2fhow-can-i-do-join-two-tables-and-do-pivot-dynamically%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

                                Schultheiß

                                Liste der Kulturdenkmale in Wilsdruff

                                Android Play Services Check