用 sql将两个表中的数据统计出来

来源:百度知道 编辑:UC知道 时间:2024/05/13 09:48:19
一个表示
visit_no pham_name amount visit_date
3414 葡萄糖 1 20080914
2224 螺旋霉素 3 20080704
另外一个表
visit_date visit_no ordered_by_doctor
20080914 3414 张三
如何统计出
张三在九月份中使用葡萄糖的数量

select t1.ordered_by_doctor as 姓名,sum(t2.amount) as 数量
from [tablename1] t1, [tablename2] t2
where t1.visit_no=t2.visit_no and
t2.ordered_by_doctor = '张三' and
year(t1.visit_date)=2008 and
month(t1.visit_date)=9
group by t1.ordered_by_doctor
注:
1、以上是MSSQL,
2、注意ordered_by_doctor字段可能有尾空格:rtrim(t2.ordered_by_doctor) = '张三'
3、visit_date是日期时间类型
4、如果是ORACLE数据库,日期判断写成:to_char(t1.visit_date,'yyyymm')='200809'
5、两个表中都有visit_date,如表达同一意思,根据范式,建议去掉一个。如表达不同意思,建议其中一个改名。

select a.amount,a.pham_name
from a,b
where a.visit_no=b.visit_no and b.ordered_by_doctor ='张三' and a.pham_name='葡萄糖'

select count(amount) from table1 join table2 on table1.visit_no=table2.visit_no group by convert(varchar(6),table1.visit_date,112) where ordered_by_doctor='张三' and month(visit_date)=9

select amount from 表1 where visit_no in(select cisit_no from 表2 where ordered_by_doctor li