sql order by inside a subquery - sql-server

I have this query:
SELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN ISNUMERIC(dtLu.sLu) = 1 THEN CONVERT(INT, dtLu.sLu) ELSE 9999999 END asc, dtLu.sLu) as row,
dtLu.*, dtLuDerived.cCll, dtMtrDerived.cMtrCll, dtMtrDerived.cMtrCllIn, dtMtrDerived.cMtrCllOut FROM dtLu
LEFT OUTER JOIN (
SELECT pLu, COUNT(pLu) AS cCll
FROM dtCll
GROUP BY pLu)
AS dtLuDerived ON dtLu.pLu = dtLuDerived.pLu
LEFT OUTER JOIN (
SELECT dtCll.pLu, SUM(cMtrCll) AS cMtrCll, SUM(cMtrCllIn) AS cMtrCllIn, SUM(cMtrCllOut) AS cMtrCllOut
FROM dtMtrCll
INNER JOIN dtCll on dtCll.pCll = dtMtrCll.pCll
WHERE dtCll.pWhr IN (SELECT DISTINCT pWhr FROM dtUserWhr WHERE pUser = 5)
GROUP BY dtCll.pLu)
AS dtMtrDerived ON dtLu.pLu = dtMtrDerived.pLu
INNER JOIN dtLct on dtLct.pLct = dtLu.pLct
WHERE dtLu.pLu > 0 AND dtLct.pLctAsl IN (select pAsl from dtAsl where pAslUnt = 1)
-- this is the ORDER I need
ORDER BY dtLu.pLct DESC
) a
WHERE a.row > 0 and a.row <= 17
but if I use the order ORDER BY dtLu.pLct DESC it gives me error...
The ORDER BY clause is invalid in views, inline functions, derived
tables, subqueries, and common table expressions, unless TOP, OFFSET
or FOR XML is also specified.
I searched, found various samples, but my subquery is different, 'cause is needed to retrieve only 17 rows per page (next page will have the last line like this: WHERE a.row > 17 and a.row <=35)
how can I select the top 17 rows but with an order inside?
thanks

You are trying to put the order in your inner query which doesn't work. Move the order by to the main query. Also, you should list your columns instead of using *. You could probably improved this query a bit with fewer subselects but that is outside the scope of your question.
SELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN ISNUMERIC(dtLu.sLu) = 1 THEN CONVERT(INT, dtLu.sLu) ELSE 9999999 END asc, dtLu.sLu) as row,
dtLu.* --you should list the columns out here
, dtLuDerived.cCll, dtMtrDerived.cMtrCll, dtMtrDerived.cMtrCllIn, dtMtrDerived.cMtrCllOut FROM dtLu
LEFT OUTER JOIN (
SELECT pLu, COUNT(pLu) AS cCll
FROM dtCll
GROUP BY pLu)
AS dtLuDerived ON dtLu.pLu = dtLuDerived.pLu
LEFT OUTER JOIN (
SELECT dtCll.pLu, SUM(cMtrCll) AS cMtrCll, SUM(cMtrCllIn) AS cMtrCllIn, SUM(cMtrCllOut) AS cMtrCllOut
FROM dtMtrCll
INNER JOIN dtCll on dtCll.pCll = dtMtrCll.pCll
WHERE dtCll.pWhr IN (SELECT DISTINCT pWhr FROM dtUserWhr WHERE pUser = 5)
GROUP BY dtCll.pLu)
AS dtMtrDerived ON dtLu.pLu = dtMtrDerived.pLu
INNER JOIN dtLct on dtLct.pLct = dtLu.pLct
WHERE dtLu.pLu > 0 AND dtLct.pLctAsl IN (select pAsl from dtAsl where pAslUnt = 1)
-- this is the ORDER I need
--ORDER BY dtLu.pLct DESC
) a
WHERE a.row > 0 and a.row <= 17
order by a.pLct

