简体   繁体   English

仅根据当前会计年度计算字段总数 - SQL

[英]Calculate totals of field based on current fiscal year only - SQL

I have seen many examples regarding calculating the sum of fields using the fiscal year, but I can not find one that fits my needs. 我已经看到很多关于使用会计年度计算字段总和的例子,但我找不到符合我需求的字段。 What I am trying to do is get just the current fiscal year totals for a field using SQL Query. 我想要做的是使用SQL Query获取字段的当前会计年度总计。 The fields I have is userid, startdate, total_hours, and missed_hours. 我有的字段是userid,startdate,total_hours和missed_hours。 Here is the query I have so far: 这是我到目前为止的查询:

SELECT    
userid,    
SUM(total_hours) - SUM(missed_hours) AS hours    
FROM mytable    
GROUP BY userid

This works great, but all I need is the total number of hours for the current fiscal year for each of the userid's. 这很好用,但我需要的是每个用户ID的当前会计年度的总小时数。 Our fiscal year runs from July to June. 我们的财政年度从7月到6月。 I only need the current fiscal year and I need it to start over again this coming July. 我只需要当前的财政年度,我需要在今年7月重新开始。

Add a where clause: 添加where子句:

FROM mytable
WHERE startdate >= '2011-07-01'
GROUP BY userid

Or with the start of the year dynamically: 或者动态地开始年份:

where startdate >= dateadd(yy, datepart(yy, getdate())-2001, '2000-07-01')

Assuming this is SQLServer, try: 假设这是SQLServer,请尝试:

SELECT userid, SUM(total_hours) - SUM(missed_hours) AS hours    
FROM mytable
WHERE startdate >= cast( cast(year(dateadd(MM,-6,getdate())) as varchar(4)) + 
                         '-07-01' as date ) and
      startdate <  cast( cast(year(dateadd(MM, 6,getdate())) as varchar(4)) + 
                         '-07-01' as date )
GROUP BY userid

Maybe something like this: 也许是这样的:

SELECT
    userid,
    SUM(total_hours) - SUM(missed_hours) AS hours
FROM 
    mytable
WHERE 
    MONTH(startdate) BETWEEN 6 AND 7
    AND YEAR(startdate) IN (2011,2012)
GROUP BY userid

For the solution, two additional information is needed 对于该解决方案,需要两个附加信息

  • the name of the date column 日期列的名称
  • the vendor type of RDBMS you are using 您正在使用的RDBMS的供应商类型

I supposed your date column is date_col and you are using MySQL 我想你的日期列是date_col ,你正在使用MySQL

SELECT    
userid,    
SUM(total_hours) - SUM(missed_hours) AS hours    
FROM mytable    
WHERE date_col between STR_TO_DATE('01,7,2011','%d,%m,%Y') and STR_TO_DATE('01,7,2010','%d,%m,%Y')
GROUP BY userid

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

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