问题
在我的SQL服务器2014我存储项目与列的表:从时间跨度选择多行
开始日期 .. | 结束日期 .... | 项目名称 ................. | 卷
2017-02-13 | 2017-04-12 | GenerateRevenue ......... | 20.02
2017-04-02 | 2018-01-01 | BuildRevenueGenerator | 300.044
2017-05-23 | 2018-03-19 | HarvestRevenue ............ | 434.009
我需要一个SELECT给我每个项目的项目每月一行。这个月的日子不需要考虑。
日期 .......... | 项目名称 .................. | Volume
2017-02-01 | GenerateRevenue ......... | 20.02
2017-03-01 | GenerateRevenue ......... | 20.02
2017-04-01 | GenerateRevenue ......... | 20.02
2017-04-01 | BuildRevenueGenerator | 300.044
2017-05-01 | BuildRevenueGenerator | 300.044
2017-06-01 | BuildRevenueGenerator | 300.044
...
额外
理想的选择的逻辑让我既来计算月成交量也每个月和以前的区别。
日期 .......... | 项目名称 .................. | VolumeMonthly
2017-02-01 | GenerateRevenue ......... | 6.6733
2017-03-01 | GenerateRevenue ......... | 6.6733
2017-04-01 | GenerateRevenue ......... | 6.6733
2017-04-01 | BuildRevenueGenerator | 30.0044
2017-05-01 | BuildRevenueGenerator | 30.0044
2017-06-01 | BuildRevenueGenerator | 30.0044
...
也...
我知道我可以映射它放在一个临时万年历表,但往往会变得过于庞大和复杂的非常快。我真的想找一个更好的方法来解决这个问题。
解决方案
戈登解决方案的工作非常精美,它不需要对某种类型的日历中的第二个表或映射。虽然我不得不改变一些东西,比如确保工会的双方都有相同的SELECT。
这里我改编版:
with cte as (
select startdate as mondate, enddate, projectName, volume
from projects
union all
select dateadd(month, 1, mondate), enddate, projectName, volume
from cte
where eomonth(dateadd(month, 1, mondate)) <= eomonth(enddate)
)
select * from cte;
量每月可以通过更换容积来实现:
CAST(Cast(volume AS DECIMAL)/Cast(Datediff(month,
startdate,enddate)+ 1 AS DECIMAL) AS DECIMAL(15, 2))
END AS [volumeMonthly]
我推荐宝宝的步骤。 –
样本数据和期望的结果将有所帮助。你也应该简化问题。 –
谢谢戈登,你是对的。我添加了一些你建议的样本数据。 – LeComte