读书人

SQL查询不重复的数据有关问题

发布时间: 2012-12-14 10:33:07 作者: rapoo

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 行)


[解决办法]
老大,这个太复杂了吧!用linq 怎么实现啊
[解决办法]
按日期和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)

[解决办法]
--设表名为tt
select * from tt a where
(select count(*) from tt where [type]=a.[type] and [date]=a.[date])=1

[解决办法]
学习了!,顶个!学习了!,顶个!
[解决办法]
学习了
[解决办法]
学习学习
[解决办法]
引用:
老大,这个太复杂了吧!用linq 怎么实现啊

linq不懂,帮顶
[解决办法]
select date,type
from 表名 group by date,type
having count(date)>1
以上查询重复的日期+type重复

以下查询日期+Type不重复
select date,type
from 表名 group by date,type
having count(date)=1
[解决办法]
引用:
老大,这个太复杂了吧!用linq 怎么实现啊


linq是什么?

读书人网 >SQL Server

热点推荐