简体   繁体   中英

How to get the total number of positive, neutral and negative tweets in SQL Server?

I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 --- --- --- --- --- 700 --- --- --- --- 800

The schema for the tables involved in this query:

T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText 

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount, 
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount, 
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6
SELECT SUM(CASE WHEN ts.SentimentLabel = 'Positive' THEN 1 ELSE 0 END) AS PositivesCount, 
       SUM(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN 1 ELSE 0 END) AS NeutralsCount, 
       SUM(CASE WHEN ts.SentimentLabel = 'Negative' THEN 1 ELSE 0 END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6

Why not just use:

SELECT COUNT(*), SentimentLabel 
FROM SentimentLabel
GROUP BY SentimentLabel

I don't see why you need T_tweet for this. The JOIN seems unnecessary:

SELECT SUM(CASE WHEN ts.SentimentLabel = 'Positive' THEN 1 ELSE 0
           END) as PositiveCount, 
       SUM(CASE WHEN ts.SentimentLabel = 'Neutral' THEN 1 ELSE 0
           END) as NeutralCount, 
       SUM(CASE WHEN ts.SentimentLabel = 'Negative' THEN 1 ELSE 0
           END) as NegativeCount
FROM dbo.T_TweetSentiment ts
WHERE ts.TypeId = 6;

The only reason you would need the join is if you had TweetId s in T_TweetSentiment that are not in the tweets table. That seems unlikely (and would be a sign of an issue with the data design).

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