Duplicate records with Multiple joins - sql-server

I had written a join query statement. that statement returns me multiple(duplicate) row again even though I'm having only single record on that.
declare #BenefitClass int ;
set #BenefitClass = (select BenefitClass From HJOB where userid='d76c5000-69e0-461e-92e1-3cfe7590d098' and CompanyId =1629)
select #BenefitClass;
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098' and bhsac.PlanInfoId=38044
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId and oems.EndDt > GETDATE()
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
For that I'm getting the result as second row as duplicate :
observe the result

Try this once it may help you
declare #BenefitClass int ;
set #BenefitClass = (select BenefitClass From HJOB where userid='d76c5000-69e0-461e-92e1-3cfe7590d098' and CompanyId =1629)
select #BenefitClass;
;with cte as (
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098' and bhsac.PlanInfoId=38044
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId and oems.EndDt > GETDATE()
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
)
select distinct EmployerContribution,
CatchUpValue ,Tier,planYear,Ischecked,EmployeeContribute,Id ,Value ,HSALmitId from cte

Please change your where condition as below:
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098'
and bhsac.PlanInfoId=38044
and oems.EndDt > GETDATE()

Related

Is there a way that I can return multiple columns from a subquery rather than repeating the subquery for each column? It works but takes too long

As you can see I'm trying to add 4 columns by repeating the subquery,
this works but takes too long to be useful. I tried to put all the
joins at the end but then I only get the records that have values in
[dbo.permit_terms] whereas I want all the records from [dbo.prd]. I hope this makes
sense and will be very grateful for an answer.
SELECT WLC.name AS WELLCOMPL
, WLC.id_subsidiary AS SUB
, PD.Date
, PD.days
, PD.oil
, PD.water
, PD.gas
, PD.interest
, PD.operator
, PD.comments
, (
SELECT PT.net_working_int_oil
FROM dbo.prd AS P (NOLOCK)
left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
left JOIN dbo.permit WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
-- AND W.[name] = WLC.[name]
AND p.id = pd.id
AND pd.id_subsidiary = w.id_subsidiary
AND P.deletedAt Is Null
AND W.deletedAt Is Null
AND dbo.wellstring.deletedAt Is Null
AND dbo.permit.deletedAt Is Null
AND wb.deletedAt Is Null
AND PT.deletedAt Is Null
)
as permit_interest
, (
SELECT PT.operator
FROM dbo.prd AS P (NOLOCK)
left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
left JOIN dbo.permit WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
-- AND W.[name] = WLC.[name]
AND p.id = pd.id
AND pd.id_subsidiary = w.id_subsidiary
AND P.deletedAt Is Null
AND W.deletedAt Is Null
AND dbo.wellstring.deletedAt Is Null
AND dbo.permit.deletedAt Is Null
AND wb.deletedAt Is Null
AND PT.deletedAt Is Null
)
as permit_operator
, (
SELECT pd.oil*PT.net_working_int_oil/100
FROM dbo.prd AS P (NOLOCK)
left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
left JOIN dbo.permit WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
-- AND W.[name] = WLC.[name]
AND p.id = pd.id
AND pd.id_subsidiary = w.id_subsidiary
AND P.deletedAt Is Null
AND W.deletedAt Is Null
AND dbo.wellstring.deletedAt Is Null
AND dbo.permit.deletedAt Is Null
AND wb.deletedAt Is Null
AND PT.deletedAt Is Null
)
as Oil_net
, (
SELECT pd.gas*PT.net_working_int_gas/100
FROM dbo.prd AS P (NOLOCK)
left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
left JOIN dbo.permit WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
-- AND W.[name] = WLC.[name]
AND p.id = pd.id
AND pd.id_subsidiary = w.id_subsidiary
AND P.deletedAt Is Null
AND W.deletedAt Is Null
AND dbo.wellstring.deletedAt Is Null
AND dbo.permit.deletedAt Is Null
AND wb.deletedAt Is Null
AND PT.deletedAt Is Null
)
as Gas_net
FROM (dbo.prd AS PD
INNER JOIN dbo.wellbore_compl AS WLC ON (PD.id_subsidiary = WLC.id_subsidiary) AND (PD.id_wellborecompl = WLC.id))
WHERE
PD.deletedAt Is Null
AND WLC.deletedAt Is Null
This should get you close
Select WELLCOMPL = WLC.name
, SUB = WLC.id_subsidiary
, PD.Date
, PD.days
, PD.oil
, PD.water
, PD.gas
, PD.interest
, PD.operator
, PD.comments
, permit_interest = tt.net_working_int_oil
, permit_operator = tt.operator
, Oil_net = PD.oil * tt.net_working_int_oil / 100
, Gas_net = PD.gas * tt.net_working_int_gas / 100
From dbo.prd PD With (NoLock)
Inner Join dbo.wellbore_compl WLC With (NoLock) On PD.id_subsidiary = WLC.id_subsidiary
And pd.id_wellborecompl = WLC.id
Cross Apply (Select PT.operator
, PT.net_working_int_oil
, PT.net_working_int_gas
From dbo.wellstring ws With (NoLock)
Inner Join dbo.wellbore wb With (NoLock) On wb.id = ws.id_wellbore
Inner Join dbo.wellbore_permit WP With (NoLock) On WP.id_wellbore = wb.id
Inner Join dbo.permit p With (NoLock) On p.id = WP.id_permit
Inner Join dbo.permit_terms PT With (NoLock) On PT.id_permit = p.id
Where ws.id = WLC.id_wellstring -- this ties us back to the outer query
And PD.[date] >= pt.Start_Date -- this ties back to date on outer PD table
And pd.[date] <= pt.end_date -- this ties back to date on outer PD table
And ws.deletedAt Is Null
And wb.deletedAt Is Null
And p.deletedAt Is Null
And PT.deletedAt Is Null
) tt
Where PD.deletedAt Is Null
And WLC.deletedAt Is Null;
As already stated - remove NOLOCK hints unless you are sure that you understand the risks associated with using it.
Now you can add any additional columns needed from the permit (PT) table and define your calculations based off those values. This assumes you will always have related values and are only interested in showing those that actually have values.
If you need to show all, even if there is no wellstring, wellbore, permit, etc... then change the cross apply to an outer apply and you will get NULL values for all of your calculations.

