在报表里,基本上都可以把重复的资料不显示,在SQL里怎么才能做到如下情况呢?
a 10
a 20
b 30
b 40
b 50
显示为:
a 10
20
b 30
40
50
SQL 如下:
create table #a (part varchar(10),price int)
go
insert into #a values('a',10)
insert into #a values('a',20)
insert into #a values('b',30)
insert into #a values('b',40)
insert into #a values('b',50)
go
select * from #a
go
select part ,MIN(price) price into #b from #a group by part
go
select * from #a
select * from #b
go
select
case when price in (select price from #b) then part else '' end ,price
from #a
go
参考: http://bbs.csdn.net/topics/310112824
主要内容:
方案一:
if object_id('[tab]') is not null drop table [tab]
create table [tab]([单位] varchar(6),[姓名] varchar(4),[学历] varchar(4))
insert [tab]
select '一车间','张三','本科' union all
select '一车间','李四','本科' union all
select '一车间','王五','本科' union all
select '二车间','王中','专科' union all
select '二车间','刘一','专科'
select 单位,姓名,学历 from
(
select 单位,姓名=(select top 1 姓名 from tab where ta.单位=单位 and ta.学历=学历),学历,s1=0,s2=单位,s3=0 from tab ta group by 单位,学历 union all
select ' ' ,姓名,'',s1=0,s2=单位,s3=1 from tab tb where 姓名<>(select top 1 姓名 from tab where tb.单位=单位 and tb.学历=学历)
)t
order by s1,s2,s3
/*
单位 姓名 学历
------ ---- ----
二车间 王中 专科
刘一
一车间 张三 本科
李四
王五
(所影响的行数为 5 行)
*/
方案二:
select 姓名 into #temp from (
select [单位],max(姓名)as 姓名 from [tab]
group by [单位]
)T
select case when 姓名 in (select * from #temp ) then [单位] else '' end,
姓名,
case when 姓名 in (select * from #temp ) then [学历] else '' end
from [tab]