注册 登录
编程论坛 SQL Server论坛

请问,能否在查询结果中,显示 … 谢谢

mansohu 发布于 2017-01-03 14:16, 1695 次点击
TB:
      FD1          FD2          FD3
      1             2           3
      1             2           3
      1A           2A           3A
      1A           2A           3A
      1A           2B           3A
      1B           2A           3A
      1B           2A           3B
      1B           2A           3C

我想得到以下查询结果:
      FD1        FD2        FD3
      1           2          3
      1A          …         3A
      1B          2A         …

即在FD1的编组中,其它字段内容相同时显示内容,内容不同时显示“……”,请问应该如何写 SQL:
select ……From TB Group by FD1

谢谢!

[此贴子已经被作者于2017-1-3 14:18编辑过]

1 回复
#2
mywisdom882017-01-03 16:00
--测试数据
if object_id('tempdb..#tb') is not null
drop table #tb

create table #tb(fd1 varchar(10),fd2 varchar(10),fd3 varchar(10))
insert into #tb
select '1', '2', '3' union all
select '1', '2', '3' union all
select '1A','2A','3A' union all
select '1A','2A','3A' union all
select '1A','2B','3A' union all
select '1B','2A','3A' union all
select '1B','2A','3B' union all
select '1B','2A','3C'

--查询语句
select distinct t0.fd1,
       case when then t0.fd2 else '...' end as fd2,
       case when then t0.fd3 else '...' end as fd3
from (select fd1,max(fd2) as fd2,max(fd3) as fd3 from #tb group by fd1)t0
left join (select fd1,count(fd1) as cnt1 from #tb group by fd1)t1 on t0.fd1=t1.fd1
left join (select fd1,count(fd2) as cnt2 from #tb group by fd1,fd2)t2 on t0.fd1=t2.fd1
left join (select fd1,count(fd3) as cnt3 from #tb group by fd1,fd3)t3 on t0.fd1=t3.fd1
只有本站会员才能查看附件,请 登录
1