SQL Server 2005 Select Data From Table1 and Table2 but if Table2 column1 value is null Select Data From Table3

My Query IS
SELECT TblPharmacyBillingDetails.UPBNo, TblMasterBillingData.IPDNo, InPatRegistration.PatTitle+PatientName, TblPharmacyBillingDetails.InvoiceNo, TblPharmacyBillingDetails.InvoiceDateTime, TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
but if TblMasterBillingData.IPDNo value is NULL select Data From TblMasterBillingData.OPDNo and
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.IPDNo
Method #1: Using UNION
SELECT * FROm
(
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.IPDNo,
InPatRegistration.PatTitle+PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
WHERE TblMasterBillingData.IPDNo IS NOT NULL
UNION ALL
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.OPDNo,
OutPatRegistration .PatTitle + PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.OPDNo
WHERE TblMasterBillingData.OPDNo IS NOT NULL
)Tmp
ORDER BY TblPharmacyBillingDetails.UPBNo
Method #2 Using ISNULL and LEFT JOIN
SELECT TblPharmacyBillingDetails.UPBNo,
ISNULL(TblMasterBillingData.IPDNo,TblMasterBillingData.OPDNo),
ISNULL(IP.PatTitle + IP.PatientName, OP.PatTitle + OP.PatientName),
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
LEFT JOIN InPatRegistration IP ON TblMasterBillingData.IPDNo = IP.IPDNo
LEFT JOIN outPatRegistration OP ON TblMasterBillingData.OPDNo = OP.OPDNo
ORDER BY TblPharmacyBillingDetails.UPBNo
You can write either case statement or ISNULL() function as shown below in the demo query.
SELECT
Orders.OrderID,
Case when Customers1.CustomerName is null then Customers2.CustomerName else Customers1.CustomerName
end as CustomerName, --way 1
ISNULL(Customers1.CustomerName, Customers2.CustomerName) as Customer, --way 2
Orders.OrderDate
FROM Orders
INNER JOIN Customers1 ON Orders.CustomerID = Customers1.CustomerID
INNER JOIN Customers2 ON Orders.CustomerID = Customers2.CustomerID
-- where your condition here
-- order by your column name
You can also check whether data is available or not in the table and join the table accordingly using if exists as shown below.
if exists(select 1 from tablename where columnname = <your values>)

