110,534
社区成员
发帖
与我相关
我的任务
分享
use tempdb
if OBJECT_ID('#tmp') is not null drop table #tmp
create table #tmp(
tId int identity(1,1) not null,
tBox int null default(0),
tApple int null default(0)
)
insert into #tmp (tBox,tApple)
select 1,8
union all select 2,3
union all select 3,0
union all select 4,8
union all select 5,2
union all select 6,0
union all select 7,1
union all select 8,11
union all select 9,5
union all select 10,4
--- 只读取前10行
;with cte as(
select tApple,COUNT(tId ) as cnt from #tmp group by tApple
)
select top 10 CAST(number as nvarchar(100))+' 个苹果' as N'ColA','有 '+CAST(isnull(cnt,0) as nvarchar(100))+' 个箱子' as N'ColB' from master.dbo.spt_values v
left join cte c on c.tApple =v.number
where v.type='p'
order by number
(10 行受影响)
ColA ColB
----------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------
0 个苹果 有 2 个箱子
1 个苹果 有 1 个箱子
2 个苹果 有 1 个箱子
3 个苹果 有 1 个箱子
4 个苹果 有 1 个箱子
5 个苹果 有 1 个箱子
6 个苹果 有 0 个箱子
7 个苹果 有 0 个箱子
8 个苹果 有 2 个箱子
9 个苹果 有 0 个箱子
(10 行受影响)