题
我已经创建了下列表格(通过联盟的所有):
ID Date Hour Weight Fiscal
AAA 1/27/2009 0 10 0
AAA 1/30/2009 0 20 0
AAA 2/14/2009 0 10 0
AAA 2/18/2009 0 20 0
AAA 2/27/2009 0 20 0
AAA 2/28/2009 0 20 0
AAA 1/14/2009 10 0 0
AAA 2/14/2009 20 0 0
AAA 2/16/2009 10 0 0
AAA 2/25/2009 10 0 0
AAA 2/26/2009 10 0 0
AAA 3/3/2009 20 0 0
NULL 0 0 0 1/28/2009
NULL 0 0 0 2/27/2009
NULL 0 0 0 3/29/2009
我想检索:
ID Date Hour Weight
AAA 1/28/2009 10 10
AAA 2/27/2009 50 50
AAA 3/29/2009 20 20
它应该第一个转换的日期列于下一个财政月结束的财政(例如1/27/2007 -> 1/28/2009, 1/30/2009 -> 2/27/2009, 等等)。 然后小组通过这种价值。
我能够使用:
SELECT ID
, left(CONVERT(VARCHAR(10)
, date, 111),7) as Date
, round(sum(Hours),0) as Hours
, round(sum(Weight),0) as Weight
FROM ...
GROUP BY ID
, left(CONVERT(VARCHAR(10), date, 111),7)
ORDER by ID ASC
, left(CONVERT(VARCHAR(10), date, 111),7) ASC
但是,这只是群体通过 日历 日期,而不是根据财政月结束我的 财政 列。
解决方案
你不应该联盟的财政期成为你的表。但与表作为你必须现在,您可以创建一个表(使用,所以没有特别权限是必要的)财政'期并加入这个表格与你的主表。
我叫你表。我也不得不重新命名你的列cHour和CDate因为在Oracle至少日期是一个保留词。你可以很有可能创建的表中的'主要'和表财政'直接从你的来源表,以加速事:
with fiscal_part as (
select fiscal
from SO
where fiscal is not null)
, fiscal as (
select fb.fiscal fiscal_begin
, min(fe.fiscal) fiscal_end
from fiscal_part fb right join
fiscal_part fe
on fe.fiscal > fb.fiscal
group by fb.fiscal)
, main as (
select *
from SO
where fiscal is null)
select main.ID
, fiscal.fiscal_end
, sum(main.cHour)
, sum(main.weight)
from main
join fiscal on main.cdate >= coalesce(fiscal.fiscal_begin, main.cdate)
and main.cdate < fiscal.fiscal_end
group by main.ID
, fiscal.fiscal_end
order by fiscal.fiscal_end
还注意到,你的样本数据有一个错误;重于你的最后期限应为40(行的日期日到2月27日和2月28日).
不隶属于 StackOverflow