SQL - Pivot Column data to raw. Not as table header value - sql

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

Related

Wrap CTE inside another Select statement

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.

Self Join Issue - Defining Extracted Time Periods

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

Divide 2 columns with a WHERE clause

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

Get results only if it exists in a union tsql

So I have the following select that will output datametrics and I have a Union as well
SELECT DISTINCT (SELECT DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,MAX(GreatestDate)) + 1, 0))
FROM
(VALUES (max(th.TransactionEffectiveDt)),(max(bp.EffectiveDt)),(max(th.TransactionDt))) AS Value(GreatestDate)) AS BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,max(cast(th.TransactionEffectiveDt AS DATE)) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,replace(UPPER(ni.IndexName), ',', '') InsuredName
,replace(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''), ',', '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,'0'
,'0'
,'0'
,bd.YearBuilt YrConstruction
,ln.PROPDed + '%' [% loss ded EQ]
,CAST(bd.BldgNumber AS VARCHAR(255)) BldgNumber
,CONVERT(INT,REPLACE(bd.BuildingValue,',','')) BuildingValue
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',','')) ContentsBLimit
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',','')) ContentsCLimit
,CONVERT(INT,REPLACE(bd.TIBLimit,',','')) TIBLimit
,CONVERT(INT,REPLACE(bd.BILimit,',','')) BILimit
,CONVERT(INT,REPLACE(bd.EDPLimit,',','')) EDPLimit
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.risk r on r.SystemId=bp.SystemId
AND r.CMMContainer=bp.CMMContainer
AND r.ParentId=ln.Id
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
AND bd.ParentId=r.id
AND bd.[Status] = 'ACTIVE'
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd in ('RiskAddr')
AND ad.ParentId = bd.id
INNER JOIN java.transactioninfo th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'Application'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
AND th.TransactionNumber in (select distinct th.TransactionNumber
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd = 'InsuredMailingAddr'
INNER JOIN java.transactionhistory th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'policy'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC')
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '')
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,bd.YearBuilt
,ln.PROPDed + '%'
,CAST(bd.BldgNumber AS VARCHAR(255))
,CONVERT(INT,REPLACE(bd.BuildingValue,',',''))
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',',''))
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',',''))
,CONVERT(INT,REPLACE(bd.TIBLimit,',',''))
,CONVERT(INT,REPLACE(bd.BILimit,',',''))
,CONVERT(INT,REPLACE(bd.EDPLimit,',',''))
UNION
SELECT distinct (SELECT DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,MAX(GreatestDate)) + 1, 0))
FROM
(VALUES (max(th.TransactionEffectiveDt)),(max(bp.EffectiveDt)),(max(th.TransactionDt))) AS Value(GreatestDate)) AS BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,max(cast(th.TransactionEffectiveDt AS DATE)) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,replace(UPPER(ni.IndexName), ',', '') InsuredName
,replace(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''), ',', '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,isnull(cast(th.writtenpremiumamt as int), '0') APRP
,isnull(cast(th.inforcepremiumamt as int), '0') AnnualPremium
,CONVERT(INT,REPLACE(REPLACE(REPLACE(ln.DWELLLimit, '.00', ''), '$', ''),',','')) AggreLimit
,'0'
,ln.PROPDed +'%' [% loss ded EQ]
,CASE
WHEN BD.bldgnumber > 0
THEN '0' END as bldgnumber
,'0'
,'0'
,'0'
,'0'
,'0'
,'0'
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd = 'InsuredMailingAddr'
INNER JOIN java.transactionhistory th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'policy'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,cast(th.TransactionEffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''))
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,isnull(cast(th.writtenpremiumamt as int), '0')
,isnull(cast(th.inforcepremiumamt as int), '0')
,CONVERT(INT,REPLACE(REPLACE(REPLACE(ln.DWELLLimit, '.00', ''), '$', ''),',',''))
,ln.PROPDed +'%'
,CASE
WHEN BD.bldgnumber > 0
THEN '0' END
ORDER BY PolicyNumber
,transactionnumber
,bldgnumber
,BOOKDATE
I get the following results:
enter image description here
Notice how there are three 1's and three 2's but only two 3's? That's because in my union, the 3 doesn't exist. Only on my top query does. What I want to do is to select everything where only it exists in my union. So for this instance, since 3 doesn't exist in my union, I want to omit it from my results. I tried doing EXISTS and IN but still not getting what I want. Been stuck on this.
Try this approach
;WITH cte
AS (SELECT 1 AS fst_indicator, -- To identify the records from first query
NULL as scd_indicator,
TransactionNumber,..
FROM First_Query
UNION ALL -- Change it to UNION if you really want to remove duplicates
SELECT NULL AS fst_indicator,
1 as scd_indicator,-- To identify the records from second query
TransactionNumber,..
FROM Second_Query),
cte1
AS (SELECT TransactionNumber
FROM cte
GROUP BY TransactionNumber
HAVING Sum(fst_indicator) >= 1 -- to make sure TransactionNumber is present in first query
AND Sum(scd_indicator) >= 1 -- to make sure TransactionNumber is present in second query
)
SELECT *
FROM cte c
WHERE EXISTS (SELECT 1
FROM cte1 c1
WHERE c.TransactionNumber = c1.TransactionNumber)

Store procedure for a select statement which should take input

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'