SQL查询不重复的数据问题
我想查询一个表的某个字段,该字段的值不能重复,但是有另一个字段,另一个字段值不相同的时候可以重复。
例如
id id1 num date type
110011002010-01-01 00:00:00.0001
110021002010-01-01 00:00:00.0001
11003NULL2010-01-01 00:00:00.0001
21001NULL2010-01-02 00:00:00.0001
210021002010-01-02 00:00:00.0001
21003NULL2010-01-02 00:00:00.0001
110011002010-01-01 00:00:00.0002
110021002010-01-01 00:00:00.0002
110031002010-01-01 00:00:00.0002
现在我要查询 日期不重复,但type不同的时候可以重复。
[解决办法]
结果呢
[解决办法]
select *
from tb t
where not exists(select 1 from tb where type=t.type and datediff(dd,[date],t.[date])=0 and id1>t.id1)
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[id1] int,[num] int,[date] datetime,[type] int)
insert [tb]
select 1,1001,100,'2010-01-01 00:00:00.000',1 union all
select 1,1002,100,'2010-01-01 00:00:00.000',1 union all
select 1,1003,null,'2010-01-01 00:00:00.000',1 union all
select 2,1001,null,'2010-01-02 00:00:00.000',1 union all
select 2,1002,100,'2010-01-02 00:00:00.000',1 union all
select 2,1003,null,'2010-01-02 00:00:00.000',1 union all
select 1,1001,100,'2010-01-01 00:00:00.000',2 union all
select 1,1002,100,'2010-01-01 00:00:00.000',2 union all
select 1,1003,100,'2010-01-01 00:00:00.000',2
---查询---
select *
from tb t
where not exists(select 1 from tb where type=t.type and datediff(dd,[date],t.[date])=0 and id1>t.id1)
---结果---
id id1 num date type
----------- ----------- ----------- ------------------------------------------------------ -----------
1 1003 NULL 2010-01-01 00:00:00.000 1
2 1003 NULL 2010-01-02 00:00:00.000 1
1 1003 100 2010-01-01 00:00:00.000 2
(所影响的行数为 3 行)
--设表名为tt
select * from tt a where
(select count(*) from tt where [type]=a.[type] and [date]=a.[date])=1