Related
I am migrating procedure from SQL Server to PostgreSQL. I can not write this query in PostgreSQL. How to use temp within WITH clause in PostgreSQL?
WITH TEMP AS
(
SELECT a.AssignNo as LowestAssignNo
, a.AssignNo
, a.AssignName
, HierarchyLevel
, UpperAssignNo
FROM TAssignInfo a
WHERE DeleteYesNo = 'N'
AND UseYesNo = 'Y'
UNION ALL
SELECT a.LowestAssignNo
, b.AssignNo
, b.AssignName
, b.HierarchyLevel
, b.UpperAssignNo
FROM TEMP a
INNER JOIN TAssignInfo b
ON a.UpperAssignNo = b.AssignNo
WHERE DeleteYesNo = 'N'
AND UseYesNo = 'Y'
)
SELECT DISTINCT LowestAssignNo
, STUFF(( SELECT '|' + AssignName
FROM TEMP A
WHERE a.LowestAssignNo = b.LowestAssignNo
AND HierarchyLevel > 1
ORDER BY HierarchyLevel
FOR XML PATH('')
), 1, 1, '') AS AssignNamePath
INTO #NewAssignInfo
FROM TEMP B
WHERE B.HierarchyLevel <> 0
ORDER BY LowestAssignNo DESC
enter image description here
I'm trying to build code that will generate a file in a specific format. The code worked in its entirety until I added A.PrevYTDSales and A.YtdQtySold, so I'm not sure what's going on. It now gives me an error saying "error converting varchar to numeric" so I'm assuming I have a syntax error somewhere but I can't find where. Below is the code.
select
Inv.StockCode -- part
+ '|' + Inv.Description -- desc
+ '|' + isnull(
replace(
CONVERT(varchar,
CAST(
isnull(
case when 0 > (Inv.QOH - isnull(Sor.QOO,0)) then 0
else (Inv.QOH - isnull(Sor.QOO,0)) end
,0)
as Money)
, 1)
,'.00','')
,'0') -- QOH
+ '|' + replace(convert(varchar,cast(BoxQty as money),1),'.00','') -- box qty
+ '|' + YTDSales -- YTD Qty Sold
+ '|' + PrevYTDSales -- Prev YTD Qty Sold
+ '|' + convert(varchar,TRY_CAST(Mass as NUMERIC(19,4))) -- mass
+ '|' + isnull(convert(varchar,DueDt+3,101),' ') -- duedt
+ '|' +
case when isnull(convert(varchar,DueDt+3,101),' ') = ' ' then ' '
when 0 > (Inv.QOH - isnull(Sor.QOO,0)) then
isnull(
replace(
CONVERT(varchar,
CAST(
isnull(
case when 0 > (GitQty - isnull(Sor.QOOtoPOS,0)) then 0
else (GitQty - isnull(Sor.QOOtoPOS,0)) end
,0)
as Money)
, 1)
,'.00','')
,'0')
else
replace(convert(varchar,convert(money,GitQty),1),'.00','')
end -- QTY coming
+ '|' + COO -- COO
+ '|' + Tariff -- tariff
+ '|' + Location -- Customer
+ '|' + isnull(Cus.Customer,' ') -- customer
+ '|' + isnull(
replace(
replace(
Cus.CustStockCode
,Char(13),'')
,Char(10),'')
,' ') customer part
+ '|' + isnull(Cus.StockCode,' ')
+ '|' + 'R'
as partlist
from (
select
A.StockCode as StockCode
,B.Description as Description
,Sum(QtyOnHand) as QOH
,B.UserField2 as BoxQty
,A.YtdQtySold as YTDSales
,A.PrevYearQtySold as PrevYTDSales
,B.Mass as Mass
,B.ProductClass
,B.CountryOfOrigin as COO
,B.TariffCode as Tariff
,case
when Warehouse = '01' then 'All W/H'
when Warehouse = '02' then 'All W/H'
else ''
end as Location
from CompanyR.dbo.InvWarehouse A
left join CompanyR.dbo.InvMaster B on A.StockCode = B.StockCode
left join CompanyR.dbo.[InvMaster+] C on B.StockCode = C.StockCode
where Warehouse in ('01', '02')
and A.StockCode not like 'TEC%'
and B.StockCode is not null
group by A.StockCode , B.Description, B.UserField2, A.YtdQtySold, A.PrevYearQtySold, Mass, B.ProductClass
,B.CountryOfOrigin
,B.TariffCode
,case
when Warehouse = '01' then 'All W/H'
when Warehouse = '02' then 'All W/H'
else ''
end
) Inv
LEFT JOIN
(
select
sum(case
when (Getdate()+57) < MLineShipDate then 0
else (MOrderQty)
end
) as QOO,
sum(case
when ( MLineShipDate > isnull(DueDt, GetDate() ) )
AND
( MLineShipDate < isnull(POSDt, GetDate()+57) )
then MOrderQty
else 0
end
) as QOOtoPOS,
DueDt,
GitQty,
POSDt,
A.MStockCode as StockCode
from CompanyR.dbo.SorDetail A
left join CompanyR.dbo.SorMaster B on A.SalesOrder = B.SalesOrder
left join (
select StockCode
,(ExpectedDueDate) as DueDt
,SUM(GtrQuantity-QtyReceived) as GitQty
from CompanyR.dbo.GtrDetail A
where TransferComplete <> 'Y'
and CompanyR.dbo.get_week(ExpectedDueDate,0) >= CompanyR.dbo.get_week(GETDATE(),0)
and ExpectedDueDate = (select Min(ExpectedDueDate)
from CompanyR.dbo.GtrDetail B where TransferComplete <> 'Y' and A.StockCode = B.StockCode
and CompanyR.dbo.get_week(ExpectedDueDate,0) >= CompanyR.dbo.get_week(GETDATE(),0) )
group by StockCode, ExpectedDueDate
) GIT on A.MStockCode = GIT.StockCode
left join (
select
MStockCode
,min(MLatestDueDate) as POSDt
from CompanyR.dbo.PorMasterDetail
where MCompleteFlag <> 'Y'
and MLatestDueDate > getdate()
and MStockCode not like '-%'
and MStockCode not like '#%'
and MStockCode not like '*%'
group by MStockCode
) POS on A.MStockCode = POS.MStockCode
where 1=1
and A.MLineShipDate < dateadd(week,8,getdate())
and A.MLineShipDate >= DATEADD(s, -0,DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
and A.MStockCode not like '*%'
and A.MStockCode not like '-%'
and B.OrderStatus not in ('\','*','9')
group by A.MStockCode,DueDt,POSDt,GitQty
) Sor on Inv.StockCode = Sor.StockCode
LEFT JOIN CompanyR.dbo.ArCustStkXref Cus on Inv.StockCode = Cus.StockCode and Cus.Customer <> ''
It's supposed to output something like this
098-01-PK|#6 , 3MM DL WASHER 200 PAIR PK|0|0|1.0000| | |TWN|7318.22.0000|All W/H| | | |L
098-01-PK|#6 , 3MM DL WASHER 200 PAIR PK|0|0|1.0000| | |TWN|7318.22.0000|| | | |L
098-01|#6 , 3MM DL WASHER PAIR|0|3,000|1.0000| | |TWN|7318.22.0000|All W/H| | | |L
098-01|#6 , 3MM DL WASHER PAIR|0|3,000|1.0000| | |TWN|7318.22.0000|| | | |L
Anyone have any ideas where I could be having an issue?
Apparently the only conversion to numeric that you have is for the Mass, column.
Since you added the new columns into the group by, probably new rows would appear showing the Mass column with (maybe) a null or some new strange value.
Try running the query from the query inside the from clause by itself and then looking for distinct values for the Mass column and check if they all are numeric.
Hope it helps!
I have the following (obfuscated) SQL running on SQL Server 2012 and need to significantly improve its performance. It works, but sometimes takes more than 60s to return.
I would like to extract the JOINS but this post seems to indicate that this will not be possible (because of things like MIN and MAX) - so how can improve the performance and get these joins simplified/improved?
SELECT
wm.id, wm.uid, wm.em, wm.fn, wm.ln, c, y, RTRIM(LTRIM(yCode)) AS yCode, wm.d1, ISNULL(wm.ffn, wm.pp) as ffn, wm.ada,
case
when wm.mss & 2=2
then 'false'
else 'true'
end AS isa,
(
SELECT ', '+RTRIM(p1.cKey)
FROM profile p1
inner join loc stl on p1.cKey=stl.cKey
WHERE p1.id = wm.id and p1.s = 'A'
FOR XML PATH('')
) [lst],
lishc.[lstCount],
TotalCount = COUNT(*) OVER(),
la.lsa, wskp.cKey AS pid
FROM wmm wm
LEFT JOIN profile p1 ON wm.id = p1.id
LEFT JOIN (
SELECT UA.id, CONVERT(datetime, UA.ins, 1) As lsa
FROM actlog UA
INNER JOIN (
select id, max(ins) as laa
from actlog
group by id
) UAJ on UA.id=UAJ.id and UA.ins=UAJ.laa
) la on la.id=wm.id
LEFT JOIN (
SELECT id, cKey FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY d1 desc) AS ROWNUM
FROM keypro where sc = 'SAP' AND cKeyDesc = 'SAP Agent ID'
) x WHERE ROWNUM = 1
) wskp ON wskp.id = wm.id
LEFT JOIN (
(SELECT p1.id ,COUNT(p1.cKey) AS [lstCount]
FROM profile p1
inner join loc stl on p1.cKey=stl.cKey
where p1.s = 'A'
GROUP BY p1.id)
) lishc ON lishc.id = wm.id
WHERE (#id = 0 OR wm.id = #id)
AND (#uid IS NULL OR wm.uid LIKE '%' + #uid + '%')
AND (#c IS NULL OR wm.c LIKE '%' + #c + '%')
AND (#fn IS NULL OR wm.fn LIKE '%' + #fn + '%')
AND (#ln IS NULL OR wm.ln LIKE '%' + #ln + '%')
AND (#em IS NULL OR wm.em LIKE '%' + #em + '%')
AND (#ffn IS NULL OR (wm.ffn LIKE '%' + #ffn + '%' OR wm.pp LIKE '%' + #ffn + '%'))
AND (#pid IS NULL OR wskp.cKey LIKE '%' + #pid + '%' )
AND (#Date1 IS NULL OR (CAST(wm.d1 AS DATE) BETWEEN CAST(#Date1 AS DATE) AND CAST(#Date2 AS DATE)))
AND (#lsa1 IS NULL OR (CAST(la.lsa AS DATE) BETWEEN CAST(#lsa1 AS DATE) AND CAST(#lsa2 AS DATE)))
AND (#Active IS NULL OR (wm.mss & 2 != 2))
AND (#Inactive IS NULL OR (wm.mss & 2 = 2))
AND (#External IS NULL OR (wm.ada = 'biz'))
AND (#Internal IS NULL OR (wm.ada <> 'biz'))
AND (#ApplyyFilter =0 OR (wm.yCode IN (SELECT #yCode WHERE 1 = 0)))
AND (#ApplylstFilter = 0 OR(p1.cKey IN (SELECT #ShipToList WHERE 1 = 0)))
AND (#ApplylstFilter = 0 OR(p1.s = 'A'))
AND (#ApplyNoFilter = 0 OR (lishc.[lstCount] is null))
AND (#lstCount = 0 OR lishc.[lstCount] = #lstCount)
AND (#ApplyLimitedFilter = 0 OR (wm.id IN (0)))
AND (#ApplyMoreFilter = 0 OR (wm.id IN (SELECT #idss WHERE 1 = 0)))
GROUP BY wm.id, wm.uid, wm.em, wm.fn, wm.ln, y, yCode,c,wm.d1,wm.ffn,wm.mss,wm.ada, la.lsa, wskp.cKey, lishc.[lstCount], wm.pp
ORDER BY lsa DESC
OFFSET #PageOffset ROWS FETCH NEXT #PageSize ROWS ONLY
The quick hit here is to add OPTION (RECOMPILE) so SQL Server can eliminate the predicates that correspond to null parameters and create a new plan for each search.
And see, generally Dynamic Search Conditions in T‑SQL
The next thing to do is to get rid of the wildcard searches wherever possible.
And transform this
(CAST(la.lsa AS DATE) BETWEEN CAST(#lsa1 AS DATE) AND CAST(#lsa2 AS DATE)))
into a SARGable pattern like
la.lsa >= #lsa1 and la.lsa < #lsa2
Then start to pull this query apart, and hand-write separate queries for the most common or critical cases.
I am trying to run reporting services with below SQL query
select ca.callingpartynumber, ca.originalcalledpartynumber, case
when calledpartylastname is not null then ca.calledpartylastname + ',' + calledpartyfirstname
else p1.name end,
p1.location, p1.dept, p1.title,
case
when callingpartylastname is not null then ca.callingpartylastname + ',' + callingpartyfirstname
else p3.name end
from calldata.calldetailreport ca
join ps_bc_peoplesource_base p1 on ca.originalcalledpartynumber = replace(p1.bc_int_phone, '-', '')
left outer join ps_bc_peoplesource_base p3 on ca.callingpartynumber = replace(p1.bc_int_phone, '-', '')
where originalcalledpartynumber in (select replace(bc_int_phone, '-', '') internal_modified from ps_bc_peoplesource_base where bc_lan_id = 'f7c')
--and datetimedisconnect between #startdate and #enddate --1221
I get this error-
“An item with the same key has already been added.”
You are missing Column Alias for Two Case Statement in Your SELECT query. As SSRS uses only the column name as the key, not table + column, so it was choking.
Refer Here And Here And Here also
SELECT ca.callingpartynumber, ca.originalcalledpartynumber,
CASE WHEN calledpartylastname IS NOT NULL
THEN ca.calledpartylastname + ',' + calledpartyfirstname
ELSE p1.name END AS calledpartylastname,
p1.location,
p1.dept,
p1.title,
CASE WHEN callingpartylastname IS NOT NULL
THEN ca.callingpartylastname + ',' + callingpartyfirstname
ELSE p3.name END AS callingpartylastname
...
...
I am working with the following query.I want to use Date_Sent_to_Recorder in my other calculations which follows.I am getting an error "Invalid column name 'Date_Sent_to_Recorder'." People recommended using a CTE for this but i am not able to fit it in this scenerio.I have a correlated subquery which calculates Date_Sent_to_Recorder.Please help.
SELECT
C.Name Client ,
SecONdary_Document.Primary_Document_ID ,
SecONdary_Document.Secondary_Document_Id ,
Primary_Document.State + ',' + GB_Counties.CountyName State ,
Grantor.Name Grantor ,
Loan_Number ,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date ,
( SELECT CASE WHEN dbo.SECONDARY_DOCUMENT.Status_ID = 21
THEN CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT.Updated_Dt, 101)
ELSE ( SELECT TOP 1
CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt, 101)
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Secondary_Document_ID = SecONdary_Document.Secondary_Document_Id
AND SECONDARY_DOCUMENT_STATUS_HISTORY.Status_ID = 21
ORDER BY dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt DESC
)
END
) AS Date_Sent_to_Recorder ,
Satis_TimeFrame ,
CASE WHEN PIF_Date IS NULL
OR Date_Sent_to_Recorder IS NULL THEN NULL
ELSE DATEDIFF(DAY, PIF_Date,
Date_Sent_to_Recorder)
END TotalDays ,
CASE WHEN PIF_Date IS NULL
OR Date_Sent_to_Recorder IS NULL THEN NULL
ELSE CASE WHEN DATEDIFF(DAY, PIF_Date,
ISNULL(Date_Sent_to_Recorder,
GETDATE())) > Satis_TimeFrame
THEN 'N'
ELSE 'Y'
END
END InCompliance ,
Loan_Name ,
Deal_Name ,
Deal.Deal_Id ,
Loan.Loan_Id
FROM Primary_Document
INNER JOIN SecONdary_Document ON SecONdary_Document.Primary_Document_ID = Primary_Document.Primary_Document_ID
INNER JOIN Status ON Status.Status_Id = SecONdary_Document.Status_Id
INNER JOIN GB_Counties ON GB_Counties.CountyId = Primary_Document.County_Id
INNER JOIN Loan ON Loan.Loan_Id = Primary_Document.Loan_Id
EDIT------------
DECLARE #Date_Sent_to_Recorder varchar(10)
SELECT C.Name Client ,
SecONdary_Document.Primary_Document_ID ,
SecONdary_Document.Secondary_Document_Id ,
Primary_Document.State + ',' + GB_Counties.CountyName State ,
Grantor.Name Grantor ,
Loan_Number ,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date ,
--<START>
--3021,RRaghuvansi,If current status is 21 in SECONDARY_DOCUMENT then take Updated_Dt else take Created_Dt in SECONDARY_DOCUMENT_STATUS_HISTORY with status Out For Recorder
--CONVERT(VARCHAR(20), Recording_Date, 101) AS Recording_Date ,
#Date_Sent_to_Recorder=[dbo].[GET_RecordingDate](SecONdary_Document.Secondary_Document_Id), --<END>
Satis_TimeFrame ,
Loan_Name ,
Deal_Name ,
Deal.Deal_Id ,
Loan.Loan_Id
FROM Primary_Document
Since your schema is sort of unclear, here is a brief sample for the derived table syntax and referencing values from the derived table
Declare #Sample table(id1 int, id2 int, value varchar(20))
insert into #sample values (1,1, 'this')
insert into #sample values(2,2, 'that')
insert into #sample values(3,2, 'the other')
Select t1.ID1, t1.Value, t2.RevVal,
case
when t2.RevVal = 'siht' then 1 else 0
end as RevIsThisBackwards
from #sample t1
inner join (Select id1, reverse(value) as RevVal from #sample) t2
on t1.ID1 = t2.ID1
Results
id VALUES Rev Rev Value is this backwards
1 this siht 1
2 that taht 0
3 the other rehto eht 0
So you'll want to move the calculated column, and sufficient columns to join to into a derived table, in your case it would it would look similar to the below
INNER JOIN Loan ON Loan.Loan_Id = Primary_Document.Loan_Id
INNER JOIN (Select SomPKField, CASE WHEN dbo.SECONDARY_DOCUMENT.Status_ID = 21
THEN CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT.Updated_Dt, 101)
ELSE ( SELECT TOP 1
CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt, 101)
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE
dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Secondary_Document_ID = SecONdary_Document.Secondary_Document_Id
AND SECONDARY_DOCUMENT_STATUS_HISTORY.Status_ID = 21
ORDER BY dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt DESC
)
END as Date_Sent_to_Recorder
) as Sub1
on SomeTable.SomePKField = Sub1.SomePKField
**I edit your edit in this edit.**
SELECT C.Name Client ,
SecONdary_Document.Primary_Document_ID ,
SecONdary_Document.Secondary_Document_Id ,
Primary_Document.State + ','
+ GB_Counties.CountyName State ,
Grantor.Name Grantor ,
Loan_Number ,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date ,
[dbo].[GET_RecordingDate]
(SecONdary_Document.Secondary_Document_Id)
As Date_Sent_To_Recorder
Satis_TimeFrame ,
Loan_Name ,
Deal_Name ,
Deal.Deal_Id ,
Loan.Loan_Id
FROM Primary_Document
You cannot refer to a computed column in other columns of a SELECT. The simplest solution for what you are trying to achieve is to pre-calculate Date_Sent_to_Recorder and store it in a temporary table, then join to that table when doing your main query.
Protip: use proper formatting and table aliases; SQL like you posted is difficult to read, and almost impossible to understand.
Edit: something like this:
create table #temp
( Primary_Document_ID int,
Date_Sent_To_Recorder datetime )
insert #temp
select Primary_Document_ID,
CASE
WHEN dbo.SECONDARY_DOCUMENT.Status_ID = 21
THEN CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT.Updated_Dt, 101)
ELSE
(SELECT TOP 1
CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt, 101)
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Secondary_Document_ID = SecONdary_Document.Secondary_Document_Id
AND SECONDARY_DOCUMENT_STATUS_HISTORY.Status_ID = 21
ORDER BY dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt DESC)
END
from SecONdary_Document
-- main select, joining to #temp
Because Date_Sent_to_Recorder depends only on SECONDARY_DOCUMENT & SECONDARY_DOCUMENT_STATUS_HISTORY tables, you can replace SECONDARY_DOCUMENT in the INNER JOIN by the following (which gives you Date_Sent_to_Recorder as a column):
SELECT SD.Primary_Document_ID,
SD.Secondary_Document_Id,
CASE WHEN SD.Status_ID = 21
THEN CONVERT(VARCHAR(10), SD.Updated_Dt, 101)
ELSE CONVERT(VARCHAR(10), SDSH.Created_Dt, 101)
END Date_Sent_to_Recorder
FROM SECONDARY_DOCUMENT SD
INNER JOIN dbo.SECONDARY_DOCUMENT_STATUS_HISTORY SDSH
ON SDSH.Secondary_Document_ID = SD.Secondary_Document_Id
AND SDSH.Status_ID = 21
INNER JOIN (SELECT Secondary_Document_ID, max(Created_Dt) Created_Dt
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE Status_ID = 21
GROUP BY Secondary_Document_ID) SDSH2
ON SDSH.Secondary_Document_ID = SDSH2.Secondary_Document_Id
AND SDSH.Created_Dt = SDSH2.Created_Dt
and finally you have:
SELECT C.Name Client,
SecONdary_Document.Primary_Document_ID,
SecONdary_Document.Secondary_Document_Id,
Primary_Document.State + ',' + GB_Counties.CountyName State,
Grantor.Name Grantor,
Loan_Number,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date,
SecONdary_Document.Date_Sent_to_Recorder,
Satis_TimeFrame,
CASE WHEN PIF_Date IS NULL
OR SecONdary_Document.Date_Sent_to_Recorder IS NULL
THEN NULL
ELSE DATEDIFF(DAY, PIF_Date,
SecONdary_Document.Date_Sent_to_Recorder)
END TotalDays,
CASE WHEN PIF_Date IS NULL
OR SecONdary_Document.Date_Sent_to_Recorder IS NULL THEN NULL
ELSE CASE WHEN DATEDIFF(DAY, PIF_Date,
ISNULL(SecONdary_Document.Date_Sent_to_Recorder
,GETDATE())) > Satis_TimeFrame
THEN 'N'
ELSE 'Y'
END
END InCompliance,
Loan_Name,
Deal_Name,
Deal.Deal_Id,
Loan.Loan_Id
FROM Primary_Document
INNER JOIN (SELECT SD.Primary_Document_ID,
SD.Secondary_Document_Id,
CASE WHEN SD.Status_ID = 21
THEN CONVERT(VARCHAR(10), SD.Updated_Dt, 101)
ELSE CONVERT(VARCHAR(10), SDSH.Created_Dt, 101)
END Date_Sent_to_Recorder
FROM SECONDARY_DOCUMENT SD
INNER JOIN dbo.SECONDARY_DOCUMENT_STATUS_HISTORY SDSH
ON SDSH.Secondary_Document_ID = SD.Secondary_Document_Id
AND SDSH.Status_ID = 21
INNER JOIN (SELECT Secondary_Document_ID, max(Created_Dt) Created_Dt
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE Status_ID = 21
GROUP BY Secondary_Document_ID) SDSH2
ON SDSH.Secondary_Document_ID = SDSH2.Secondary_Document_Id
AND SDSH.Created_Dt = SDSH2.Created_Dt) SecONdary_Document
ON SecONdary_Document.Primary_Document_ID
= Primary_Document.Primary_Document_ID
INNER JOIN Status ON Status.Status_Id = SecONdary_Document.Status_Id
INNER JOIN GB_Counties ON GB_Counties.CountyId = Primary_Document.County_Id
INNER JOIN Loan ON Loan.Loan_Id = Primary_Document.Loan_Id