我有这张桌子:
textid | 情绪 | 日期 |
---|---|---|
1 | 否定 | 2020-01-02 |
2 | 正面 | 2020-01-02 |
3 | 中立 | 2020-01-02 |
4 | 否定 | 2020-01-02 |
5 | 否定 | 2021-08-10 |
6 | 正面 | 2018-10-22 |
7 | 否定 | 2021-03-10 |
8 | 中立 | 2019-11-30 |
9 | 否定 | 2019-12-29 |
而且我想计算 sentiment
随时间变化的不同值......以便稍后构建一个图表,我可以在其中比较三种情绪随时间的变化。
所以,给示例表...我需要这样的表:
日期 | countPositive | countNeutral | countNegative |
---|---|---|---|
2018-10-22 | 1 | 0 | 0 |
2019-11-30 | 0 | 1 | 0 |
2019-12-29 | 0 | 0 | 1 |
2020-02-01 | 1 | 1 | 2 |
2021-03-10 | 0 | 0 | 1 |
2021-08-01 | 0 | 0 | 1 |
谁能帮帮我?我不知道如何执行此 SQL 查询...
谢谢!
答案 0 :(得分:1)
使用条件聚合,在 Postgres 中的意思是 filter
:
select date,
count(*) filter (where sentiment = 'positive') as positive,
count(*) filter (where sentiment = 'neutral') as neutral,
count(*) filter (where sentiment = 'negative') as negative
from t
group by date;
答案 1 :(得分:0)
您可以使用按日期分组和过滤 count() :
select
date
, count(*) filter (where sentiment = 'positive') countPositive
, count(*) filter (where sentiment = 'neutral') countNeutral
, count(*) filter (where sentiment = 'negative') countNegative
from yourtable
group by date
如果日期列实际上是 date/time ,则需要先将其转换为日期:
select
date_trunc('day', now())
, count(*) filter (where sentiment = 'positive') countPositive
, count(*) filter (where sentiment = 'neutral') countNeutral
, count(*) filter (where sentiment = 'negative') countNegative
from yourtable
group by date_trunc('day', now())