2

我需要在 MS-SQL 数据库中过滤带有关系表的表。

我得到:

persId  persName1   catId

 4        Hans        0
 4        Hans        51
 4        Hans        73
 5        Torleif     0
 5        Torleif     5
 5        Torleif    73
 5        Torleif    76
 6        Peter       0
 6        Peter      51
 6        Peter      73
 7        Jonas       0
 7        Jonas      16
 7        Jonas      73

和:

SELECT   distinct  tblPerson.persId
, tblPerson.persName1
, relCatPers.catId
FROM         tblPerson LEFT OUTER JOIN
             relCatPers ON tblPerson.persId = relCatPers.persId

但是我需要。删除 catId 为 51 的那些。并且名称和 ID 仅出现 1 次:

persId  persName1

  5         Torleif
  7         Jonas

桌子:

CREATE TABLE [dbo].[tblPerson](
    [persId] [int] IDENTITY(1,1) NOT NULL,
    [persName1] [varchar](255) NULL,
CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED 
)


CREATE TABLE [dbo].[relCatPers](
    [rcpId] [int] IDENTITY(1,1) NOT NULL,
    [catId] [int] NOT NULL,
    [persId] [int] NOT NULL,
CONSTRAINT [PK_relCatPers] PRIMARY KEY CLUSTERED
)
4

3 回答 3

3

尝试这个:

Fiddle 1 演示在这里

select distinct p.persId, p.persName1 
from   tblPerson p left join 
         relCatPers c on p.persId = c.persId
where  p.persId not in
       (select persId from relCatPers where catId = 51)

或者您可以忽略relCatPers表格并执行以下操作

Fiddle 2 演示在这里

select p.persId, p.persName1 
from   tblPerson p 
where  p.persId not in
       (select persId from relCatPers where catId = 51)
于 2013-03-14T09:48:02.887 回答
1

尝试这个 :

With cte as 
(Select persId,persName1,
        row_number() over (partition by persId,persName1 order by persID) as rn
 from tblPerson 
)
Select cte.persID,cte.persName1
from relCatPers
left join cte
on tblPerson.persId = relCatPers.persId
where relCatPers.catid=51  and
rn=1
于 2013-03-14T08:50:32.397 回答
1

我已经编辑了查询,因此它不会返回您的问题中定义的 catId:

SELECT distinct
       tblPerson.persId
       ,tblPerson.persName1
FROM   tblPerson
LEFT OUTER JOIN relCatPers ON tblPerson.persId = relCatPers.persId
WHERE  tblPerson.persId NOT IN 
       (SELECT persId FROM relCatPers WHERE catId = 51);

如果您想添加额外的 catId 以排除人员,您可以WHERE将子查询中的子句更改为 example WHERE catId IN (16, 23, 51)

于 2013-03-14T09:16:14.737 回答