【问题标题】:sql- how to get min,max,ave after inner join with groupby column?sql-如何在与 groupby 列进行内部连接后获取 min、max、ave?
【发布时间】:2022-01-12 07:21:18
【问题描述】:

我试图根据另一列在group by 之后的列中获取最小值、最大值、平均值。

从我在这里看到的:SQL Get MIN() and MAX() with INNER JOIN

我的语法是正确的,所以我不确定是什么问题。

但是我收到了这个错误:

一次只能执行一条语句。

代码是:

import sqlite3
import pandas as pd
battles=pd.read_csv('https://github.com/TheMLGuy/Game-of-Thrones-Dataset/raw/master/battles.csv')
character_deaths=pd.read_csv('https://github.com/TheMLGuy/Game-of-Thrones-Dataset/raw/master/character-deaths.csv')
character_predictions=pd.read_csv('https://github.com/TheMLGuy/Game-of-Thrones-Dataset/raw/master/character-predictions.csv')

character_deaths.loc[:,'Book_of_Death']=character_deaths.loc[:,'Book of Death']

cnx = sqlite3.connect('pythonsqlite.db')
battles.to_sql(name='battles', con=cnx, if_exists='replace')
character_deaths.to_sql(name='character_deaths', con=cnx, if_exists='replace')
character_predictions.to_sql(name='character_predictions', con=cnx, if_exists='replace')


#Edit the query
qry="""
--<<<write your query below this line>>>

SELECT MIN(character_predictions.age) as 
min_age,MAX(character_predictions.age) as 
max_age,AVG(character_predictions.age) as ave_age
FROM character_predictions
INNER JOIN character_deaths ON 
character_predictions.name = character_deaths.Name;
GROUP BY character_deaths.Book_of_Death
"""

pd.read_sql(qry, con=cnx)

而我想要得到的是每本书的“年龄”列的平均值、最小值、最大值(这就是我使用group by.. 的原因)

【问题讨论】:

    标签: sql pandas-groupby inner-join


    【解决方案1】:

    删除连接条件末尾的分号:

    INNER JOIN character_deaths ON  
    character_predictions.name = character_deaths.Name; <-- REMOVE THIS CHARACTER  
    GROUP BY character_deaths.Book_of_Death
    
    qry="""
    --<<<write your query below this line>>>
    
    SELECT MIN(character_predictions.age) as 
    min_age,MAX(character_predictions.age) as 
    max_age,AVG(character_predictions.age) as ave_age
    FROM character_predictions
    INNER JOIN character_deaths ON 
    character_predictions.name = character_deaths.Name
    GROUP BY character_deaths.Book_of_Death;
    """
    

    【讨论】:

    • ok tnx 问题可以关闭
    • @AsaelBarIlan 要“关闭”问题,您只需单击解决方案左侧的灰色勾号即可接受。 :)
    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 2016-06-30
    • 2017-06-10
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多