将Pandas操作转换为SQL查询

时间:2018-07-26 15:03:48

标签: python sql postgresql

table = (df.groupby('name')['activity'].value_counts().unstack().fillna(0))

我有一个要创建的表,可以在python中创建它,但我想在sql中创建它以使它像下面这样:

activity tv football cooking chatting
name
chandler 0   0        3       2
monica   1   1        2       0
ross     3   2       1        1

我认为应该是这样,但我不能再进一步了。

SELECT name,
    COUNT(CASE WHEN END) AS ,
    COUNT(CASE WHEN END) AS
  FROM dataset
    GROUP BY name;

1 个答案:

答案 0 :(得分:2)

因此,您需要有条件的聚合:

SELECT name,
       SUM(CASE WHEN activity = 'tv' THEN 1 ELSE 0 END) AS tv,
       SUM(CASE WHEN activity = 'football' THEN 1 ELSE 0 END) AS football,
       SUM(CASE WHEN activity = 'cooking' THEN 1 ELSE 0 END) AS cooking,
       . . . 
FROM dataset
GROUP BY name;