Counting the number of mention depending on sentiment SQL

爱⌒轻易说出口 提交于 2020-08-10 19:24:09

问题


Apologies if this is a duplicate of anything, I wasn't finding answers which particularly did what I wanted.

I'm trying to write a SQL query which will return the count of rows which contain a positive, negative or neutral sentiment on one of the candidates in the dataset.

Here is a screenshot for reference

Sentiment is one column but the values in it define the tweet to be positive, negative, or neutral. my goal is to have the query return something like this

if anyone could give me an example on how to do this, I'd appreciate!


回答1:


try using specific COUNT() functions in your query like this.

SELECT name as `Candidate Name`, 
    COUNT(CASE WHEN sentiment='Negative' THEN 1 END) AS `Negative`,
    COUNT(CASE WHEN sentiment='Positive' THEN 1 END) AS `Positive`,
    COUNT(CASE WHEN sentiment='Neutral' THEN 1 END) AS `Neutral`,
    COUNT(*) AS `Total`

FROM [table]
    
GROUP BY candidate



回答2:


I like using IF()'s or CASE WHEN's to solve this type of thing. Pivots are sometimes time consuming to think through.

SELECT
  Name as CandidateName,
  SUM(IF(Sentiment = 'N', 1, 0)) as Negative,
  SUM(IF(Sentiment = 'Y', 1, 0)) as Positive,
  SUM(IF(Sentiment = 'N', 1, 0)) as Neutral
  COUNT(*) as Total
FROM [TABLE]
GROUP BY
  Name

To use t-SQL, or to just use CASE WHEN's, that same code could look like:

SELECT
  Name as CandidateName,
  SUM(CASE WHEN Sentiment = 'N' THEN 1 ELSE 0 END) as Negative,
  SUM(CASE WHEN Sentiment = 'Y' THEN 1 ELSE 0 END) as Positive,
  SUM(CASE WHEN Sentiment = 'N' THEN 1 ELSE 0 END) as Neutral
  COUNT(*) as Total
FROM [TABLE]
GROUP BY
  Name


来源:https://stackoverflow.com/questions/63023991/counting-the-number-of-mention-depending-on-sentiment-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!