alternative to sub query in join

I have a SQL query that I'm trying to optimize.
Is there a better way to avoid using subquery here?
Got a suggestion on using Row_number(),
posting this with some corrections
DECLARE #curdate DATETIME
SET #curdate = GETDATE()
SELECT DISTINCT
SIS.StudentID, StudentCoverage.StudentCoverageDataID,
Student.FirstName, Student.LastName,
Student.DateOfBirth, Student.Gender,
ASMT.AssessmentDate
FROM
SIS (NOLOCK)
INNER JOIN
SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
INNER JOIN
Assessment ASMT ON SIS.StudentID = ASMT.StudentId
INNER JOIN
StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
INNER JOIN
Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
INNER JOIN
Student (NOLOCK) ON Student.StudentID = SIS.StudentID
INNER JOIN
StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
AND StudentCoverageData.StudentCoverageDataID = (SELECT TOP 1 StudentCoverageData.StudentCoverageDataID
FROM StudentCoverage
INNER JOIN StudentCoverageData ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
WHERE StudentCoverage.StudentId = SIS.StudentID
AND StudentCoverageData.Active = 1
AND StudentCoverageData.EffectiveDate <= #curdate
AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > #curdate)
ORDER BY StudentCoverageData.AsOfDate DESC)
All Tables in your subquery is exists in inner join clause, so you could rewrite your query like this:
;WITH temps AS
(
DECLARE #curdate DATETIME = GETDATE()
SELECT
SIS.StudentID, StudentCoverage.StudentCoverageDataID,
Student.FirstName, Student.LastName,
Student.DateOfBirth, Student.Gender,
ASMT.AssessmentDate,
ROW_NUMBER() OVER (PARTITION BY StudentCoverageData.StudentCoverageDataID ORDER BY StudentCoverageData.AsOfDate) AS RowIndex
FROM
SIS (NOLOCK)
INNER JOIN
SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
INNER JOIN
StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
INNER JOIN
Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
INNER JOIN
Student (NOLOCK) ON Student.StudentID = SIS.StudentID
INNER JOIN
StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
WHERE StudentCoverageData.Active = 1
AND StudentCoverageData.EffectiveDate <= #curdate
AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > #curdate)
)
SELECT * FROM temps t
WHERE t.RowIndex = 1

How to return latest record from SQL Server

