表A
id names types
1 笔记本 文具
2 作业本 文具
3 课本 文具
4 笔记本 文具
5 作业本 文具
6 笔记本 文具
7 笔记本电脑 电脑
8 台式电脑 电脑
如上,我要把types类型下的names字段中重复的个数大于3个的去掉,得到如下结果:
id names types
2 作业本 文具
3 课本 文具
5 作业本 文具
7 笔记本电脑 电脑
8 台式电脑 电脑
sql语句改怎么写?sql数据库
id names types
1 笔记本 文具
2 作业本 文具
3 课本 文具
4 笔记本 文具
5 作业本 文具
6 笔记本 文具
7 笔记本电脑 电脑
8 台式电脑 电脑
如上,我要把types类型下的names字段中重复的个数大于3个的去掉,得到如下结果:
id names types
2 作业本 文具
3 课本 文具
5 作业本 文具
7 笔记本电脑 电脑
8 台式电脑 电脑
sql语句改怎么写?sql数据库
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-09-11 08:24:05
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[names] varchar(10),[types] varchar(4))
insert [A]
select 1,'笔记本','文具' union all
select 2,'作业本','文具' union all
select 3,'课本','文具' union all
select 4,'笔记本','文具' union all
select 5,'作业本','文具' union all
select 6,'笔记本','文具' union all
select 7,'笔记本电脑','电脑' union all
select 8,'台式电脑','电脑'
--------------开始查询--------------------------
SELECT *
FROM [a] a
WHERE EXISTS (SELECT 1 FROM (
select [types] ,NAMES
from [A]
GROUP BY [types],names
HAVING COUNT(1)<3)b WHERE a.NAMES=b.NAMES AND a.types=b.types)----------------结果----------------------------
/*
id names types
----------- ---------- -----
2 作业本 文具
3 课本 文具
5 作业本 文具
7 笔记本电脑 电脑
8 台式电脑 电脑
*/
select * from 表A t1
where not exists(select 1 from 表A where types=t1.types group by types,[names] having count([names])>3)
where not exists(select 1 from 表A where types=t1.types and [names]=t1.[names] group by types,[names] having count([names])>3)