简体   繁体   中英

SQL command to group field and create new column

I have a table: name, date, url, no , url includes "facebook","twitter","other" .

How can I generate a new table: date, facebook, twitter, total, unique name , such that, grouping by date, facebook field is the sum of the no WHERE url="facebook" , and same as twitter ; total field is the sum of the no of all; unique name counts the distinct name number?

You can use SUM/CASE for this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM