Sql 如何选择WHERE语句与其他语句不同的内容

Sql 如何选择WHERE语句与其他语句不同的内容,sql,pivot,Sql,Pivot,我想做的是: 我在SQL中创建了一个透视表,其中我创建了几个列,其中包含用户帐户、每个日期的合计金额等。这些列都具有相同的where条件 但是,我想创建另一个列,其中包含过去30天的金额,该列的条件是WHERE date>=CURRENT\u TIMESTAMP-30 如何在具有不同条件的同一表中创建选择 例如: 我有这个: 我想做一个像这样的透视表 除了最后一列之外,我已经完成了所有操作-它需要使用条件WHERE date>=CURRENT\u TIMESTAMP-30对金额求和 我的其他

我想做的是:

我在SQL中创建了一个透视表,其中我创建了几个列,其中包含用户帐户、每个日期的合计金额等。这些列都具有相同的where条件

但是,我想创建另一个列,其中包含过去30天的金额,该列的条件是
WHERE date>=CURRENT\u TIMESTAMP-30

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

例如:

我有这个:

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

除了最后一列之外,我已经完成了所有操作-它需要使用条件
WHERE date>=CURRENT\u TIMESTAMP-30
对金额求和

我的其他列将具有条件
WHERE date>='20200201'

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


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

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

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;

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

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

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;

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

您的数据库是什么?你能提供一些样本数据吗?以及预期的结果。对不起,我是新来的。我编辑了这篇文章,其中包括了我所拥有的和我的问题所在。很好,但仍然缺少数据库。是Oracle、SQLServer、MySQL还是?你的数据库是什么?你能提供一些样本数据吗?以及预期的结果。对不起,我是新来的。我编辑了这篇文章,其中包括了我所拥有的和我的问题所在。很好,但仍然缺少数据库。是Oracle、SQLServer、MySQL还是?