2

我有一个如下表(使用 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)

我怎样才能得到预期的结果?

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

4

4 回答 4

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)
于 2013-02-19T10:06:32.480 回答
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
于 2013-02-19T10:12:03.433 回答
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
      )
于 2013-02-19T09:59:56.500 回答
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
于 2013-02-19T10:05:33.950 回答