如何在SQL中转置表

时间:2015-07-14 07:06:38

标签: mysql sql transpose

表abc:

cookie_id   key         time
123         search      5/6/15
123         search      5/7/15
123         homepage    5/6/15
123         book        5/12/15
234         homepage    5/7/15
234         search      5/8/15

预期结果如下:

cookie_id   homepage    search     book
123          5/6/15     
123                     5/6/15  
123                     5/7/15  
123                               5/12/15
234          5/7/15     
234                     5/8/15  

如何使用tableabc ????

制作预期的结果表

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT 
    `Cookie_id`,
    (CASE WHEN `key` = 'homepage' THEN `time` END) AS `homepage`,
    (CASE WHEN `key` = 'search' THEN `time` END) AS `search`,
    (CASE WHEN `key` = 'book' THEN `time` END) AS `book`
FROM
    `tableabc`

答案 1 :(得分:1)

使用case语句获得所需的结果。

SELECT cookie_id,
       CASE WHEN key = 'search' THEN time ELSE NULL END as search, -- You can replace NULL with empty string
       CASE WHEN key = 'homepage' THEN time ELSE NULL END as homepage,
       CASE WHEN key = 'book' THEN time ELSE NULL END as book
FROM   Yourtable