我见过许多关于使用会计年度计算字段总和的例子,但我找不到符合我需求的字段。我想要做的是使用SQL Query获取字段的当前会计年度总计。我有的字段是userid,startdate,total_hours和missed_hours。这是我到目前为止的查询:
SELECT
userid,
SUM(total_hours) - SUM(missed_hours) AS hours
FROM mytable
GROUP BY userid
这很有效,但我需要的是每个用户ID的当前会计年度的总小时数。我们的财政年度从7月到6月。我只需要当前的财政年度,我需要在今年7月重新开始。
答案 0 :(得分:1)
添加where子句:
FROM mytable
WHERE startdate >= '2011-07-01'
GROUP BY userid
或者动态地开始年份:
where startdate >= dateadd(yy, datepart(yy, getdate())-2001, '2000-07-01')
答案 1 :(得分:1)
假设这是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
答案 2 :(得分:0)
也许是这样的:
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
答案 3 :(得分:0)
对于解决方案,需要另外两个信息
我认为您的日期列是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