select all values in 1 row from table where same value in column

时间:2018-02-03 09:13:01

标签: mysqli

I have rows in my database example

col1     col2      col3
test1   value1      5
test1   value2      10
test1   value3      12
test2   value1      2
test2   value2      8
test2   value3      10
test3   value1      8
test3   value2      7
test3   value3      11

i want select all values in 1 row from my table where same value in column

col1 value1 value2 value3
test1   5      10     12
test2   2      8     10
test3   8      7     11

Sorry If my english is bad

After Edited : my query :

SELECT  T.`col1`,

        CASE 
            WHEN T.`col2`='value1'  
            THEN T.`col3` 
        END
     AS 'value1',

        CASE 
            WHEN T.`col2`='value2' 
            THEN T.`col3` 
        END
     AS 'value2',        
     CASE 
            WHEN T.`col2`='value3' 
            THEN T.`col3` 
        END
     AS 'value3',

FROM    table T
GROUP BY T.`col1`;

1 个答案:

答案 0 :(得分:0)

Your query is close to being correct, except that you forgot to take aggregates of your CASE expressions:

SELECT
    col1,
    MAX(CASE WHEN col2 = 'value1' THEN col3 END) AS value1,
    MAX(CASE WHEN col2 = 'value2' THEN col3 END) AS value2,
    MAX(CASE WHEN col2 = 'value3' THEN col3 END) AS value3
FROM
    yourTable
GROUP BY
    col1;