Requirement:
Divide EUR exchange rate by USD exchange rate and show result in a new column.
For example, 0.912/0.822 = 1.1. I want the 1.1 in a new column called 'EUR/USD'
I will have to do this division for a few different rates but we can use the EUR/USD as an example.
Query
select er.Rate, wc.CurrencyCode + ' ' + wc.Descr as [Currency], er.EDate as [Exchange Date], ISNULL(wc.MonSymbol, ' ') AS [Symbol], er2.Rate as [Rate2]
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
JOIN ExchangeRate er2 on er.InExchangeRateId = er2.InExchangeRateId
inner join (
select wc.CurrencyCode, max(er.EDate) as MaxDate
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
group by wc.CurrencyCode
) erm on wc.CurrencyCode = erm.CurrencyCode and er.EDate = erm.MaxDate
Current Result
Schema
Attempt
select b.*,max(case when b.currency='EUR Euro' then b.Rate end)/max(case when
b.currency='USD US Dollar' then b.Rate end) as [EUR/USD] from
(select er.Rate as Rate, wc.CurrencyCode + ' ' + wc.Descr as [Currency], er.EDate
as [Exchange Date], ISNULL(wc.MonSymbol, ' ') AS [Symbol], er2.Rate as [Rate2]
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
JOIN ExchangeRate er2 on er.InExchangeRateId = er2.InExchangeRateId
inner join (
select wc.CurrencyCode, max(er.EDate) as MaxDate
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
group by wc.CurrencyCode
) erm on wc.CurrencyCode = erm.CurrencyCode and er.EDate = erm.MaxDate)b
group by b.rate, b.Currency, b.[Exchange Date], b.Symbol, b.Rate2
Result:
Solution:
select er.Rate, wc.CurrencyCode + ' ' + wc.Descr as [Currency], er.EDate as [Exchange Date], ISNULL(wc.MonSymbol, ' ') AS [Symbol],
[eur].Rate/[usd].rate as [EUR/USD], [usd].Rate/[zar].rate as [USD/ZAR], [eur].Rate/[zar].rate as [EUR/ZAR], [eur].Rate/[nok].rate as [EUR/NOK],
[eur].Rate/[bwp].rate as [EUR/BWP], [bwp].Rate/[zar].rate as [ZAR/BWP]
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
inner join (
select wc.CurrencyCode, max(er.EDate) as MaxDate
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
group by wc.CurrencyCode
) erm on wc.CurrencyCode = erm.CurrencyCode and er.EDate = erm.MaxDate
OUTER APPLY
(SELECT er3.Rate, wc3.CurrencyCode + ' ' + wc3.Descr as [Currency], er3.EDate as [Exchange Date]
FROM ExchangeRate er3
JOIN WorldCurrency wc3 on er3.ExCurrencyId = WC3.InCurrencyId
WHERE wc3.CurrencyCode = 'USD' AND er3.EDate = erm.MaxDate) as [USD]
OUTER APPLY
(SELECT er4.Rate, wc4.CurrencyCode + ' ' + wc4.Descr as [Currency], er4.EDate as [Exchange Date]
FROM ExchangeRate er4
JOIN WorldCurrency wc4 on er4.ExCurrencyId = WC4.InCurrencyId
WHERE wc4.CurrencyCode = 'EUR' AND er4.EDate = erm.MaxDate) as [EUR]
OUTER APPLY
(SELECT er5.Rate, wc5.CurrencyCode + ' ' + wc5.Descr as [Currency], er5.EDate as [Exchange Date]
FROM ExchangeRate er5
JOIN WorldCurrency wc5 on er5.ExCurrencyId = WC5.InCurrencyId
WHERE wc5.CurrencyCode = 'ZAR' AND er5.EDate = erm.MaxDate) as [ZAR]
OUTER APPLY
(SELECT er6.Rate, wc6.CurrencyCode + ' ' + wc6.Descr as [Currency], er6.EDate as [Exchange Date]
FROM ExchangeRate er6
JOIN WorldCurrency wc6 on er6.ExCurrencyId = WC6.InCurrencyId
WHERE wc6.CurrencyCode = 'NOK' AND er6.EDate = erm.MaxDate) as [NOK]
OUTER APPLY
(SELECT er7.Rate, wc7.CurrencyCode + ' ' + wc7.Descr as [Currency], er7.EDate as [Exchange Date]
FROM ExchangeRate er7
JOIN WorldCurrency wc7 on er7.ExCurrencyId = WC7.InCurrencyId
WHERE wc7.CurrencyCode = 'BWP' AND er7.EDate = erm.MaxDate
) as [BWP]
try this
select b.*,case when b.currency='EUR Euro' then b.Rate end/case when
b.currency='USD US Dollar' then b.Rate end as [EUR/USD] from
(select er.Rate as Rate, wc.CurrencyCode + ' ' + wc.Descr as [Currency], er.EDate
as [Exchange Date], ISNULL(wc.MonSymbol, ' ') AS [Symbol], er2.Rate as [Rate2]
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
JOIN ExchangeRate er2 on er.InExchangeRateId = er2.InExchangeRateId
inner join (
select wc.CurrencyCode, max(er.EDate) as MaxDate
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
group by wc.CurrencyCode
) erm on wc.CurrencyCode = erm.CurrencyCode and er.EDate = erm.MaxDate)b
I don't understand why you would like to do this and this is a longshot without knowing the ExchangeRate table. But this should do what you're asking
select er.Rate,
wc.CurrencyCode + ' ' + wc.Descr as [Currency],
er.EDate as [Exchange Date], ISNULL(wc.MonSymbol, ' ') AS [Symbol],
er2.Rate as [Rate2],
erEur.Rate/erUsd.Rate as [EUR/USD]
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
JOIN ExchangeRate er2 on er.InExchangeRateId = er2.InExchangeRateId
JOIN ExchangeRate erUsd on er.EDate = erEUR.Edate and erEUR.CurrencyCode = 'USD'
JOIN ExchangeRate erEur on er.EDate = erEUR.Edate and erEUR.CurrencyCode = 'EUR'
inner join (
select wc.CurrencyCode, max(er.EDate) as MaxDate
from ExchangeRate er
JOIN WorldCurrency wc on er.ExCurrencyId = WC.InCurrencyId
group by wc.CurrencyCode
) erm on wc.CurrencyCode = erm.CurrencyCode and er.EDate = erm.MaxDate
Related
Is it possible to wrap a CTE inside of another Select statement?
Here is my CTE:
WITH IRS AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'IRS' ) ,
PA AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'PA' )
SELECT IRS_WTHD.BUSINESS_UNIT, IRS_WTHD.VOUCHER_ID, IRS_WTHD.VOUCHER_LINE_NUM,
--COLUMN 1 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN 'PA'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'IRS'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'IRS'
ELSE ''
END ,
--COLUMN 2 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ','0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'MISC7'
WHEN PA_WTHD.WTHD_ENTITY = '' THEN ''
ELSE 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
END
FROM IRS IRS_WTHD
LEFT JOIN PA PA_WTHD ON PA_WTHD.BUSINESS_UNIT = IRS_WTHD.BUSINESS_UNIT AND PA_WTHD.VOUCHER_ID = IRS_WTHD.VOUCHER_ID AND PA_WTHD.VOUCHER_LINE_NUM = IRS_WTHD.VOUCHER_LINE_NUM
I would like to wrap the above CTE inside of this main SQL Select statement below and output the two CASE statement columns above into the final SELECT statement below while joining on BUSINESS_UNIT, VOUCHER_ID, and VOUCHER_LINE_NUM fields from the PS_VCHR_LINE_WTHD table :
--Main Select Statement:
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END, A.MERCHANDISE_AMT, B.QTY_VCHR, A.UNIT_PRICE, A.UNIT_OF_MEASURE, A.DESCR, A.PO_ID, A.LINE_NBR,
A.SCHED_NBR, B.PO_DIST_LINE_NUM, A.DESCR254_MIXED, '','',
F.OR_ENTITY + '.' + F.OR_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
ELSE '000' END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000000.' + '000000' ,'', C.ACCOUNTING_DT, '',
'','','', ISNULL(D.WTHD_ENTITY,''), '', '', '', A.SALETX_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
ORDER BY 1,2
Is this possible, or is there an alternate way of avoiding using the CTE? I am using the CTE because I need to be able to run Case statements across multiple rows and possibly return data on other rows.
In the below query, I extract the month in the Select query. I then execute multiple Self Joins using the extracted month. I am getting an
Invalid column name 'mnth'
for every time that field is referenced in the Self Joins. Where would I define the extracted month in the query below?
SELECT MONTH(frcst.InvDate) AS mnth
, frcst.LineCode
, frcst.ClassCode
, cc_type
, rank
, keycust1
, keycust2
, keycust3
, sales1
, sales2
, sales3
, SUM(ship2017.GrossSales) AS gross_sales2017
, SUM(ship2017.QtyShip + ( (ship2017.QtyOrd - ship2017.QtyShip) * 0.25) ) AS frcst_qty2017
, SUM(ship2018.GrossSales) AS gross_sales2018
, SUM(ship2018.QtyShip + ( (ship2018.QtyOrd - ship2018.QtyShip) * 0.25) ) AS frcst_qty2018
, SUM(ship2019.GrossSales) AS gross_sales2019
, SUM(ship2019.QtyShip + ( (ship2019.QtyOrd - ship2019.QtyShip) * 0.25) ) AS frcst_qty2019
, SUM(ship2020.GrossSales) AS gross_sales2020
, SUM(ship2020.QtyShip + ( (ship2020.QtyOrd - ship2017.QtyShip) * 0.25) ) AS frcst_qty2020
FROM FrcstFactTbl frcst
JOIN account_hierarchy_lu account
ON frcst.AccountNumber = account.account_number
JOIN cc_type_lu cct
ON frcst.ClassCode = cct.class_code
JOIN pop_code_lu pop
ON frcst.PartNumber = pop.PartNumber
JOIN FrcstFactTbl ship2017
ON frcst.mnth = ship2017.mnth
AND frcst.LineCode = ship2017.LineCode
AND frcst.ClassCode = ship2017.ClassCode
AND frcst.AccountNumber = ship2017.AccountNumber
JOIN FrcstFactTbl ship2018
ON frcst.mnth = ship2018.mnth
AND frcst.LineCode = ship2018.LineCode
AND frcst.ClassCode = ship2018.ClassCode
AND frcst.AccountNumber = ship2018.AccountNumber
JOIN FrcstFactTbl ship2019
ON frcst.mnth = ship2019.mnth
AND frcst.LineCode = ship2019.LineCode
AND frcst.ClassCode = ship2019.ClassCode
AND frcst.AccountNumber = ship2019.AccountNumber
JOIN FrcstFactTbl ship2020
ON frcst.mnth = ship2020.mnth
AND frcst.LineCode = ship2020.LineCode
AND frcst.ClassCode = ship2020.ClassCode
AND frcst.AccountNumber = ship2019.AccountNumber
WHERE YEAR(ship2017.InvDate) = '2017'
AND YEAR(ship2018.InvDate) = '2018'
AND YEAR(ship2019.InvDate) = '2019'
AND YEAR(ship2020.InvDate) = '2020'
GROUP BY mnth, frcst.LineCode, frcst.ClassCode, cc_type, rank, keycust1, keycust2, keycust3, sales1, sales2, sales3
ORDER BY mnth
The only place you can use a column alias (which is what mnth is) is in the order by clause. Everywhere else you have to use the computation MONTH(frcst.InvDate) or else compute it in a sub-query.
I would use a sub-query i.e. replace this line:
FROM FrcstFactTbl frcst
With this:
FROM (
select *, MONTH(frcst.InvDate) AS mnth
from FrcstFactTbl
) frcst
And of course replace the first line:
SELECT MONTH(frcst.InvDate) AS mnth
With
SELECT mnth
Thank you all. Below is the query that finally worked.
SELECT
masterlist.Month AS [Month]
,masterlist.LineCode AS [Line Code]
,masterlist.ClassCode AS [Class Code]
,ct.cc_type AS [Class Code Type]
,pop.pop_code AS [Pop Code]
,ah.keycust1 AS [Key Cust1]
,ah.keycust2 AS [KeyCust2 - Territory]
,ah.keycust3 AS [Key cust3]
,ah.sales1 AS [Sales1]
,ah.sales2 AS [Sales2]
,ah.sales3 AS [Sales3]
,SUM(ff2017.[Gross]) AS [2017 Gross]
,SUM (ff2017.QtyShip + ( (ff2017.QtyOrd - ff2017.QtyShip) * 0.25) ) AS [2017 Forecast Qty]
,SUM(ff2018.[Gross]) AS [2018 Gross]
,SUM (ff2018.QtyShip + ( (ff2018.QtyOrd - ff2018.QtyShip) * 0.25) ) AS [2018 Forecast Qty]
,SUM(ff2019.[Gross]) AS [2019 Gross]
,SUM (ff2019.QtyShip + ( (ff2019.QtyOrd - ff2019.QtyShip) * 0.25) ) AS [2019 Forecast Qty]
,SUM(ff2020.[Gross]) AS [2020 Gross]
,SUM (ff2020.QtyShip + ( (ff2020.QtyOrd - ff2020.QtyShip) * 0.25) ) AS [2020 Forecast Qty]
FROM (
SELECT
DISTINCT ff.AccountNumber, MONTH(InvDate) AS Month,LineCode,ClassCode,ff.PartNumber
FROM FrcstFactTbl ff
) AS masterlist
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2017
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2017 ON masterlist.Month = ff2017.Month AND masterlist.AccountNumber = ff2017.AccountNumber AND masterlist.PartNumber = ff2017.PartNumber
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2018
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2018 ON masterlist.Month = ff2018.Month AND masterlist.AccountNumber = ff2018.AccountNumber AND masterlist.PartNumber = ff2018.PartNumber
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2019
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2019 ON masterlist.Month = ff2019.Month AND masterlist.AccountNumber = ff2019.AccountNumber AND masterlist.PartNumber = ff2019.PartNumber
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2020
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2020 ON masterlist.Month = ff2020.Month AND masterlist.AccountNumber = ff2020.AccountNumber AND masterlist.PartNumber = ff2020.PartNumber
LEFT OUTER JOIN cc_type_lu ct ON masterlist.ClassCode = ct.class_code
LEFT OUTER JOIN pop_code_lu pop ON masterlist.PartNumber = pop.PartNumber
LEFT OUTER JOIN account_hierarchy_lu ah ON masterlist.AccountNumber = ah.account_number
--ORDER BY masterlist.Month
GROUP BY masterlist.Month
,masterlist.LineCode
,masterlist.ClassCode
,ct.cc_type
,pop.pop_code
,ah.keycust1
,ah.keycust2
,ah.keycust3
,ah.sales1
,ah.sales2
,ah.sales3
Here is my current output format:
This is the output I need:
And here is my code
SELECT
tblPO.PONO,
CONVERT(CHAR(10), tblPO.POEnterdDate, 126) AS PODate,
tblSupplier.SupplierCode + '-' + tblSupplier.SupName AS SupplierName,
tblPOMaterials.MaterialCode + '-' + tblMaterial.MaterialDescription AS [Item Description],
tblPR.PRType AS [SPR or PR],
tblPOFromPR.PRNO AS [PR/SPR],
tblUnit.UnitCode,
tblPOMaterials.POQty AS Qty,
tblPOMaterials.UnitPrice,
tblPOMaterials.POQty * tblPOMaterials.UnitPrice AS [Total Price]
FROM
tblPO
INNER JOIN
tblPOMaterials ON tblPO.PONO = tblPOMaterials.PONO
INNER JOIN
tblMaterial ON tblPOMaterials.MaterialCode = tblMaterial.MaterialCode
INNER JOIN
tblSupplier ON tblPO.POSupplierID = tblSupplier.SupplierID
INNER JOIN
tblPOFromPR ON tblPO.PONO = tblPOFromPR.PONO
AND tblPOMaterials.MaterialCode = tblPOFromPR.MaterialCode
INNER JOIN
tblUnit ON tblMaterial.UnitID = tblUnit.UnitID
INNER JOIN
tblPR ON tblPOFromPR.PRNO = tblPR.PRNO
WHERE
(CONVERT(date, tblPO.PODate) BETWEEN #StartDate AND #EndDate)
AND (tblPO.POType <> 'Service')
AND (tblPO.POType = #Category)
ORDER BY
tblPO.PONO
Try Using Stuff and Distinct
SELECT DISTINCT tblPO.PONO, CONVERT(CHAR(10), tblPO.POEnterdDate, 126) AS PODate, tblSupplier.SupplierCode + '-' + tblSupplier.SupName AS SupplierName,
tblPOMaterials.MaterialCode + '-' + tblMaterial.MaterialDescription AS [Item Description], tblPR.PRType AS [SPR or PR],
STUFF((
SELECT '/' + CAST(T.PRNO AS VARCHAR(100))
FROM dbo.tblPOFromPR T
WHERE tblPO.PONO = T.PONO AND tblPOMaterials.MaterialCode = T.MaterialCode
FOR XML PATH('')),1,1,'') AS [PR/SPR],
tblUnit.UnitCode, tblPOMaterials.POQty AS Qty, tblPOMaterials.UnitPrice,
tblPOMaterials.POQty * tblPOMaterials.UnitPrice AS [Total Price]
FROM tblPO INNER JOIN tblPOMaterials ON tblPO.PONO = tblPOMaterials.PONO
INNER JOIN tblMaterial ON tblPOMaterials.MaterialCode = tblMaterial.MaterialCode
INNER JOIN tblSupplier ON tblPO.POSupplierID = tblSupplier.SupplierID
INNER JOIN tblPOFromPR ON tblPO.PONO = tblPOFromPR.PONO AND tblPOMaterials.MaterialCode = tblPOFromPR.MaterialCode
INNER JOIN tblUnit ON tblMaterial.UnitID = tblUnit.UnitID
INNER JOIN tblPR ON tblPOFromPR.PRNO = tblPR.PRNO
WHERE (CONVERT(date, tblPO.PODate) BETWEEN #StartDate AND #EndDate) AND (tblPO.POType <> 'Service') AND (tblPO.POType = #Category)
ORDER BY tblPO.PONO
I have the following query .its execution took 15 min .It is too much slowly .
Is there a way to optimize it ?
Query
SELECT
Id,Fees,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Fees ' AS FeesName
,#MonthName AS [MonthName]
INTO ##TempFeesMonthly
from
(
SELECT DISTINCT
1 as Id,sum(((CNTI_THPAYE *(CNTI_THFACT / CNTI_THPAYE)) *
(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate)t
--CREATE INDEX IDX_TempFeesMonthly ON ##TempFeesMonthly(WeekOfMonth)
--Calcul Temp Margin
UNION ALL
--INSERT INTO ##TempFeesMonthly(Id,Fees,WeekOfMonth,StartDate,EndDate,FeesName,[MonthName])
SELECT
2, sum(Fees) AS Fees ,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Margin ' AS FeesName
,#MonthName AS [MonthName]
from
(
SELECT DISTINCT
sum((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)-(CNTI_THPAYE *(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*1.453*1.21*#NumberOfDays) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate,CNTI_THPAYE,CNTI_DURHEBDO)t
GROUP BY WeekOfMonth,StartDate,EndDate
Can anyone please help me with the store procedure for the following
select statement which should take an input of completeddatekey which
is at the bottom of the select statement
CompletedDateKey is filled with a key in this code but I need a store procedure that should take an input of completeddatekey
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
Its really simple. Just create procedure like below
create procedure MyProc(
#CompletedDateKey varchar(20) )
as
Begin
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = #CompletedDateKey
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
End
Execute it like
Execute MyProc '20140131'