Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine gridview rows and eliminate duplicates

I have 2 tables:

Table 1

id   question   customerId
1     bla1         1
2     bla2         2    

Table 2

id    customerId    Key         Value
1      1           firstname    John
2      1           lastname     Doe
3      2           firstname    Billy
4      2           lastname     Jones

I need to get my gridview to show:

Row 1: John Doe        Bla1
Row 2: Billy Jones     Bla2

Currently it shows: (but I dont want it like this):

Row 1: John      Bla1
Row 2: Doe       Bla1
Row 3: Billy     Bla2
Row 4: Jones     Bla2

I think I have tried everything and could use your help! Thanks.

like image 439
mlg74 Avatar asked Jan 25 '26 03:01

mlg74


1 Answers

SELECT  [firstname],[lastname], question
FROM
        (
            SELECT  a.question, b.[key], b.[value]
            FROM    Table1 a
                    INNER JOIN Table2 b
                        ON a.customerID = b.CustomerID
        ) org
        PIVOT
        (
            MAX([value])
            FOR [KEY] IN ([firstname],[lastname])
        ) pvt
  • SQLFiddle Demo

OUTPUT

╔═══════════╦══════════╦══════════╗
║ FIRSTNAME ║ LASTNAME ║ QUESTION ║
╠═══════════╬══════════╬══════════╣
║ John      ║ Doe      ║ bla1     ║
║ Billy     ║ Jones    ║ bla2     ║
╚═══════════╩══════════╩══════════╝
like image 80
John Woo Avatar answered Jan 26 '26 18:01

John Woo