SQL命令将字段分组并创建新列

时间:2012-01-30 22:22:00

标签: mysql sql

我有一张桌子:name, date, url, nourl包含"facebook","twitter","other"

如何生成新表:date, facebook, twitter, total, unique name,以便按日期分组facebook字段是no WHERE url="facebook"的总和,并且相同twitter; total字段是所有no的总和; unique name计算不同的name数字?

1 个答案:

答案 0 :(得分:4)

您可以使用SUM / CASE。

SELECT Date,
       SUM(case when url = 'facebook' then no else 0 end) as facebook,
       SUM(case when url = 'twitter' then no  else 0 end) as twitter,
       SUM(no) total,
       COUNT(DISTINCT NAME) as `unique name`
FROM
      table
GROUP BY
      date