如何从SQL中的两个表获取记录

时间:2019-06-12 06:55:13

标签: sql

我有两个DB表STUDENT和FEES。预期结果是从表中获取特定月份(日期)的所有记录,并从FEES表中获取该月的金额之和,从STUDENT表中获取相同的id记录

学生

enter image description here

费用

**预期结果(针对特定日期,根据FEE表中的DATE字段)  例如:02-2019 **

for i in result:
    df = pd.read_csv("bigfolder/"+i, parse_dates=True, delim_whitespace=True, header=0)
    if len(df) > 2:
            df['time'] = pd.to_datetime(df['time'])
            df['just_dates'] = df['time'].dt.date

2 个答案:

答案 0 :(得分:0)

使用 INNER JOIN

查询

select t1.id, t1.name, t1.address, sum(t2.amount) as amount
from student as t1
join fess as t2
on t1.id = t2.id
group by t1.id, t1.name, t1.address;

答案 1 :(得分:0)

由于您需要特定日期的结果,因此您无需仅按学生将日期分组:

select s.id, s.name, s.address, sum(f.amount) amount
from student s left join fees f 
on f.id = s.id
where f.date = '02-2019'
group by s.id, s.name, s.address;

请参见demo。 结果:

| id  | name | address | amount |
| --- | ---- | ------- | ------ |
| S1  | abc  | ind     | 600    |
| S2  | pqr  | ind     | 100    |

在您的预期结果中,id='S2'date = '02-2019'的金额应该为100,对吧?