请教sql查询语句,如何将缺失的类别补全?

mademelaugh 2006-10-23 11:43:26
有如下记录:
-----------------
月份 标记 数量
1 收 1
1 收 2
1 付 2
2 收 1
3 付 1
-----------------
要得到如下数据:
-----------------
月份 类别 数量
1 收 3
1 付 2
1 存 1
2 收 1
2 付 0
2 存 1
3 收 0
3 付 1
3 存 -1
...全文
337 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
playwarcraft 2006-10-23
  • 打赏
  • 举报
回复
--貌似可以將就用用?出去玩了一圈,發現腦袋要銹豆了
create table t ([month] int ,flag varchar(02),qty int)
insert into t
select 1,'收',1 union all
select 1,'收',2 union all
select 1,'付',2 union all
select 2,'收',1 union all
select 3,'付',1


go
declare @t table (flag varchar(02))
insert into @t select '收' union all select '付' union all select '存'
select * into #t from @t,(select distinct [month] from t) tt

select a.[month],a.flag,isnull(sum ( b.qty ),0) as qty
into #tt
from #t a left join t b
on a. flag=b.flag and a.[month]=b.[month]
group by a.[month],a.flag
order by a.[month],case when a.flag='收' then 1 when a.flag='付' then 2 else 3 end

update #tt set qty=isnull((select a.qty from #tt a where a.[month]=#tt.[month] and a.flag='收'),0)-isnull((select a.qty from #tt a where a.[month]=#tt.[month] and a.flag='付'),0)
where flag='存'


/*result:*/
select * from #tt
drop table t
drop table #t
drop table #tt

/*
month flag qty
----------- ---- -----------
1 收 3
1 付 2
1 存 1
2 收 1
2 付 0
2 存 1
3 收 0
3 付 1
3 存 -1
*/


Well 2006-10-23
  • 打赏
  • 举报
回复
有点不太明白楼主的意思,可否说清楚些
louifox 2006-10-23
  • 打赏
  • 举报
回复
set nocount on
drop table #t
drop table #

declare @t table (月份 int, 标记 char(5), 数量 int)
create table #t (月份 int, 标记 char(5), 数量 int)
declare @c int

insert @t values(1, '收', 1)
insert @t values(1, '收', 2)
insert @t values(1, '付', 2)
insert @t values(2, '收', 1)
insert @t values(3, '付', 1)

select @c=max(月份) from @t
while @c>0
begin
insert #t values(@c,'收',0)
insert #t values(@c,'付',0)
insert #t values(@c,'存',0)
set @c=@c-1
end

select 月份,标记,数量=sum(数量) into # from @t group by 月份,标记

update #t set #t.数量= #.数量 from # where
#t.月份=#.月份 and #t.标记=#.标记


update #t set 数量=isnull((select top 1 数量 from # where 月份=#t.月份 and 标记='收' order by 数量 ),0)
-isnull((select top 1 数量 from @t t where 月份=#t.月份 and 标记='付' order by 数量 ),0)
where 标记='存'
set nocount off
select * from #t order by 月份,case 标记 when '收' then 0 when '付' then 1 else 2 end

月份 标记 数量
----------- ----- -----------
1 收 3
1 付 2
1 存 1
2 收 1
2 付 0
2 存 1
3 收 0
3 付 1
3 存 -1

(所影响的行数为 9 行)

qpeg 2006-10-23
  • 打赏
  • 举报
回复
不明白 楼住的意思

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