Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query using Partition By

I have following table name JobTitle

JobID LanaguageID
-----------------
1         1
1         2
1         3
2         1
2         2 
3         4
4         5
5         2

I am selecting all records from table except duplicate JobID's for which count > 1. I am selecting only one record/first row from the duplicate JobID's. Now I am passing LanguageID as paramter to stored procedure and I want to select duplicate JobID for that languageID along with the other records Also. If I have passed languageID as 1 then output should come as follows

JobID LanaguageID
-----------------
1         1
2         1
3         4
4         5
5         2

I have tried using following query.

with CTE_RN as
(
    SELECT ROW_NUMBER() OVER(PARTITION BY JobTitle.JobID ORDER BY JobTitle.JobTitle) AS RN
    FROM JobTitle
    INNER JOIN JobTitle_Lang
        ON JobTitle.JobTitleID = JobTitle_Lang.JobTitleID
)

But I am unable to use WHERE clause in the above query. Is any different approch should be followed. Or else how can i modify the query to get the desired output

like image 860
XamDev Avatar asked Sep 24 '13 17:09

XamDev


1 Answers

with CTE_RN as
(
    SELECT
        JobID, LanaguageID,
        ROW_NUMBER() OVER(PARTITION BY JobTitle.JobID ORDER BY JobTitle.JobTitle) AS RN
    FROM JobTitle
        INNER JOIN JobTitle_Lang ON JobTitle.JobTitleID = JobTitle_Lang.JobTitleID
)
select
from CTE_RN
where RN = 1 or LanguageID = @LanguageID

update

simplified a bit (join removed), but you'll get the idea:

declare @LanguageID int = 2

;with cte_rn as
(
    select
        JobID, LanguageID,
        row_number() over(
          partition by JobTitle.JobID
          order by
              case when LanguageID = @LanguageID then 0 else 1 end, 
              LanguageID
        ) as rn
    from JobTitle
)
select *
from cte_rn
where rn = 1

sql fiddle demo

like image 188
Roman Pekar Avatar answered Oct 18 '22 08:10

Roman Pekar