8

我有以下表名 JobTitle

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

我正在从表中选择所有记录,除了重复的 JobID 的 count > 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 子句。是否应遵循任何不同的方法。否则我如何修改查询以获得所需的输出

4

2 回答 2

9
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

于 2013-09-24T17:07:10.497 回答
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

结果

| 乔比 | 语言ID |
--------|-------------|
| 1 | 1 |
| 2 | 1 |
| 3 | 4 |
| 4 | 5 |
| 5 | 2 |

查看演示

于 2013-09-24T17:08:03.553 回答