問題
在我的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