在一张表中,我在某段时间(五年)内有货币汇率。在另一张表中,我计算了数据。 我有任务。我需要从连接表的每周摘要中获取统计信息 我现在正在这样做:
DECLARE @Category_RentHouse INT = 3;
DECLARE @Category_Parents INT = 5;
DECLARE @Category_Salary INT = 9;
DECLARE @TestDateStart DATE = '2012-01-01';
DECLARE @TestDateFinish DATE = '2012-01-07';
select Weeks, SUM(Cash_Usd) TotalMoney
from (select CAST(RateDate AS DATE) Weeks,
CASE WHEN CategoryID = @Category_RentHouse THEN (TransactionAmount*(-1))
WHEN CategoryID = @Category_Parents THEN TransactionAmount
WHEN CategoryID = @Category_Salary THEN CAST((TransactionAmount /
RateValue) AS MONEY)
ELSE CAST((TransactionAmount*(-1) / RateValue) AS MONEY)
END AS Cash_Usd
FROM (select * from Marathon.dbo.Transactions T
LEFT JOIN IntermediateM.dbo.Rates R ON T.TransactionDate = R.RateDate) Y
) RR
WHERE Weeks BETWEEN @TestDateStart AND @TestDateFinish
GROUP BY DATEPART(week, Weeks), Weeks
ORDER BY Weeks
运行这个小代码的结果是
但如果在字段Weeks和TotalSumm中我会得到下一个字段会更好:
Weeks TotalSumm
2012-01-07 -552...
2012-01-14 ....
答案 0 :(得分:0)
我认为您只需修复select
和group by
:
SELECT MIN(Dte) as Weeks, SUM(Cash_Usd) TotalMoney
FROM (SELECT CAST(RateDate AS DATE) as Dte,
(CASE WHEN CategoryID = @Category_RentHouse THEN (TransactionAmount*(-1))
WHEN CategoryID = @Category_Parents THEN TransactionAmount
WHEN CategoryID = @Category_Salary THEN CAST((TransactionAmount / RateValue) AS MONEY)
ELSE CAST((TransactionAmount*(-1) / RateValue) AS MONEY)
END) AS Cash_Usd
FROM Marathon.dbo.Transactions T LEFT JOIN
IntermediateM.dbo.Rates R
ON T.TransactionDate = R.RateDate
WHERE Weeks BETWEEN @TestDateStart AND @TestDateFinish
) RT
GROUP BY DATEPART(week, Weeks)
ORDER BY Weeks