跪求各位大虾:如何写多表查询的语句

wfexp 2004-11-02 10:17:11
我现在有一数据库,库内有如下命名的表 MZ_F+日期
因而有以下各表: MZ_F040101 MZ_F040102 MZ_F040101 ...MZ_F041101
表结构如下:
id ypdm ysdm sl
序号 代码1 代码2 数量
1 52 4902 2
2 52 4902 1
3 52 4901 3
4 52 4902 2
现要查 符合代码1 代码2的总数量
一个表查询就是
select sum(sl)
from MZ_F040101
where ypdm='52' and ysdm='4902'
但我不知道多个表怎么写,
比如要查一个月,就是统计 MZ_F040101。。。。到MZ_F040131 31张表的相关数量
...全文
193 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
lzymagi 2004-11-02
  • 打赏
  • 举报
回复
通过临时表也行啊
lsxaa 2004-11-02
  • 打赏
  • 举报
回复
用mgsray(我是新新新新,新来的吧) 的方法
mgsray 2004-11-02
  • 打赏
  • 举报
回复
set @begindate='040101'
set @enddate='040131'
这两个是我测试的时候用的,忘了注释了,你注释掉吧,否则存储过程参数传不进去
mgsray 2004-11-02
  • 打赏
  • 举报
回复
create proc test_query @begindate varchar(6), @enddate varchar(6)
as
--declare @begindate varchar(6), @enddate varchar(6)
declare @now varchar(6), @str varchar(8000)
set @begindate='040101'
set @enddate='040131'
set @now=@begindate
set @str=''
while @now<=@enddate
begin
set @str=@str+'union select sum(sl) as sumall from MZ_F'+@now+' where ypdm=''52'' and ysdm=''4902'''
set @now=right(convert(varchar(8),dateadd(d,1,convert(datetime, @now)),112),6)
end
set @str='select sum(sumall) from ('+stuff(@str,1,6,'')+') a'
exec(@str)
--未测试,语句应该没有问题,如果还要判断where语句,可以考虑再添加两个变量
zhuxiaojun2002 2004-11-02
  • 打赏
  • 举报
回复
select sum(sl)
from MZ_F040101
where ypdm='52' and ysdm='4902'

把表名称做变量传进去啊
fivefive 2004-11-02
  • 打赏
  • 举报
回复
这么快!
分那么多给点吧!
wfexp 2004-11-02
  • 打赏
  • 举报
回复
具体怎么做呢。谢谢各位大虾
jinjazz 2004-11-02
  • 打赏
  • 举报
回复
用动态SQL吧
lsxaa 2004-11-02
  • 打赏
  • 举报
回复
用union all
select sum(aa.s1) from (
select * from 表1
union all
select * form 表2
...
) aa
where ypdm='52' and ysdm='4902'
itzhiren 2004-11-02
  • 打赏
  • 举报
回复
上面的方法应该能解决了,楼主给个信儿吧,解决了没有?
gzapu 2004-11-02
  • 打赏
  • 举报
回复
mgsray(我是新新新新,新来的吧) 的方法已经可以了。

34,587

社区成员

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

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