使用分区依据的SQL查询

时间:2013-09-24 17:00:17

标签: sql sql-server sql-server-2008

我有以下表名JobTitle

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

我正在从表格中选择所有记录,除了重复的JobID的计数> 1.我只从重复的JobID中选择一个记录/第一行。 现在我将LanguageID作为参数传递给存储过程,我想为该languageID选择重复的JobID以及其他记录。 如果我已将languageID作为1传递,则输出应如下所示

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

我尝试过使用以下查询。

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
)

但是我无法在上面的查询中使用WHERE子句。 是否应遵循任何不同的方法。或者我如何修改查询以获得所需的输出

2 个答案:

答案 0 :(得分:8)

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

<强>更新

简化了一点(删除了联接),但你会明白:

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

答案 1 :(得分:3)

SELECT b.[JobID], b.[LanaguageID]
FROM
  (SELECT a.[JobID], a.[LanaguageID],
    ROW_NUMBER() OVER(PARTITION BY a.[JobID] ORDER BY a.[LanaguageID]) AS [row]
  FROM [JobTitle] a) b
WHERE b.[row] = 1

<强>结果

| JOBID | LANAGUAGEID |
--------|-------------|
|     1 |           1 |
|     2 |           1 |
|     3 |           4 |
|     4 |           5 |
|     5 |           2 |

See a demo