简体   繁体   English

如何在表的日期范围内选择值的聚合

[英]How to select aggregate of values within a date range from a table

Let me just give a simplified example to illustrate what I mean. 让我举一个简单的例子来说明我的意思。

Let's say we have a table named accounts with columns deposits , dmonth , and dyear . 比方说,我们有一个栏目存款 ,d月 ,和d年的表名为帐户 Select sum(deposits) will get the sum of ALL values under the deposits column. 选择总和(存款)将获得存款列下的所有值的总和。 What is the SQL query to get sum of deposits for, say, period earlier than July 2016 什么是获得存款总额的SQL查询,例如,比2016年7月 更早的时期

Here is another way: 这是另一种方式:

SELECT SUM(Deposits)
FROM   Accounts
WHERE  (dYear = 2016 AND dMonth < 7)
OR     dYear < 2016

Depending on how your dyear and dmonth or stored, you may need to do something like this: 根据您的dyeardmonth或存储方式,您可能需要执行以下操作:

SELECT SUM(deposits) as Deposits_Sum WHERE CONVERT(int, dyear+dmonth) < 201607

What i've done here is combined your dyear and dmonth to create a value that's chronologically sortable. 我在这里所做的就是将你的dyeardmonth结合起来创造一个按时间顺序排序的值。 I then convert this to an integer for comparison purposes. 然后我将其转换为整数以进行比较。

Using this logic, we can find all records where this value is less than July 2016 by doing < 201607 in the WHERE clause. 使用此逻辑,我们可以通过在WHERE子句中执行< 201607来查找此值小于2016年7月的所有记录。 This final piece may require some modification if your years are not stored as yyyy and/or your months are not MM . 如果您的年份没有存储为yyyy和/或您的月份不是MM ,则最后一件可能需要进行一些修改。

Assuming dmonth contains something date time like you could do this with a where clase 假设dmonth包含某些日期时间,就像你可以使用where clase一样

Select sum(deposits) as Sum from accounts where dmonth < 07-01-16 00:00:000.000

See also: 也可以看看:

SQL sum with condition 带条件的SQL和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM