sql group by 小问题

taojm 2003-09-20 08:17:12
数据库名为:A
表1:
商品代号:numeric(8,0)
进货数:numeric(4,0)
表中数据为:
(1,10)
(1,20)
(2,10)
(2,10)
表2:
商品代号:numeric(8,0)
出货数:numeric(4,0)
表中数据为:
(1,5)
(1,5)
(2,5)
(2,5)
需要解决问题为:求货舱还剩多少货group by 商品代号请问怎么写?也就是怎么得到
(1,20)
(2,10)
的结果,在线等待谢谢^0^
...全文
24 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
Union
返回对两个集合进行 union 运算所生成的集合,可以保留重复的成员。

语法
Union(«Set1», «Set2»[, ALL])

替代语法 1
{«Set1», «Set2»}

替代语法 2
«Set1» + «Set 2»

注释
此函数返回 «Set1» 和 «Set2» 的 union 运算结果,并在默认情况下消除重复项。ALL 标志表示在并集中保留重复项。从尾部删除重复项。
taojm 2003-09-20
  • 打赏
  • 举报
回复
union all 什么意思啊?
wyb0026 2003-09-20
  • 打赏
  • 举报
回复
select a.商品代号,进货数 -出货数 from
(select 商品代号,sum(出货数) as 出货数 from a group by 商品代号) as a
inner join
(select 商品代号,sum(进货数) as 进货数 from b group by 商品代号) as b
on a.商品代号 =b.商品代号
yoki 2003-09-20
  • 打赏
  • 举报
回复
select 商品代号,sum() as 剩余货 from
(
select 商品代号,进货数 as 剩余货 from a
union all
select 商品代号, - 出货数 as 剩余货 from b ) c
group by c.商品代号
yangvxin1 2003-09-20
  • 打赏
  • 举报
回复
select a.商品代号,(进货总数-isnull(出货总数,0)) as 剩余货 from (select 商品代号,sum(进货数)进货总数 from 表1 group by 商品代号) a left join
(select 商品代号,sum(出货数)出货总数 from 表2 group by 商品代号) b on a.商品代号=b.商品代号
wzh1215 2003-09-20
  • 打赏
  • 举报
回复

create table #a(id numeric(8,0),jhs numeric(4,0))
insert #a values(1,10)
insert #a values(1,20)
insert #a values(2,10)
insert #a values(2,10)
create table #b(id numeric(8,0),chs numeric(4,0))
insert #b values(1,5)
insert #b values(1,5)
insert #b values(2,5)
insert #b values(2,5)
select id,sum(sl) from (select id,jhs sl from #a union all select id , -chs sl from #b ) c group by c.id
drop table #a
drop table #b
yujohny 2003-09-20
  • 打赏
  • 举报
回复
select 商品代号,sum(进货数) from
(select 商品代号,sum(进货数) AS 进货数 from 表1
union
select 商品代号,-sum(出货数) from 表2)
group by 商品代号
happy_0325 2003-09-20
  • 打赏
  • 举报
回复
create table a (id numeric(8,0),jhs numeric(4,0))
insert a values(1,10)
insert a values(1,20)
insert a values(2,10)
insert a values(2,10)
create table b(id numeric(8,0),chs numeric(4,0))
insert b values(1,5)
insert b values(1,5)
insert b values(2,5)
insert b values(2,5)
select id,sum(sl) from (select id,jhs sl from a union all select id , -chs sl from b ) c group by c.id
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
请注意 
1:Select 商品代号,sum(进货数) as 剩余数 from
(
Select 商品代号,进货数 from 表1
Union all
Select 商品代号,-出货数 from 表2 -- 出货数前面有一个负号
) tmp
group by 商品代号
taojm 2003-09-20
  • 打赏
  • 举报
回复
按照你说的答案是(1,40)(2,20)不对啊
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
或者:
Select a.商品代号,IsNull(sum(a.进货数),0) - IsNull(sum(b.出货数),0) as 剩余数
from 表1 a
join 表2 b on a.商品代号 = b.商品代号
group by a.商品代号
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
Select 商品代号,sum(进货数) as 剩余数 from
(
Select 商品代号,进货数 from 表1
Union all
Select 商品代号,-出货数 from 表2
) tmp
group by 商品代号

34,874

社区成员

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

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