Use TOP 100 Percent in Subquery
SELECT *
FROM (SELECT top 100 percent Row_number()
OVER (
ORDER BY CASE WHEN Isnumeric(dtLu.sLu) = 1 THEN CONVERT(INT, dtLu.sLu) ELSE 9999999 END ASC, dtLu.sLu) AS row,
dtLu.*,
dtLuDerived.cCll,
dtMtrDerived.cMtrCll,
dtMtrDerived.cMtrCllIn,
dtMtrDerived.cMtrCllOut
FROM dtLu
LEFT OUTER JOIN (SELECT pLu,
Count(pLu) AS cCll
FROM dtCll
GROUP BY pLu) AS dtLuDerived
ON dtLu.pLu = dtLuDerived.pLu
LEFT OUTER JOIN (SELECT dtCll.pLu,
Sum(cMtrCll) AS cMtrCll,
Sum(cMtrCllIn) AS cMtrCllIn,
Sum(cMtrCllOut) AS cMtrCllOut
FROM dtMtrCll
INNER JOIN dtCll
ON dtCll.pCll = dtMtrCll.pCll
WHERE dtCll.pWhr IN (SELECT DISTINCT pWhr
FROM dtUserWhr
WHERE pUser = 5)
GROUP BY dtCll.pLu) AS dtMtrDerived
ON dtLu.pLu = dtMtrDerived.pLu
INNER JOIN dtLct
ON dtLct.pLct = dtLu.pLct
WHERE dtLu.pLu > 0
AND dtLct.pLctAsl IN (SELECT pAsl
FROM dtAsl
WHERE pAslUnt = 1)
-- this is the ORDER I need
ORDER BY dtLu.pLct DESC) a
WHERE a.row > 0
AND a.row <= 17

Related

SQL Server: exclude column row number from distinct?

How can I exclude a column row number from distinct?
The select statement looks like this:
SELECT *
FROM
(SELECT DISTINCT TOP 100
ROW_NUMBER() OVER (ORDER BY Cases.CreatedDate DESC) as row,
Cases.status, Cases.CreatedDate, Cases.DWFCaseId,
Resource.ResourceInfo AS ResourceFullName,
actions.ActionDate, Action.ActionDuedate
FROM
Cases
INNER JOIN
ResourceInfo ON Cases.caseid = ResourceInfo.caseid
LEFT OUTER JOIN
actions ON actions.ActionId = ResourceInfo.ActionId
WHERE
(actions.ActionType = 2)
)
Use the window function in the outer query instead of the subquery as
SELECT *,
ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) as row,
FROM
(
SELECT DISTINCT TOP 100
Cases.status,
Cases.CreatedDate,
Cases.DWFCaseId,
Resource.ResourceInfo AS ResourceFullName,
actions.ActionDate,
Action.ActionDuedate
FROM
Cases
INNER JOIN
ResourceInfo ON Cases.caseid = ResourceInfo.caseid
LEFT OUTER JOIN
actions ON actions.ActionId = ResourceInfo.ActionId
WHERE actions.ActionType = 2
) T; --Don't forget to use an alias for the subquery
Take it out from subquery:
select ROW_NUMBER() OVER (ORDER BY x.CreatedDate desc ) as row, x.*
from (
SELECT DISTINCT top (100)
Cases.status,
Cases.CreatedDate,
Cases.DWFCaseId,
Resource.ResourceInfo AS ResourceFullName,
actions.ActionDate,
Action.ActionDuedate
from Cases
inner join ResourceInfo on Cases .caseid = ResourceInfo .caseid
left outer join actions on actions.ActionId = ResourceInfo .ActionId
WHERE (actions.ActionType = 2)
) x

How to use multiple values in between clause

