获取具有相同“文本”但不同“代码”的记录

时间:2013-02-19 09:53:01

标签: sql sql-server

我有一个如下表(使用SQL Server 2008 R2 Enterprise):

create table Message
(
ID int Not Null Primary Key,
Text nvarchar(100) not null,
Code nvarchar(50) null
)

Insert Into Message Values (1,'Hello Everybody','T6/45')
Insert Into Message Values (2,'Hello Everybody',Null)
Insert Into Message Values (3,'Hello Everybody','T6/45')
Insert Into Message Values (4,'Hello Everybody','T6/45')
Insert Into Message Values (5,'Hello Everybody','T6/70')
Insert Into Message Values (6,'Hello Everybody','T6/70')
Insert Into Message Values (7,'Hello','T6/70')
Insert Into Message Values (8,'Hello','T6/45')
Insert Into Message Values (9,'Hello Everybody',Null)
Insert Into Message Values (10,'Hello Everybody','T6/70')
Insert Into Message Values (11,'Hello',Null)

我需要获取具有相同Text但不同Code的所有记录。 Code不会是Null

所以预期的产出将是:

Insert Into Message Values (1,'Hello Everybody','T6/45')
Insert Into Message Values (5,'Hello Everybody','T6/70')
Insert Into Message Values (7,'Hello','T6/70')
Insert Into Message Values (8,'Hello','T6/45')

我尝试了以下查询,但它返回了几行:

select m1.* 
from Message M1 
With (nolock)
JOIN Message M2 
With (Nolock) 
On m1.Text=m2.Text
where (m1.ID<>m2.ID 
  and m1.Code<>m2.Code 
  and m1.Code is not null)

如何获得预期结果?

此外,这是一个示例数据库。我需要在一个有50万条记录的表上运行查询。所以任何优化的查询都会有很大的帮助。

4 个答案:

答案 0 :(得分:2)

SELECT ID,TEXT,CODE
FROM message
WHERE ID IN 
(
  SELECT MIN(ID) FROM message
 WHERE CODE IS NOT NULL GROUP BY TEXT,CODE
)

SELECT 
   MIN(ID)
   ,TEXT
   ,CODE 
FROM message
WHERE CODE IS NOT NULL GROUP BY TEXT,CODE
ORDER BY MIN(ID)

答案 1 :(得分:2)

试试这个; SQL-FIDDLE-DEMO

;with cte as (
  select id,text,code, row_number() over (partition by text,code order by id) rn
  from message
  where code is not null
)
select id,text,code
from cte 
where rn = 1
order by id

答案 2 :(得分:1)

SELECT m.*
FROM message m
WHERE EXISTS (
      SELECT 1
        FROM message m2
       WHERE m2.text = m.text
         AND m2.code = m.code
         AND m2.code IS NOT NULL
    GROUP BY m2.text, m2.code
      HAVING MIN(m2.id) = m.id
      )

答案 3 :(得分:1)

SELECT DISTINCT m.* 
FROM Message m 
WHERE EXISTS (
  SELECT * 
  FROM Message m1 
  WHERE m1.Id<>m.id 
  AND m1.code<>m.code 
  AND m1.Text=m.Text) 
AND m.Code IS NOT NULL