I'm glad you could solved, I was working on a possible solution but I'm not sure that it will work for you. I'll share it anyway.
;with Vol_Factdata as
(
Select CASE WHEN @Period = 'Year' THEN DATEPART(YEAR, EventStartDate)
WHEN @Period = 'Quarter' THEN DATEPART( QUARTER, EventStartDate)
WHEN @Period = 'Month' THEN DATEPART( MONTH, EventStartDate)
END as Period,
Agg.ProductTypeID,
Agg.ProductTypeName,
Agg.LoanProgramTypeId,
MIN(MetricValue) AS MetricValall,
SUM(SampleSize) as SampleSizeall
FROM [Reporting].[AggregatedRatesforWidgets] Agg with (NOLOCK)
WHERE Agg.EventStartDate >= @ipstartdate
and Agg.EventStartDate <=@ipenddate
and Agg.LoanProgramTypeID= @ipProducttypeID
GROUP BY CASE WHEN @Period = 'Year' THEN DATEPART(YEAR, EventStartDate)
WHEN @Period = 'Quarter' THEN DATEPART( QUARTER, EventStartDate)
WHEN @Period = 'Month' THEN DATEPART( MONTH, EventStartDate)
END,
Agg.ProductTypeID,
Agg.ProductTypeName,
Agg.LoanProgramTypeId
)
Select
vcy.Period as Period,
vcy.ProductTypeID as ProductTypeID,
vcy.ProductTypeName as ProductTypeName,
vcy.LoanProgramTypeID AS LoanProgramTypeId,
'ALL' as Loanstate,
vcy.MetricValall_1year as MetricValue,
vcy.SampleSizeall_1year as SampleSize
FROM Vol_Factdata vcy
By the way, I noticed the NOLOCK hint you're using and you should be aware that the data returned by your query might be incorrect due to it.