Hi all is there any way that i can use multiple values in between clause as
column_name between 0 and 100 or 200 and 300 like this
Any help would be appreciated
here is my query SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100
i just want to append multiple values in between clause
This is full query
SELECT ROW_NUMBER() OVER
(
order by Vendor_PrimaryInfo.Vendor_ID asc
)AS RowNumber
, Unit_Table.Unit_title, Vendor_Base_Price.Base_Price, Vendor_Base_Price.showprice, Category_Table.Title, Vendor_Registration.Business_Name,
Vendor_PrimaryInfo.Street_Address, Vendor_PrimaryInfo.Locality, Vendor_PrimaryInfo.Nearest_Landmark, Vendor_PrimaryInfo.City, Vendor_PrimaryInfo.State,
Vendor_PrimaryInfo.Country, Vendor_PrimaryInfo.PostalCode, Vendor_PrimaryInfo.Latitude, Vendor_PrimaryInfo.Longitude, Vendor_PrimaryInfo.ImageUrl,
Vendor_PrimaryInfo.ContactNo, Vendor_PrimaryInfo.Email,Vendor_PrimaryInfo.Vendor_ID
FROM Unit_Table INNER JOIN
Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID INNER JOIN
Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID INNER JOIN
Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID AND
Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID INNER JOIN
Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN
Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID LEFT JOIN
Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
where Vendor_Registration.Category_ID=5 and Vendor_PrimaryInfo.City='City'
AND(
value_text in('Dhol Wala$Shahnai Wala')
or
(SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100
)
You can do this using AND/OR logic
value_text NOT LIKE '%[^0-9]%' and
(
value_text between 0 and 100
Or
value_text between 101 and 200
)
If you don't want to repeat the column name then frame the range in table valued constructor and join with your table
SELECT Row_number()
OVER (
ORDER BY Vendor_PrimaryInfo.Vendor_ID ASC )AS RowNumber,
Unit_Table.Unit_title,
Vendor_Base_Price.Base_Price,
Vendor_Base_Price.showprice,
Category_Table.Title,
Vendor_Registration.Business_Name,
Vendor_PrimaryInfo.Street_Address,
Vendor_PrimaryInfo.Locality,
Vendor_PrimaryInfo.Nearest_Landmark,
Vendor_PrimaryInfo.City,
Vendor_PrimaryInfo.State,
Vendor_PrimaryInfo.Country,
Vendor_PrimaryInfo.PostalCode,
Vendor_PrimaryInfo.Latitude,
Vendor_PrimaryInfo.Longitude,
Vendor_PrimaryInfo.ImageUrl,
Vendor_PrimaryInfo.ContactNo,
Vendor_PrimaryInfo.Email,
Vendor_PrimaryInfo.Vendor_ID
FROM Unit_Table
INNER JOIN Vendor_Base_Price
ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID
INNER JOIN Vendor_PrimaryInfo
ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID
INNER JOIN Vendor_Registration
ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID
AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID
INNER JOIN Category_Table
ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN Vendor_Value_Table
ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID
LEFT JOIN Feature_Table
ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
JOIN (VALUES (0, 100),
(101, 200),
(201, 300)) tc (st, ed)
ON Try_cast(value_text AS INT) BETWEEN st AND ed
OR Try_cast(value_text AS VARCHAR(100)) = 'Dhol Wala$Shahnai Wala'
WHERE Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
Note : You have stored two different information's in a single column which causes lot of pain when you want to extract the data like this. Consider changing your table structure

Top N percent Desc and Top M percent Asc

I am trying to get top 5 customertypes and show data for each 5 customer types, The balance (which can be any amount) I show them as "Other Customer Types". my issue is since the rows can be random and not perfectly divisible by a number then there can be repeated values in the top 5 showing up in the "Other" group which overstates the Total sales.
the Data is also being rendered in SSRS
My code using TOP PERCENT:
select final.[description], sum(final.YTDSales$) as YTDSales$
FROM(
select top 25 percent pytd2.[Description], sum(pytd2.YTDSales$) as YTDSales$
FROM(
-- ytd sales
select re.SIC_Desc as [description], sum((ol.NetAmt - ol.WhlOrdDiscAmt) / #exrt) AS YTDSales$
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN #FStartDate AND #EndDate AND ol.Cono = 1 and ol.VendId IN(#Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.SIC_Desc
)PYTD2
group by pytd2.[description]
order by sum(pytd2.YTDSales$) DESC
UNION ALL
select top 75 percent 'Other' as 'description', sum(pytd.YTDSales$) as YTDSales$
FROM(
-- ytd sales
select re.SIC_Desc as [description], sum((ol.NetAmt - ol.WhlOrdDiscAmt) / #exrt) AS YTDSales$
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN #FStartDate AND #EndDate AND ol.Cono = 1 and ol.VendId IN(#Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.SIC_Desc
)PYTD
group by Ppytd.[description]
order by sum(pytd.YTDSales$)
)final
group by final.[Description]
order by sum(final.YTDSales$) DESC
my results:
As you can see the Large Independent and Other has the same figure of $2280.60 in YTDQty since it is being repeated
I was picturing something like this:
with data as (
-- your base query here grouped and summarized by customer type
), rankedData as (
select *, row_number() over (order by YTDSales$ desc) as CustTypeRank
from data
)
select
case when CustTypeRank <= 5 then min("description") else 'Others' end as "description",
sum(YTDSales$) as YTDSales$
from rankedData
group by case when CustTypeRank <= 5 then CustTypeRank else 999 end
order by case when CustTypeRank <= 5 then CustTypeRank else 999 end
I actually used RANK instead which worked great :-
select 0 as rankytd, RANK() OVER(ORDER BY sum(ol.NetAmt - ol.WhlOrdDiscAmt) DESC) as rankpytd, re.sic, ol.VendId, vd.name, re.SIC_Desc As [description], 0 AS YTDQty, sum(ol.Quantity) AS PYTDQty
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join dbo.Product p on ol.Cono = p.Cono and ol.prodid = p.ProdId and p.ProdCatId in (#pcat)
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN DATEADD(YEAR, -1,#FStartDate) AND DATEADD(YEAR, -1, #EndDate) and ol.Cono = 1 and ol.VendId IN(#Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.sic, ol.VendId, vd.Name, re.SIC_Desc

GROUP BY in SQL Server in complex query

I need to group this by T.TopicID to only receive the last result.
Whatever I try I get errors like the other T. items rant included in group by or aggregate etc
ALTER PROCEDURE [dbo].[SPGetFollowingTopics]
#id int = null
,#UserGroupId int = null
,#lastvisit DateTime = null
AS
SELECT *
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY TopicOrder DESC,
(CASE
WHEN M.MessageCreationDate > T.TopicCreationDate
THEN M.MessageCreationDate
ELSE T.TopicCreationDate
END) DESC) AS RowNumber,
T.TopicId, T.TopicTitle, T.TopicShortName,
T.TopicDescription, T.TopicCreationDate, T.TopicViews,
T.TopicReplies, T.UserId, T.TopicTags, T.TopicIsClose,
T.TopicOrder, T.LastMessageId, U.UserName,
M.MessageCreationDate, T.ReadAccessGroupId,
T.PostAccessGroupId, TF.userid AS Expr1, U.UserGroupId,
U.UserPhoto, U.UserFullName, M.UserId AS MessageUserId,
MU.UserName AS MessageUserName
FROM
Topics AS T
LEFT OUTER JOIN
Messages AS M ON M.TopicId = T.TopicId AND M.Active = 1 AND M.MessageCreationDate < #lastvisit
INNER JOIN
topicfollows AS TF ON T.TopicId = TF.topicid
INNER JOIN
Users AS U ON U.UserId = T.UserId
LEFT JOIN
Users MU ON MU.UserId = M.UserId
WHERE
(TF.userid = #id)
) T
It isn't clear what the requirement is (in my view) but I think you are seeking:
"the latest message"
PER TOPIC
for a given user
In this situation ROW_NUMBER() is a good option but I believe you need to PARTITION the ROW_NUMBER as well as ordering it.
SELECT
*
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY TF.userid, T.TopicId
ORDER BY
(CASE
WHEN M.MessageCreationDate > T.TopicCreationDate THEN M.MessageCreationDate
ELSE T.TopicCreationDate
END) DESC) AS ROWNUMBER
, T.TopicId, T.TopicTitle, T.TopicShortName, T.TopicDescription
, T.TopicCreationDate, T.TopicViews, T.TopicReplies, T.UserId
, T.TopicTags, T.TopicIsClose, T.TopicOrder, T.LastMessageId
, U.UserName, M.MessageCreationDate, T.ReadAccessGroupId
, T.PostAccessGroupId, TF.userid AS EXPR1
, U.UserGroupId, U.UserPhoto, U.UserFullName
, M.UserId AS MESSAGEUSERID, MU.UserName AS MESSAGEUSERNAME
FROM Topics AS T
LEFT OUTER JOIN Messages AS M ON M.TopicId = T.TopicId
AND M.Active = 1
AND M.MessageCreationDate < #lastvisit
INNER JOIN topicfollows AS TF ON T.TopicId = TF.topicid
INNER JOIN Users AS U ON U.UserId = T.UserId
LEFT JOIN Users MU ON MU.UserId = M.UserId
WHERE (TF.userid = #id)
) T
WHERE ROWNUMBER = 1
You could change your left join to any outer apply, and add TOP 1:
SELECT ...
FROM
Topics AS T
OUTER APPLY
( SELECT TOP 1 M.MessageCreationDate, M.UserId
FROM Messages AS M
WHERE M.TopicId = T.TopicId
AND M.Active = 1
AND M.MessageCreationDate < #lastvisit
ORDER BY M.MessageCreationDate DESC
) AS m
This allows you to use TOP 1 and still get one row per topicID
Alternatively you can use ROW_NUMBER() OVER(PARTITION BY m.TopicID ORDER BY M.MessageCreationDate DESC)
SELECT ...
FROM
Topics AS T
LEFT OUTER JOIN
( SELECT M.TopicId,
M.MessageCreationDate,
M.UserId,
RowNum = ROW_NUMBER() OVER(PARTITION BY m.TopicID ORDER BY M.MessageCreationDate DESC)
FROM Messages AS M
WHERE M.Active = 1
AND M.MessageCreationDate < #lastvisit
) AS m
ON M.TopicId = T.TopicId
AND m.RowNum = 1
I would test both methods and see which one works best for you.

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