I have this query:
SELECT
t_ticket.ticketID, t_ticket.addedDate, t_ticket.question,
t_ticket.code, t_ticket.priority, t_orgSection.title,
t_actionTicket.addedDateAction, t_actionTicket.title AS Expr1
FROM
t_actionTicket
INNER JOIN
t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID
INNER JOIN
t_orgSection ON t_ticket.orgSectionID_FK = t_orgSection.orgSectionID
WHERE
(t_ticket.userID_FK = #userid) AND (t_ticket.cusDelete = 0)
I want to return just the latest record in t_actionTicket table for each row in t_ticket table.
You can use row_number to pick just the top row for each ticket ID, by ordering by your date and then making row = 1 one of your join criteria. See as follows:
Replace
FROM t_actionTicket INNER JOIN
t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID
with
FROM
(select *
, row_number() over (partition by ticketID_FK order by TicketActionDate desc) as RN
from t_actionTicket ) at
INNER JOIN t_ticket
ON at.ticketID_FK = t_ticket.ticketID and at.RN = 1
I guessed at the name of your date column in ActionTicket, so you will probably need to change that.
You can try this one too, just alternative:
SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question,t_ticket.code, t_ticket.priority, t_orgSection.title,t_actionTicket.addedDateAction, t_actionTicket.title AS Expr1
FROM t_ticket INNER JOIN
(select TOP 1 t_actionTicket.* from t_actionTicket INNER JOIN
t_ticket on t_ticket.ticketID = t_actionTicket.ticketID_FK ORDER BY
t_actionTicket.addedDateAction DESC ) AS t_actionTicket
ON t_actionTicket.ticketID_FK = t_ticket.ticketID
INNER JOIN t_orgSection ON t_ticket.orgSectionID_FK = t_orgSection.orgSectionID
WHERE (t_ticket.userID_FK = #userid) AND (t_ticket.cusDelete = 0)
I assume that addedDateAction uses timestamp when new record is inserted.
I find this solution
SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question,
t_ticket.code, t_ticket.priority, t_actionTicket.addedDateAction,
t_actionTicket.title AS Expr1
FROM t_actionTicket INNER JOIN t_ticket ON
t_actionTicket.ticketID_FK = t_ticket.ticketID INNER JOIN
(SELECT ticketID_FK, MAX(addedDateAction) AS maxDate
FROM t_actionTicket AS t_actionTicket_1
GROUP BY ticketID_FK) AS b ON t_actionTicket.ticketID_FK = b.ticketID_FK AND t_actionTicket.addedDateAction = b.maxDate
WHERE (t_ticket.userID_FK = #userid) AND (t_ticket.cusDelete = 0)

ROW_NUMBER() vs. DISTINCT

I have a problem with ROW_NUMBER() , if i used it with DISTINCT in the following Query
I have 2 scenarios:
1- run this query direct : give me for example 400 record as a result
2- uncomment a line which start with [--Uncomment1--] : give me 700 record as a result
it duplicated some records not all the records
what I want is to solve this problem or to find any way to show a row counter beside each row, to make a [where rownumber between 1 and 30] --Uncomment2--
if I put the whole query in a table, and then filter it , it is work but it still so slow
waiting for any feedback and I will appreciate that
Thanks in advance
SELECT * FROM
(SELECT Distinct CRSTask.ID AS TaskID,
CRSTask.WFLTaskID,
--Uncomment1-- ROW_NUMBER() OVER (ORDER By CRSTask.CreateDate asc ) AS RowNum ,
CRSTask.WFLStatus AS Task_WFLStatus,
CRSTask.Name AS StepName,
CRSTask.ModifiedDate AS Task_ModifyDate,
CRSTask.SendingDate AS Task_SendingDate,
CRSTask.ReceiveDate AS Task_ReceiveDate,
CRSTask.CreateDate AS Task_CreateDate,
CRS_Task_Recipient_Vw.Task_CurrentSenderName,
CRS_Task_Recipient_Vw.Task_SenderName,
CRS_INFO.ID AS CRS_ID,
CRS_INFO.ReferenceNumber,
CRS_INFO.CRSBeneficiaries,
CRS_INFO.BarCodeNumber,
ISNULL(dbo.CRS_FNC_GetTaskReceiver(CRSTask.ID), '') + ' ' + ISNULL
(CRS_Organization.ArName, '')
AS OrgName,
CRS_Info.IncidentID,
COALESCE(CRS_Subject.ArSubject, 'غير مبين') AS ArSubject,
COALESCE(CRS_INFO.Subject, 'Blank Subject') AS CRS_Subject,
CRS_INFO.Mode,
CRS_Task_Recipient_Vw.ReceiverID,
CRS_Task_Recipient_Vw.ReceiverType,
CRS_Task_Recipient_Vw.CC,
Temp_Portal_Users_View.ID AS CRS_LockedByID,
Temp_Portal_Users_View.ArabicName AS CRS_LockedByName,
CRSDraft.ID AS DraftID,
CRSDraft.Type AS DraftType,
CASE
WHEN CRS_Folder = 1 THEN Task_SenderName
WHEN CRS_Folder = 2 THEN Task_SenderName
WHEN CRS_Folder = 3 THEN Task_CurrentSenderName
END AS SenderName,
CRS_Task_Folder_Vw.CRS_Folder,
CRS_INFO.Status,
CRS_INFO.CRS_Type,
CRS_Type.arName AS CRS_Type_Name
FROM CRS_Task_Folder_Vw
LEFT OUTER JOIN CRSTask
ON CRSTask.ID = CRS_Task_Folder_Vw.TaskID
LEFT OUTER JOIN CRS_INFO
ON CRS_INFO.ID = CRSTask.CRSID
LEFT OUTER JOIN CRS_Subject
ON COALESCE(
SUBSTRING(
CRS_INFO.Subject,
CHARINDEX('_', CRS_INFO.Subject) + 1,
LEN(CRS_INFO.Subject)
),
'Blank Subject'
) = CRS_Subject.ID
LEFT OUTER JOIN CRSInfoAttribute
ON CRS_INFO.ID = CRSInfoAttribute.ID
LEFT OUTER JOIN CRS_Organization
ON CRS_Organization.ID = CRSInfoAttribute.SourceID
LEFT OUTER JOIN CRS_Type
ON CRS_INFO.CRS_Type = CRS_Type.ID
LEFT OUTER JOIN CRS_Way
ON CRS_INFO.CRS_Send_Way = CRS_Way.ID
LEFT OUTER JOIN CRS_Priority
ON CRS_INFO.CRS_Priority_ID = CRS_Priority.ID
LEFT OUTER JOIN CRS_SecurityLevel
ON CRS_INFO.SecurityLevelID = CRS_SecurityLevel.ID
LEFT OUTER JOIN Portal_Users_View
ON Portal_Users_View.ID = CRS_INFO.CRS_Initiator
LEFT OUTER JOIN AD_DOC_TBL
ON CRS_INFO.DocumentID = AD_DOC_TBL.ID
LEFT OUTER JOIN CRSTask AS Temp_CRSTask
ON CRSTask.ParentTask = Temp_CRSTask.ID
LEFT OUTER JOIN Portal_Users_View AS Temp_Portal_Users_View
ON Temp_Portal_Users_View.ID = AD_DOC_TBL.Lock_User_ID
LEFT OUTER JOIN Portal_Users_View AS Temp1_Portal_Users_View
ON Temp1_Portal_Users_View.ID = CRS_INFO.ClosedBy
LEFT OUTER JOIN CRSDraft
ON CRSTask.ID = CRSDraft.TaskID
LEFT OUTER JOIN CRS_Task_Recipient_Vw
ON CRSTask.ID = CRS_Task_Recipient_Vw.TaskID
--LEFT OUTER JOIN CRSTaskReceiverUsers ON CRSTask.ID =
CRSTaskReceiverUsers.CRSTaskID AND CRS_Task_Recipient_Vw.ReceiverID = CRSTaskReceiverUsers.ReceiverID
LEFT OUTER JOIN CRSTaskReceiverUserProfile
ON CRSTask.ID = CRSTaskReceiverUserProfile.TaskID
WHERE Crs_Info.SUBJECT <> 'Blank Subject'
AND (CRS_INFO.Subject NOT LIKE '%null%')
AND CRS_Info.IsDeleted <> 1
/* AND CRSTask.WFLStatus <> 6
AND CRSTask.WFLStatus <> 8 */
AND (
(
CRS_Task_Recipient_Vw.ReceiverID IN (1, 29)
AND CRS_Task_Recipient_Vw.ReceiverType IN (1, 3, 4)
)
)
AND 1 = 1
)Codes
--Uncomment2-- WHERE Codes.RowNum BETWEEN 1 AND 30
ORDER BY
Codes.Task_CreateDate ASC
If the issue is that you have duplicate rows and DISTINCT is failing because the ordinal row number is making each row unique; try (with DISTINCT):
DENSE_RANK() OVER (ORDER By CRSTask.CreateDate asc)
You can also remove the DISTINCT and GROUP BY everything in the CTE.

Resources