首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

==求一Sql,多谢(解决接贴)==

2012-01-12 
求一Sql,谢谢(解决接贴)类似数据:nameUnitYear-endPopulationqqqYear-endPopulation690Year-endPopula

==求一Sql,谢谢(解决接贴)==
类似数据:
    name                                             Unit
Year-end   Populationqqq
Year-end   Population690
Year-end   PopulationN/A
Year-end   Population10,000   person
Year-end   PopulationN/A
Permanent   ResidentsN/A
Permanent   ResidentsN/A
Permanent   Residents10,000   person

希望得到:
    name                                             Unit
  Year-end   Populationqqq
  Permanent   Residents10,000   person

即:获取name的distinct,   Unit只要为N/A即可(即第一个是N/A则取第二个,直到取到部为N/A为止,仅取一个).

[解决办法]
select
t.*
from
表 t
where
t.Unit = (select top 1 Unit from 表 where name=t.name and Unit <> 'N/A ')
[解决办法]
--试试
select distinct(name),(select top 1 unit where name = a.name and unit <> 'N/A ')
from t a
[解决办法]
create table # (name varchar(50), Unit varchar(50))
insert into # select 'Year-end Population ', 'qqq ' union all
select 'Year-end Population ', '690 ' union all
select 'Year-end Population ', 'N/A ' union all
select 'Year-end Population ', '10,000 person ' union all
select 'Year-end Population ', 'N/A ' union all
select 'Permanent Residents ', 'N/A ' union all
select 'Permanent Residents ', 'N/A ' union all
select 'Permanent Residents ', '10,000person '

select * from # t where Unit = (select top 1 Unit from # where name=t.name and Unit!= 'N/A ')

--
Year-end Populationqqq
Permanent Residents10,000person
[解决办法]
好了:
create table #temp
( name varchar(50), Unit varchar(50)
)
insert into #temp
select 'Year-endPopulation ', 'qqq ' union all select 'Year-endPopulation ', '690 ' union all select 'Year-endPopulation ', 'N/A ' union all select 'Year-endPopulation ', '10,000person ' union all select 'Year-endPopulation ', 'N/A ' union all select 'PermanentResidents ', 'N/A ' union all select 'PermanentResidents ', 'N/A ' union all select 'PermanentResidents ', '10,000person '
select * from #temp


select name,max(unit) unit from #temp where unit not like '%N/A% '
group by name
order by name desc


name unit
------- -------

Year-endPopulation qqq
PermanentResidents 10,000person

热点排行