SQL研究(MS-SQL)之二:分组显示

本文介绍了一种将多个子项归并到同一父项下的SQL技巧,提供了三种不同的解决方案,并针对SQL Server 2005及以上版本给出了特定的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘抄自论坛资源:http://topic.youkuaiyun.com/u/20080926/18/851a0827-25ab-43bb-b914-f30f753fdeaf.html

要求如下:

==============================================================

表的两个字段F1,F2,其值如下
F1  F2
01  a
01  aa
02  b
02  bb
02  bbb
现在想用SQL语句让上面的记录显示为
01  a
    aa
02  b
    bb
    bbb
如何写?

==============================================================

实现:

  1. declare @t table(F1 varchar(8),F2 varchar(8))
  2. insert into @t values('01','a  ')
  3. insert into @t values('01','aa ')
  4. insert into @t values('02','b  ')
  5. insert into @t values('02','bb ')
  6. insert into @t values('02','bbb')

方法一:

  1. select 
  2.     (
  3.         case 
  4.         when 
  5.             exists(select 1 from @t where F1=t.F1 and F2<t.F2) then ''
  6.          else 
  7.             F1 
  8.         end
  9.     ) as NewF1, F2 
  10. from 
  11.     @t t 
  12. order by 
  13.     F1,F2

方法二:

    • select 
    •     isnull(b.f1,'') f1,a.f2 
    • from 
    •     @t a
    • left join
    •     (select f1,min(f2) f2 from @t group by f1) b
    • on a.f1=b.f1 and a.f2=b.f2

方法三:

  1. set nocount on;
  2. declare @T table([F1] nvarchar(2),[F2] nvarchar(3))
  3. Insert @T
  4. select N'01',N'a' union all
  5. select N'01',N'aa' union all
  6. select N'02',N'b' union all
  7. select N'02',N'bb' union all
  8. select N'02',N'bbb'
  9. Select [F1]=case when [F2]=(select top 1 [F2] from @T where [F1]=t.[F1]) then [F1] else '' end,
  10.         [F2]
  11. from @T t

如果是SQL2005以上版本,则可使用如下方法:

  1. set nocount on;
  2. declare @T table([F1] nvarchar(2),[F2] nvarchar(3))
  3. Insert @T
  4. select N'01',N'aa' union all
  5. select N'01',N'aa' union all
  6. select N'02',N'bbb' union all
  7. select N'02',N'bbb' union all
  8. select N'02',N'bbb'union all
  9. select N'02',N'bbb'union all
  10. select N'02',N'bbb'
  11. select    
  12.     case when rowid = 1 then f1 else '' end as f1,
  13.     f2
  14. from (
  15. select rowid = row_number() over(partition by f1 order by f1,f2) ,* 
  16. from @t) a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值