34,587
社区成员
发帖
与我相关
我的任务
分享
select * from tbDepartment t
where
not exists(
select 1 from tbDepartment
where (PROVINCE_ID=t.PROVINCE_ID and CITY_ID=t.CITY_ID and COUNTY_ID=t.COUNTY_ID and id<t.id)
or (id=t.id and isnull(ltrim(PROVINCE_ID),'')='' and isnull(ltrim(CITY_ID),'')='' and isnull(ltrim(COUNTY_ID),'')='')
)
select PROVINCE_ID,CITY_ID,COUNTY_ID from "000".tbDepartment
where not(PROVINCE_ID='' and CITY_ID='' and COUNTY_ID='')
group by PROVINCE_ID,CITY_ID,COUNTY_ID
if object_id('[tbDepartment]') is not null drop table [tbDepartment]
go
create table [tbDepartment]([ID] int,[PROVINCE_ID] int,[CITY_ID] int,[COUNTY_ID] int)
insert [tbDepartment]
select 1,1,1000,1001001 union all
select 2,2,2001,200101 union all
select 3,1,1000,1001001 union all
select 4,null,null,null union all
select 5,null,null,null
go
-->查询
select * from tbDepartment t
where
not exists(
select 1 from tbDepartment
where (PROVINCE_ID=t.PROVINCE_ID and CITY_ID=t.CITY_ID and COUNTY_ID=t.COUNTY_ID and id<t.id)
or (id=t.id and PROVINCE_ID is null and CITY_ID is null and COUNTY_ID is null)
)
/**
ID PROVINCE_ID CITY_ID COUNTY_ID
----------- ----------- ----------- -----------
1 1 1000 1001001
2 2 2001 200101
(2 行受影响)
**/
select * from tbDepartment t
where
not exists(
select 1 from tbDepartment
where (PROVINCE_ID=t.PROVINCE_ID and CITY_ID=t.CITY_ID and COUNTY_ID=t.COUNTY_ID and id<t.id)
or (id=t.id and PROVINCE_ID is null and CITY_ID is null and COUNTY_ID is null)
)
select PROVINCE_ID,CITY_ID,COUNTY_ID from tbDepartment as a
where exists(select * from tbDepartment where a.id=id
group by PROVINCE_ID,CITY_ID,COUNTY_ID
having min(id)=a.id)
and PROVINCE_ID<>'' and CITY_ID<>'' and COUNTY_ID<>''
select distinct PROVINCE_ID,CITY_ID,COUNTY_ID from tbDepartment where PROVINCE_ID+CITY_ID+COUNTY_ID<>''
select min(ID)id, PROVINCE_ID,CITY_ID,COUNTY_ID from tb where isnull(PROVINCE_ID,'')+isnull(CITY_ID,'')+isnull(COUNTY_ID,'')<>'' group by PROVINCE_ID,CITY_ID,COUNTY_ID