请教关于select组合查询的一个问题!

letmebee 2008-04-19 06:56:01
有两个表
A表字段sj(时间)、phone(号码)
B表字段phone、huafei(话费)
要想生成一个查询,就是输入指定月份如200802后,在A表筛选出符合时间要求的phone,然后再用phone去找出B表对应的huafei合计,两个表的phone字段是一致的。
我知道应该用select的组合查询,但不知道怎么写,下面的写法又出错:
select sum(huafei) as hf from B where phone (select phone from A where sj like '%"sj"%')
请指教!
...全文
128 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
letmebee 2008-04-20
  • 打赏
  • 举报
回复
可以了,非常感谢qianjin036a!
有问题还要多多请教呢,呵呵
-晴天 2008-04-20
  • 打赏
  • 举报
回复
<%
userid=request.form("userid")
datetime=request.form("datetime")
sqlstr = "select sum(fkje) from B where phone ='" & userid & "' and ajbh in (select ajbh from A where left(sj,patindex('%月%',sj))='" & datetime & "')"
myrs=conn.execute(sqlstr)
%>
-晴天 2008-04-20
  • 打赏
  • 举报
回复
呵呵,如果时间是 2008年4月16日,又是另一种写法了...
-晴天 2008-04-20
  • 打赏
  • 举报
回复

<%
userid=request.form("userid")
datetime=request.form("datetime")
sqlstr = "select sum(fkje) from B where phone ='" & userid & "' and ajbh in (select ajbh from A where left(sj,6) = '" & datetime & "')"
myrs=conn.execute(sqlstr)
%>
-晴天 2008-04-20
  • 打赏
  • 举报
回复
如果是ASP,那么查询字符串一般该这么写(如果有个请求页面表单上有userid和datetime域的话):
<%userid=request.form("userid")
datetime=request.form("datetime")
sqlstr = "select sum(fkje) from B where phone ='" & userid & "' and ajbh in (select ajbh from A where left(sj,6) = '" & datetime & "')"
myrs=conn.execute(sqlstr)%>
-晴天 2008-04-19
  • 打赏
  • 举报
回复
你的这个查询还是要以客户来统计,不然罚了谁的款不知道,你前面帖子里是以 phone来区分用户的.
另外,我不知道你的编程语言是什么.不同的编程语言,语法是不一样的.
从回帖知道你是用SQL Server ,你把这段放在查询分析器里执行下看看:
--统计用户 abc 在指定月份 200802 的罚款金额
select sum(fkje) from B where phone ='abc' and ajbh in (select ajbh from A where left(sj,6) = '200802')
--统计所有用户在指定月份 200802 的罚款金额
select phone, sum(fkje) from B where ajbh in (select ajbh from A where left(sj,6)='200802') group by phone

如果在程序里查询的话,那么 abc 和 200802 得用变量传递,这里有个变量名的问题.
如,用VB编程,这里应该是:
sqlstr = "select sum(fkje) from B where phone ='" & txtUserID.text & "' and ajbh in (select ajbh from A where left(sj,6) = '" & txtTime.text & "')"
letmebee 2008-04-19
  • 打赏
  • 举报
回复
qianjin036a:
严格的讲是这样的,我在做个运政的罚款软件,
A表字段sj(时间,写入时就按如2008年2月12日以VC数据类型写入)、Ajbh(案件编号,也是VC型)
B表字段Ajbh、Fkje(罚款金额)
我是想统计出客户选择月份的罚款金额合计,Ajbh是唯一不会重复的。

我试了select sum(fkje) as jk from B where ajbh in (select ajbh from A where sj like '%"sj"%')
结果还是出错,出错提示是][SQL Server]Incorrect syntax near the keyword 'like'.
-晴天 2008-04-19
  • 打赏
  • 举报
回复
如时间类型为datetime的,则
select phone,sum(huafei) from B where phone in (select phone from A where datename(yyyy,sj)+ datename(mm,js)='200802') group by phone

-晴天 2008-04-19
  • 打赏
  • 举报
回复
对了,你的A表中的sj是什么数据类型呢?
-晴天 2008-04-19
  • 打赏
  • 举报
回复
语句可以这样写:
select phone,sum(huafei) from B where phone in (select phone from A where sj='200802') group by phone

不过有个疑问,话费表中如果没有时间的话,那么就算找出200802的 phone ,它的话费依然是所有时间的.

28,409

社区成员

发帖
与我相关
我的任务
社区描述
ASP即Active Server Pages,是Microsoft公司开发的服务器端脚本环境。
社区管理员
  • ASP
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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