Feb 26, 2016

Avoid duplicate rows by keep same order in SQL Server


I am looking for another solution for my sql query result.
My query below returns
SELECT 
    M.Mroutes_srno, M.Mroutes_loginid 
FROM
    Mroutes M
LEFT JOIN 
    MAccSanctioningLimit Limit ON M.mroutes_role = Limit.sac_type
                               AND M.Mroutes_moduleno = Limit.sac_moduleno
                               AND M.Mroutes_companycd = Limit.company_cd
WHERE
    M.mroutes_deptcd = 'BKAF'
    AND M.Mroutes_moduleno = 145
    AND M.mroutes_role NOT IN ('MIS', 'CFO', 'MD')
Output:
Mroutes_srno    Mroutes_loginid
--------------------------------
1   --------    AIJ1546
2   --------    BCS8021
3   --------    AIJ1546
4   --------    BCS8021
5   --------    venkatesh
6   --------    151N1636
But, after removing duplicate rows it result like below.
SELECT  
    M.Mroutes_loginid  
FROM
    Mroutes M
LEFT JOIN 
    MAccSanctioningLimit Limit ON M.mroutes_role = Limit.sac_type
                               AND M.Mroutes_moduleno = Limit.sac_moduleno
                               AND M.Mroutes_companycd = Limit.company_cd
WHERE 
    M.mroutes_deptcd = 'BKAF'
    AND M.Mroutes_moduleno = 145
    AND M.mroutes_role NOT IN ('MIS', 'CFO', 'MD')
GROUP BY
    M.Mroutes_loginid 
Output:
Mroutes_loginid
---------------
151N1636
AIJ1546
BCS8021
venkatesh
I need to keep the query in same order.

Answer 

You need to use row_number window function:
;WITH cte AS(
SELECT M.Mroutes_srno,
       M.Mroutes_loginid,
       ROW_NUMBER() OVER(PARTITION BY M.Mroutes_loginid ORDER BY M.Mroutes_srno) rn 
from Mroutes M
left JOIN MAccSanctioningLimit  Limit on M.mroutes_role =Limit.sac_type
    and  M.Mroutes_moduleno = Limit.sac_moduleno
    and M.Mroutes_companycd = Limit.company_cd
where M.mroutes_deptcd ='BKAF'
and M.Mroutes_moduleno =145
and M.mroutes_role NOT in ('MIS', 'CFO', 'MD'))

SELECT Mroutes_srno, Mroutes_loginid
FROM cte 
WHERE rn = 1
ORDER BY Mroutes_srno
Or you can order by aggregation like:
SELECT  M.Mroutes_loginid  
from Mroutes M
left JOIN MAccSanctioningLimit  Limit on M.mroutes_role =Limit.sac_type
    and  M.Mroutes_moduleno = Limit.sac_moduleno
    and M.Mroutes_companycd = Limit.company_cd
where M.mroutes_deptcd ='BKAF'
and M.Mroutes_moduleno = 145
and M.mroutes_role NOT in ('MIS', 'CFO', 'MD')
group by M.Mroutes_loginid
order by min(M.Mroutes_srno)

What is the use of n-tier architecture and 3-tier architecture?

how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it ...