I need to Convert Access Query to SQL Sever Query.
qry_BudgetForTwelveMonths :
SELECT t.JobId, t.AccountId, t.FinancialYear AS FinYear, t.Period, Sum(t.Amount) AS Amt
FROM (SELECT JobId, AccountId,FinancialYear, Period, Amount FROM Temp_BlankBudgets
union all
SELECT JobId, AccountId,FinancialYear, Period, Amount FROM Temp_Budgets) AS t
GROUP BY t.JobId, t.AccountId, t.Period, t.FinancialYear
ORDER BY t.JobId, t.AccountId, t.Period;
Qry_CrstabJobBudgetForTwelveMonths :
TRANSFORM Sum(qry_BudgetForTwelveMonths.Amt) AS SumOfAmt
SELECT qry_BudgetForTwelveMonths.JobId, qry_BudgetForTwelveMonths.AccountId, qry_BudgetForTwelveMonths.FinYear, Sum(qry_BudgetForTwelveMonths.Amt) AS FYTotal
FROM qry_BudgetForTwelveMonths
GROUP BY qry_BudgetForTwelveMonths.JobId, qry_BudgetForTwelveMonths.AccountId, qry_BudgetForTwelveMonths.FinYear
PIVOT qry_BudgetForTwelveMonths.Period;
Final Query
SELECT Temp_Accounts.AccountNumber, Temp_Accounts.AccountName,Qry_CrstabJobBudgetForTwelveMonths.[1],Qry_CrstabJobBudgetForTwelveMonths.[2], Qry_CrstabJobBudgetForTwelveMonths.[3],Qry_CrstabJobBudgetForTwelveMonths.[4], Qry_CrstabJobBudgetForTwelveMonths.[5],
Qry_CrstabJobBudgetForTwelveMonths.[6], Qry_CrstabJobBudgetForTwelveMonths.[7],
Qry_CrstabJobBudgetForTwelveMonths.[8], Qry_CrstabJobBudgetForTwelveMonths.[9],
Qry_CrstabJobBudgetForTwelveMonths.[10], Qry_CrstabJobBudgetForTwelveMonths.[11],
Qry_CrstabJobBudgetForTwelveMonths.[12], Temp_Accounts.AccountID,Qry_CrstabJobBudgetForTwelveMonths.FYTotal
FROM Temp_Accounts INNER JOIN Qry_CrstabJobBudgetForTwelveMonths ON
Temp_Accounts.AccountID = Qry_CrstabJobBudgetForTwelveMonths.AccountID
Here's my take:
--qry_BudgetForTwelveMonths :
SELECT
t.JobId
, t.AccountId
, t.FinancialYear AS FinYear
, t.Period
, Sum(t.Amount) AS Amt
INTO #tmp1
FROM (SELECT
JobId
, AccountId
,FinancialYear
, Period
, Amount
FROM Temp_BlankBudgets
union all
SELECT
JobId
, AccountId
,FinancialYear
, Period
, Amount
FROM Temp_Budgets) AS t
GROUP BY t.JobId, t.AccountId, t.Period, t.FinancialYear
ORDER BY t.JobId, t.AccountId, t.Period;
--Qry_CrstabJobBudgetForTwelveMonths :
SELECT *
INTO #tmp2
FROM (
SELECT
a.JobId
, a.AccountId
, a.FinancialYear
, Sum(a.Amount) AS FYTotal
FROM #tmp a
GROUP BY a.JobId, a.AccountId, a.FinancialYear
) AS SOURCE
PIVOT
(
Sum(a.Amount) AS SumOfAmt
FOR BMonth IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) AS PVT
ORDER BY BMonth
--Final Query
SELECT
Temp_Accounts.AccountNumber
, Temp_Accounts.AccountName
, b.[1]
, b.[2]
, b.[3]
, b.[4]
, b.[5]
, b.[6]
, b.[7]
, b.[8]
, b.[9]
, b.[10]
, b.[11]
, b.[12]
, Temp_Accounts.AccountID
, b.FYTotal
FROM Temp_Accounts
INNER JOIN #tmp2 b
ON Temp_Accounts.AccountID = b.AccountID
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.