SELECT YEAR(aum.AUM_Timeperiod) as Year,
DATEPART(q, aum.AUM_TimePeriod) AS Quarter,
SUM(cast(aum.AUM_AssetValue AS money)) as total_AssetValue
FROM AssetUnderManagement as aum,
LineOfBusiness
where aum.LOB_ID = LineOfBusiness.LOB_ID
and LineOfBusiness.LOB_Name = 'Asset Management'
GROUP BY YEAR(aum.AUM_Timeperiod), DATEPART(q, aum.AUM_TimePeriod);
上述查询返回每季度的值。
我的问题是,如果我希望将该季度上个月的Total_AssetValue
分配到该季度,我该如何更改它。
对于eaxmple Quater 3,total_AssetValue为sum(100 + 200 + 300)。但我希望quater 3的值为300,这是该季度中的最后一个月值
答案 0 :(得分:0)
怎么样:
SELECT
Year,
Quarter,
(
SELECT SUM(CAST(AUM_AssetValue AS MONEY))
FROM AssetUnderManagement
WHERE YEAR(AUM_Timeperiod) = i.Year
AND MONTH(AUM_TimePeriod) = i.LastMonthInQuarter
) AS total_AssetValue
FROM
(
SELECT
YEAR(aum.AUM_Timeperiod) AS Year,
DATEPART(q, aum.AUM_TimePeriod) AS Quarter,
MAX(MONTH(aum.AUM_TimePeriod)) AS LastMonthInQuarter
FROM
AssetUnderManagement as aum, LineOfBusiness
WHERE
aum.LOB_ID = LineOfBusiness.LOB_ID
AND LineOfBusiness.LOB_Name = 'Asset Management'
GROUP BY
YEAR(aum.AUM_Timeperiod),
DATEPART(q, aum.AUM_TimePeriod)
) AS i
答案 1 :(得分:0)
这是一个使用公用表表达式的版本:
WITH MyData AS
(SELECT YEAR(aum.AUM_Timeperiod) AS [Year], DATEPART(q, aum.AUM_TimePeriod) AS [Quarter],
DATEPART(M, aum.AUM_TimePeriod) AS [Month],
DATEPART(M, aum.AUM_TimePeriod) - (DATEPART(q, aum.AUM_TimePeriod) - 1) * 3 AS [MonthInQtr],
SUM(CAST(aum.AUM_AssetValue AS MONEY)) AS [total_AssetValue]
FROM AssetUnderManagement AS aum, LineOfBusiness
WHERE aum.LOB_ID = LineOfBusiness.LOB_ID
AND LineOfBusiness.LOB_Name = 'Asset Management'
GROUP BY YEAR(aum.AUM_Timeperiod), DATEPART(q, aum.AUM_TimePeriod),
DATEPART(M, aum.AUM_TimePeriod), DATEPART(M, aum.AUM_TimePeriod) -
(DATEPART(q, aum.AUM_TimePeriod) - 1) * 3
)
SELECT [Year], [Quarter]
FROM MyData
WHERE MonthInQtr = 3
ORDER BY [Year], [Quarter], [total_AssetValue]
;
您可以使用上面的相同CTE并使用以下查询来获取原始结果
SELECT [Year], [Quarter], SUM([total_AssetValue])
FROM MyData
GROUP BY [Year], [Quarter]
ORDER BY [Year], [Quarter]
;