- 爱易网页
-
MSSQL教程
- 有点难度的SQL语句解决办法
日期:2014-05-18 浏览次数:20515 次
有点难度的SQL语句
例如表如下:
season body color
K GC001C 03
K GC001C 84
K GC002C 03
K GC002C 67
K GC002C 70
J GC003C 03
J GC003C 20
我想得到如下结果:
season body color
K GC001C 03
K GC001C 84
K GC001C null
K GC001C null
K GC002C 03
K GC002C 67
K GC002C 70
K GC002C null
J GC003C 03
J GC003C null
J GC003C null
J GC003C null
意思是按照season,body分组,4条记录为一组,不够的就补足,其中color用null补足.
如何实现呢?
------解决方案--------------------
create table #
(season varchar(5), body varchar(10), color varchar(5))
insert into # select 'K ', 'GC001C ', '03 '
union all select 'K ', 'GC001C ', '84 '
union all select 'K ', 'GC002C ', '03 '
union all select 'K ', 'GC002C ', '67 '
union all select 'K ', 'GC002C ', '70 '
union all select 'J ', 'GC003C ', '03 '
union all select 'J ', 'GC003C ', '20 '
select * from #
union all
select season,body,null from
(select season,body,count(1)[num] from # group by season,body having count(1) <4)a
,
(select 1[newnum] union select 2 union select 3 union select 4)b
where b.newnum> a.num
order by season,body,color desc
season body color
------ ---------- -----
J GC003C 20
J GC003C 03
J GC003C NULL
J GC003C NULL
K GC001C 84
K GC001C 03
K GC001C NULL
K GC001C NULL
K GC002C 70
K GC002C 67
K GC002C 03
K GC002C NULL