首页 > 解决方案 > 如何从其他地方选择具有不同 WHERE 语句的东西

问题描述

我想做的是:

我在 SQL 中创建了一个数据透视表,在其中创建了一些包含用户帐户的列、每个日期的总和等。这些列都将具有相同的 WHERE 条件。

但是,我想创建另一个带有最近 30 天金额的列,该列将带有条件WHERE date >= CURRENT_TIMESTAMP -30

如何在同一个表中创建具有不同条件的选择?

例如:

我有这个:

这个

我想做一个像这样的数据透视表

那

除了最后一列之外,我已经完成了所有内容 - 它需要将金额与条件相加WHERE date >= CURRENT_TIMESTAMP -30

我的其他专栏将有条件WHERE date >= '20200201'

我已经将数据透视表中的天数定义为当月的天数,而最后一列需要包含过去 30 天的所有内容,因此不仅限于当月。

如何选择“过去 30 天的总计”列有自己的条件,与其他列不同?

标签: sqlpivot

解决方案


日期函数因数据库而异,但想法如下:

select user,
       sum(case when extract(day from date) = 1 then amount end) as day_1,
       sum(case when extract(day from date) = 2 then amount end) as day_2,
       sum(case when extract(day from date) = 3 then amount end) as day_3,
       sum(case when extract(year from date) = extract(year from current_date) and
                     extract(month from date) = extract(month from current_date)
                then amount
           end) as month_total,
       sum(case when date >= current_date - interval '30 da' then amount end) as last_30_days
from t
group by user;

确切的功能取决于您使用的数据库。


推荐阅读