sql - 如何从其他地方选择具有不同 WHERE 语句的东西
问题描述
我想做的是:
我在 SQL 中创建了一个数据透视表,在其中创建了一些包含用户帐户的列、每个日期的总和等。这些列都将具有相同的 WHERE 条件。
但是,我想创建另一个带有最近 30 天金额的列,该列将带有条件WHERE date >= CURRENT_TIMESTAMP -30
。
如何在同一个表中创建具有不同条件的选择?
例如:
我有这个:
我想做一个像这样的数据透视表
除了最后一列之外,我已经完成了所有内容 - 它需要将金额与条件相加WHERE date >= CURRENT_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;
确切的功能取决于您使用的数据库。
推荐阅读
- javascript - 压缩从 c# 发送的 JSON 对象到 Javascript POST -(性能改进)
- .net - 如何通过通配符模式构建 dotnet
- python - 使用 Instaloader 和 Python 时卡在下载中
- extract - Halcon - 提取箱子区域
- javascript - fullCalendar:将事件背景颜色设置为线性渐变不起作用
- javascript - 如何在特定索引处给出跨度数组底部边框?反应JS
- python - 是否可以在 python 中为 scipy.integrate 乘以 lambda 函数?
- registry - 在本地工作,在 Github 操作上失败:无法传输 Github 托管的父 pom,收到错误请求 an parent.relativePath 指向错误的本地 POM
- r - 如何在 R 中的需求曲线上找到使利润最大化的最佳点?
- java - 如何在 Android Studio 中的应用启动时连接配对的蓝牙设备?