[ { "question_id": 0, "question": "What is the highest eligible free rate for K-12 students in the schools in Alameda County?", "db_id": "california_schools", "evidence": "Eligible free rate for K-12 = `Free Meal Count (K-12)` / `Enrollment (K-12)`", "code": "import pandas as pd\nimport numpy as np\nfiltered = frpm[frpm['County Name'] == 'Alameda']\nfiltered = filtered[filtered['Enrollment (K-12)'] > 0]\nfiltered['free_rate'] = filtered['Free Meal Count (K-12)'] / filtered['Enrollment (K-12)']\nresult = filtered['free_rate'].max()", "sql": "SELECT `Free Meal Count (K-12)` / `Enrollment (K-12)` FROM frpm WHERE `County Name` = 'Alameda' ORDER BY (CAST(`Free Meal Count (K-12)` AS REAL) / `Enrollment (K-12)`) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1, "question": "Please list the lowest three eligible free rates for students aged 5-17 in continuation schools.", "db_id": "california_schools", "evidence": "Eligible free rates for students aged 5-17 = `Free Meal Count (Ages 5-17)` / `Enrollment (Ages 5-17)`", "code": "import pandas as pd\nfiltered = frpm[(frpm['Educational Option Type'] == 'Continuation School') & (frpm['Free Meal Count (Ages 5-17)'].notna()) & (frpm['Enrollment (Ages 5-17)'] > 0)]\nfiltered['eligible_free_rate'] = filtered['Free Meal Count (Ages 5-17)'] / filtered['Enrollment (Ages 5-17)']\nresult = filtered.nsmallest(3, 'eligible_free_rate')[['eligible_free_rate']]", "sql": "SELECT `Free Meal Count (Ages 5-17)` / `Enrollment (Ages 5-17)` AS eligible_free_rate FROM frpm WHERE `Educational Option Type` = 'Continuation School' AND `Free Meal Count (Ages 5-17)` IS NOT NULL AND `Enrollment (Ages 5-17)` > 0 ORDER BY eligible_free_rate ASC LIMIT 3", "difficulty": "moderate" }, { "question_id": 2, "question": "Please list the zip code of all the charter schools in Fresno County Office of Education.", "db_id": "california_schools", "evidence": "ratio calculated by dividing Y by N;District Name in frpm corresponds to District in schools; Charter School (Y/N) with value 1.0 indicates charter school; Zip in schools refers to school's postal code", "code": "import pandas as pd\nresult = schools.loc[(schools['County'] == 'Fresno') & (schools['Charter'] == 1), 'Zip']", "sql": "SELECT schools.Zip FROM schools WHERE schools.County = 'Fresno' AND schools.Charter = 1", "difficulty": "simple" }, { "question_id": 3, "question": "What is the unabbreviated mailing street address of the school with the highest FRPM count for K-12 students?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, left_on='CDSCode', right_on='CDSCode')\nmerged_sorted = merged.sort_values('FRPM Count (K-12)', ascending=False)\nresult = merged_sorted.iloc[0]['MailStreet']", "sql": "SELECT T2.MailStreet FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode ORDER BY T1.`FRPM Count (K-12)` DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 4, "question": "Please list the phone numbers of the direct charter-funded schools that are opened after 2000/1/1.", "db_id": "california_schools", "evidence": "ratio calculated by dividing Y by N;", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[(merged['Charter Funding Type'] == 'Directly funded') & (merged['Charter School (Y/N)'] == 1) & (pd.to_datetime(merged['OpenDate']) > '2000-01-01')]\nresult = filtered[['Phone']]", "sql": "SELECT T2.Phone FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T1.`Charter Funding Type` = 'Directly funded' AND T1.`Charter School (Y/N)` = 1 AND T2.OpenDate > '2000-01-01'", "difficulty": "moderate" }, { "question_id": 5, "question": "How many schools with an average score in Math greater than 400 in the SAT test are exclusively virtual?", "db_id": "california_schools", "evidence": "Virtual equals 'F' in the database; Virtual = 'F' refers to exclusively virtual schools;", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[(merged['Virtual'] == 'F') & (merged['AvgScrMath'] > 400)]\nresult = filtered['School'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.School) FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.Virtual = 'F' AND T1.AvgScrMath > 400", "difficulty": "simple" }, { "question_id": 6, "question": "Among the schools with the SAT test takers of over 500, please list the schools that are magnet schools or offer a magnet program.", "db_id": "california_schools", "evidence": "Magnet equals 1 in the database; Magnet = 1 refers to schools with magnet programs;", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[(merged['Magnet'] == 1) & (merged['NumTstTakr'] > 500)]\nresult = filtered[['School']]", "sql": "SELECT T2.School FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.Magnet = 1 AND T1.NumTstTakr > 500", "difficulty": "simple" }, { "question_id": 7, "question": "What is the phone number of the school that has the highest number of test takers with an SAT score of over 1500?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nmerged_sorted = merged.sort_values('NumGE1500', ascending=False)\nresult = merged_sorted.iloc[0]['Phone']", "sql": "SELECT T2.Phone FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.NumGE1500 DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 8, "question": "What is the number of SAT test takers of the schools with the highest FRPM count for K-12 students?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\n\n# Get the school with highest FRPM count for K-12\nhighest_frpm_school = frpm.nlargest(1, 'FRPM Count (K-12)')['CDSCode'].iloc[0]\n\n# Get the number of SAT test takers for that school\nresult = satscores[satscores['cds'] == highest_frpm_school]['NumTstTakr']", "sql": "SELECT NumTstTakr FROM satscores WHERE cds = ( SELECT CDSCode FROM frpm ORDER BY `FRPM Count (K-12)` DESC LIMIT 1 )", "difficulty": "simple" }, { "question_id": 9, "question": "Among the schools with the average score in Math over 560 in the SAT test, how many schools are directly charter-funded?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores[satscores['AvgScrMath'] > 560], frpm[frpm['Charter Funding Type'] == 'Directly funded'], left_on='cds', right_on='CDSCode')\nresult = len(merged)", "sql": "SELECT COUNT(T2.`School Code`) FROM satscores AS T1 INNER JOIN frpm AS T2 ON T1.cds = T2.CDSCode WHERE T1.AvgScrMath > 560 AND T2.`Charter Funding Type` = 'Directly funded'", "difficulty": "simple" }, { "question_id": 10, "question": "For the school with the highest average score in Reading in the SAT test, what is its FRPM count for students aged 5-17?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, frpm, left_on='cds', right_on='CDSCode')\nmerged_sorted = merged.sort_values('AvgScrRead', ascending=False)\nresult = merged_sorted.iloc[0]['FRPM Count (Ages 5-17)']", "sql": "SELECT T2.`FRPM Count (Ages 5-17)` FROM satscores AS T1 INNER JOIN frpm AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.AvgScrRead DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 11, "question": "Please list the codes of the schools with a total enrollment of over 500.", "db_id": "california_schools", "evidence": "Total enrollment can be represented by `Enrollment (K-12)` + `Enrollment (Ages 5-17)`", "code": "import pandas as pd\nresult = frpm[frpm['Enrollment (K-12)'] + frpm['Enrollment (Ages 5-17)'] > 500]['CDSCode']", "sql": "SELECT CDSCode FROM frpm WHERE `Enrollment (K-12)` + `Enrollment (Ages 5-17)` > 500", "difficulty": "simple" }, { "question_id": 12, "question": "Among the schools with an SAT excellence rate of over 0.3, what is the highest eligible free rate for students aged 5-17?", "db_id": "california_schools", "evidence": "ratio calculated by dividing NumGE1500 by NumTstTakr;", "code": "import pandas as pd\nmerged = pd.merge(frpm, satscores, left_on='CDSCode', right_on='cds')\nfiltered = merged[merged['NumGE1500'] / merged['NumTstTakr'] > 0.3]\nfiltered['free_rate'] = filtered['Free Meal Count (Ages 5-17)'] / filtered['Enrollment (Ages 5-17)']\nresult = filtered['free_rate'].max()", "sql": "SELECT MAX(CAST(T1.`Free Meal Count (Ages 5-17)` AS REAL) / T1.`Enrollment (Ages 5-17)`) FROM frpm AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds WHERE CAST(T2.NumGE1500 AS REAL) / T2.NumTstTakr > 0.3", "difficulty": "moderate" }, { "question_id": 13, "question": "Please list the phone numbers of the schools with the top 3 SAT excellence rate.", "db_id": "california_schools", "evidence": "ratio calculated by dividing NumGE1500 by NumTstTakr;", "code": "import pandas as pd\nmerged = pd.merge(schools, satscores, left_on='CDSCode', right_on='cds')\nmerged['excellence_rate'] = merged['NumGE1500'] / merged['NumTstTakr']\nmerged_sorted = merged.sort_values('excellence_rate', ascending=False)\nresult = merged_sorted[['Phone']].head(3)", "sql": "SELECT T1.Phone FROM schools AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds ORDER BY CAST(T2.NumGE1500 AS REAL) / T2.NumTstTakr DESC LIMIT 3", "difficulty": "simple" }, { "question_id": 14, "question": "List the top five schools, by descending order, from the highest to the lowest, the most number of Enrollment (Ages 5-17). Please give their NCES school identification number.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(schools, frpm, left_on='CDSCode', right_on='CDSCode')\nmerged_sorted = merged.sort_values('Enrollment (Ages 5-17)', ascending=False)\nresult = merged_sorted[['NCESSchool']].head(5)", "sql": "SELECT T1.NCESSchool FROM schools AS T1 INNER JOIN frpm AS T2 ON T1.CDSCode = T2.CDSCode ORDER BY T2.`Enrollment (Ages 5-17)` DESC LIMIT 5", "difficulty": "simple" }, { "question_id": 15, "question": "Which active district has the highest average score in Reading?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files into DataFrames\nfrpm_df = pd.read_csv('frpm.csv')\nsatscores_df = pd.read_csv('satscores.csv')\nschools_df = pd.read_csv('schools.csv')\n\n# Filter for active districts\nactive_districts = schools_df[schools_df['StatusType'] == 'Active']['District'].unique()\n\n# Filter satscores for active districts\nactive_district_scores = satscores_df[satscores_df['dname'].isin(active_districts)]\n\n# Group by district and calculate the mean average reading score\ndistrict_avg_read_scores = active_district_scores.groupby('dname')['AvgScrRead'].mean().reset_index()\n\n# Find the district with the highest average reading score\nhighest_avg_read_district = district_avg_read_scores.loc[district_avg_read_scores['AvgScrRead'].idxmax()]\n\n# Prepare the result\nresult = highest_avg_read_district\n\n# Print the result\nprint(result)", "sql": "SELECT T1.District FROM schools AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds WHERE T1.StatusType = 'Active' ORDER BY T2.AvgScrRead DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 16, "question": "How many schools in merged Alameda have number of test takers less than 100?", "db_id": "california_schools", "evidence": "StatusType 'Merged' refers to schools that have been consolidated; NumTstTakr refers to number of test takers; County 'Lake' refers to Lake County schools", "code": "import pandas as pd\nmerged = pd.merge(schools, satscores, left_on='CDSCode', right_on='cds')\nfiltered = merged[(merged['StatusType'] == 'Merged') & (merged['County'] == 'Alameda') & (merged['NumTstTakr'] < 100)]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.CDSCode) FROM schools AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds WHERE T1.StatusType = 'Merged' AND T2.NumTstTakr < 100 AND T1.County = 'Alameda'", "difficulty": "simple" }, { "question_id": 17, "question": "Rank schools by their average score in Writing where the score is greater than 499, showing their charter numbers.", "db_id": "california_schools", "evidence": "Valid charter number means the number is not null", "code": "import pandas as pd\n\n# Read the CSV files\n# Use low_memory=False to ensure accurate type inference, though explicit dtypes are safer\nschools = pd.read_csv('schools.csv', low_memory=False)\nsatscores = pd.read_csv('satscores.csv', low_memory=False)\n\n# Merge schools and satscores on CDSCode = cds\nmerged_data = pd.merge(schools, satscores, left_on='CDSCode', right_on='cds', how='inner')\n\n# Filter data: AvgScrWrite > 499 AND CharterNum is not null\n# SQL: WHERE T2.AvgScrWrite > 499 AND CharterNum is not null\nfiltered_data = merged_data[\n (merged_data['AvgScrWrite'] > 499) & \n (merged_data['CharterNum'].notna())\n].copy()\n\n# Calculate Rank\n# SQL: RANK() OVER (ORDER BY AvgScrWrite DESC)\n# method='min' corresponds to SQL RANK() behavior (1, 1, 3 for ties)\nfiltered_data['WritingScoreRank'] = filtered_data['AvgScrWrite'].rank(method='min', ascending=False)\n\n# Sort by AvgScrWrite descending to align with the rank\nfiltered_data = filtered_data.sort_values(by='AvgScrWrite', ascending=False)\n\n# Select the required columns\nresult_df = filtered_data[['CharterNum', 'AvgScrWrite', 'WritingScoreRank']]\n\n# Convert to list of lists for standard output\nresult = result_df.values.tolist()\n\nprint(result)", "sql": "SELECT CharterNum, AvgScrWrite, RANK() OVER (ORDER BY AvgScrWrite DESC) AS WritingScoreRank FROM schools AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds WHERE T2.AvgScrWrite > 499 AND CharterNum is not null", "difficulty": "simple" }, { "question_id": 18, "question": "How many schools in Fresno (directly funded) have number of test takers not more than 250?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\n\n# Merge frpm and satscores on CDSCode\nmerged = pd.merge(frpm, satscores, left_on='CDSCode', right_on='cds')\n\n# Filter for Directly funded schools in Fresno with NumTstTakr <= 250\nfiltered = merged[(merged['Charter Funding Type'] == 'Directly funded') & \n (merged['County Name'] == 'Fresno') & \n (merged['NumTstTakr'] <= 250)]\n\n# Count the number of schools\nresult = len(filtered)", "sql": "SELECT COUNT(T1.CDSCode) FROM frpm AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds WHERE T1.`Charter Funding Type` = 'Directly funded' AND T1.`County Name` = 'Fresno' AND T2.NumTstTakr <= 250", "difficulty": "simple" }, { "question_id": 19, "question": "What is the phone number of the school that has the highest average score in Math?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Merge schools and satscores tables\nmerged = pd.merge(schools, satscores, left_on='CDSCode', right_on='cds')\n\n# Sort by AvgScrMath in descending order and get the first row\nresult = merged.sort_values('AvgScrMath', ascending=False).head(1)[['Phone']]", "sql": "SELECT T1.Phone FROM schools AS T1 INNER JOIN satscores AS T2 ON T1.CDSCode = T2.cds ORDER BY T2.AvgScrMath DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 20, "question": "How many schools in Amador which the Low Grade is 9 and the High Grade is 12?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, left_on='CDSCode', right_on='CDSCode')\nfiltered = merged[(merged['County'] == 'Amador') & (merged['Low Grade'] == '9') & (merged['High Grade'] == '12')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.`School Name`) FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'Amador' AND T1.`Low Grade` = '9' AND T1.`High Grade` = '12'", "difficulty": "simple" }, { "question_id": 21, "question": "In Los Angeles how many schools have more than 500 free meals but less than 700 free or reduced price meals for K-12?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nfiltered = frpm[(frpm['County Name'] == 'Los Angeles') & (frpm['Free Meal Count (K-12)'] > 500) & (frpm['FRPM Count (K-12)'] < 700)]\nresult = len(filtered)", "sql": "SELECT COUNT(CDSCode) FROM frpm WHERE `County Name` = 'Los Angeles' AND `Free Meal Count (K-12)` > 500 AND `FRPM Count (K-12)`< 700", "difficulty": "simple" }, { "question_id": 22, "question": "Which school in Contra Costa has the highest number of test takers?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nfiltered = satscores[(satscores['cname'] == 'Contra Costa') & (satscores['sname'].notna())]\nresult = filtered.nlargest(1, 'NumTstTakr')[['sname']]", "sql": "SELECT sname FROM satscores WHERE cname = 'Contra Costa' AND sname IS NOT NULL ORDER BY NumTstTakr DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 23, "question": "List the names of schools with more than 30 difference in enrollements between K-12 and ages 5-17? Please also give the full street adress of the schools.", "db_id": "california_schools", "evidence": "Diffrence in enrollement = `Enrollment (K-12)` - `Enrollment (Ages 5-17)`", "code": "import pandas as pd\nmerged = pd.merge(schools, frpm, left_on='CDSCode', right_on='CDSCode')\nfiltered = merged[abs(merged['Enrollment (K-12)'] - merged['Enrollment (Ages 5-17)']) > 30]\nresult = filtered[['School', 'Street']]", "sql": "SELECT T1.School, T1.Street FROM schools AS T1 INNER JOIN frpm AS T2 ON T1.CDSCode = T2.CDSCode WHERE ABS(T2.`Enrollment (K-12)` - T2.`Enrollment (Ages 5-17)`) > 30", "difficulty": "moderate" }, { "question_id": 24, "question": "Give the names of the schools with the percent eligible for free meals in K-12 is more than 0.1 and test takers whose test score is greater than or equal to 1500?", "db_id": "california_schools", "evidence": "Percent eligible for free meals = Free Meal Count (K-12) / Total (Enrollment (K-12)", "code": "import pandas as pd\nimport numpy as np\n\n# Merge satscores and frpm tables\nmerged = pd.merge(satscores, frpm, left_on='cds', right_on='CDSCode')\n\n# Filter for schools where percent eligible for free meals > 0.1 and NumGE1500 > 0\nfiltered = merged[(merged['Free Meal Count (K-12)'] / merged['Enrollment (K-12)'] > 0.1) & (merged['NumGE1500'] > 0)]\n\n# Select only the school names\nresult = filtered[['School Name']]", "sql": "SELECT T2.`School Name` FROM satscores AS T1 INNER JOIN frpm AS T2 ON T1.cds = T2.CDSCode WHERE T2.`Free Meal Count (K-12)` / T2.`Enrollment (K-12)` > 0.1 AND T1.NumGE1500 > 0", "difficulty": "moderate" }, { "question_id": 25, "question": "Name schools in Riverside which the average of average math score for SAT is grater than 400, what is the funding type of these schools?", "db_id": "california_schools", "evidence": "count of schools; sum of average math scores; 'rtype' refers to 'S' ratio calculated by dividing sum of average math scores by count of schools; 'rtype' refers to 'S'; 'Charter Funding Type' refers to funding type of schools", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[(merged['County'] == 'Riverside') & (merged['rtype'] == 'S')]\ngrouped = filtered.groupby(['sname', 'FundingType'], as_index=False)['AvgScrMath'].mean()\nresult = grouped[grouped['AvgScrMath'] > 400][['sname', 'FundingType']]", "sql": "SELECT T1.sname, T3.FundingType FROM satscores AS T1 INNER JOIN schools AS T3 ON T1.cds = T3.CDSCode WHERE T3.County LIKE 'Riverside%' AND T1.rtype = 'S' GROUP BY T1.sname, T3.FundingType HAVING AVG(T1.AvgScrMath) > 400;", "difficulty": "moderate" }, { "question_id": 26, "question": "State the names and full communication address of high schools in Monterey which has more than 800 free or reduced price meals for ages 15-17?", "db_id": "california_schools", "evidence": "Full communication address should include Street, City, State and zip code if any.", "code": "import pandas as pd\nfiltered_frpm = frpm[(frpm['County Name'] == 'Monterey') & (frpm['Free Meal Count (Ages 5-17)'] > 800) & (frpm['School Type'] == 'High Schools (Public)')]\nmerged = pd.merge(filtered_frpm, schools, left_on='CDSCode', right_on='CDSCode')\nresult = merged[['School Name', 'Street', 'City', 'State', 'Zip']]", "sql": "SELECT T1.`School Name`, T2.Street, T2.City, T2.State, T2.Zip FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'Monterey' AND T1.`Free Meal Count (Ages 5-17)` > 800 AND T1.`School Type` = 'High Schools (Public)'", "difficulty": "moderate" }, { "question_id": 27, "question": "What is the average score in writing for the schools that were opened after 1991 or closed before 2000? List the school names along with the score. Also, list the communication number of the schools if there is any.", "db_id": "california_schools", "evidence": "Communication number refers to phone number.", "code": "import pandas as pd\nimport numpy as np\n\n# Convert date columns to datetime\nschools['OpenDate'] = pd.to_datetime(schools['OpenDate'])\nschools['ClosedDate'] = pd.to_datetime(schools['ClosedDate'])\n\n# Filter schools opened after 1991 or closed before 2000\nfiltered_schools = schools[\n (schools['OpenDate'].dt.year > 1991) | \n (schools['ClosedDate'].dt.year < 2000)\n]\n\n# Left join with satscores\nresult = pd.merge(\n filtered_schools[['CDSCode', 'School', 'Phone']], \n satscores[['cds', 'AvgScrWrite']], \n left_on='CDSCode', \n right_on='cds', \n how='left'\n)\n\n# Select final columns\nresult = result[['School', 'AvgScrWrite', 'Phone']]", "sql": "SELECT T2.School, T1.AvgScrWrite, T2.Phone FROM schools AS T2 LEFT JOIN satscores AS T1 ON T2.CDSCode = T1.cds WHERE strftime('%Y', T2.OpenDate) > '1991' OR strftime('%Y', T2.ClosedDate) < '2000'", "difficulty": "moderate" }, { "question_id": 28, "question": "Consider the average difference between K-12 enrollment and 15-17 enrollment of schools that are locally funded, list the names and DOC type of schools which has a difference above this average.", "db_id": "california_schools", "evidence": "Difference between K-12 enrollment and 15-17 enrollment can be computed by `Enrollment (K-12)` - `Enrollment (Ages 5-17)`", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, left_on='CDSCode', right_on='CDSCode')\nlocally_funded = merged[merged['FundingType'] == 'Locally funded']\nlocally_funded['diff'] = locally_funded['Enrollment (K-12)'] - locally_funded['Enrollment (Ages 5-17)']\navg_diff = locally_funded['diff'].mean()\nabove_avg = locally_funded[locally_funded['diff'] > avg_diff]\nresult = above_avg[['School', 'DOC']]", "sql": "SELECT T2.School, T2.DOC FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.FundingType = 'Locally funded' AND (T1.`Enrollment (K-12)` - T1.`Enrollment (Ages 5-17)`) > (SELECT AVG(T3.`Enrollment (K-12)` - T3.`Enrollment (Ages 5-17)`) FROM frpm AS T3 INNER JOIN schools AS T4 ON T3.CDSCode = T4.CDSCode WHERE T4.FundingType = 'Locally funded')", "difficulty": "challenging" }, { "question_id": 29, "question": "When did the first-through-twelfth-grade school with the largest enrollment open?", "db_id": "california_schools", "evidence": "K-12 means First-through-twelfth-grade", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, left_on='CDSCode', right_on='CDSCode')\nmerged_sorted = merged.sort_values('Enrollment (K-12)', ascending=False)\nresult = merged_sorted.iloc[0]['OpenDate']", "sql": "SELECT T2.OpenDate FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode ORDER BY T1.`Enrollment (K-12)` DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 30, "question": "Which cities have the top 5 lowest enrollment number for students in grades 1 through 12?", "db_id": "california_schools", "evidence": "K-12 refers to students in grades 1 through 12.", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, left_on='CDSCode', right_on='CDSCode')\ngrouped = merged.groupby('City')['Enrollment (K-12)'].sum().reset_index()\nresult = grouped.sort_values('Enrollment (K-12)', ascending=True).head(5)['City']", "sql": "SELECT T2.City FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode GROUP BY T2.City ORDER BY SUM(T1.`Enrollment (K-12)`) ASC LIMIT 5", "difficulty": "simple" }, { "question_id": 31, "question": "What is the eligible free rate of the 10th and 11th schools with the highest enrolment for students in grades 1 through 12?", "db_id": "california_schools", "evidence": "K-12 refers to students in grades 1 through 12; Eligible free rate for K-12 = `Free Meal Count (K-12)` / `Enrollment (K-12)`", "code": "import pandas as pd\nfiltered = frpm[frpm['School Code'].notnull()].assign(eligible_free_rate=frpm['Free Meal Count (K-12)']/frpm['Enrollment (K-12)'])\nsorted_df = filtered.sort_values('Enrollment (K-12)', ascending=False)\nresult = sorted_df.iloc[9:11][['School Name', 'eligible_free_rate']]", "sql": "SELECT frpm.`School Name`, CAST(frpm.`Free Meal Count (K-12)` AS REAL) / frpm.`Enrollment (K-12)` AS eligible_free_rate FROM frpm WHERE frpm.`School Code` IS NOT NULL ORDER BY frpm.`Enrollment (K-12)` DESC LIMIT 9, 2", "difficulty": "moderate" }, { "question_id": 32, "question": "What is the eligible free or reduced price meal rate for the top 5 schools in grades 1-12 with the highest free or reduced price meal count of the schools with the ownership code 66?", "db_id": "california_schools", "evidence": "grades 1-12 means K-12; Eligible free or reduced price meal rate for K-12 = `FRPM Count (K-12)` / `Enrollment (K-12)`", "code": "import pandas as pd\n\nfrpm = pd.read_csv('frpm.csv')\nschools = pd.read_csv('schools.csv')\n\n# Join the tables\nmerged_data = pd.merge(frpm, schools, on='CDSCode', how='inner')\n\n# Filter by SOC = 66 (Converting to numeric to match SQL integer logic)\nmerged_data['SOC'] = pd.to_numeric(merged_data['SOC'], errors='coerce')\nfiltered_data = merged_data[merged_data['SOC'] == 66]\n\n# Sort by 'FRPM Count (K-12)' descending and take top 5\ntop_5_schools = filtered_data.sort_values(by='FRPM Count (K-12)', ascending=False).head(5)\n\n# Calculate the rate: FRPM Count / Enrollment\n# Using list comprehension to match SQL output format [[val], [val]]\nresult_series = top_5_schools['FRPM Count (K-12)'] / top_5_schools['Enrollment (K-12)']\nresult = [[x] for x in result_series.tolist()]\nprint(result)", "sql": "SELECT CAST(T1.`FRPM Count (K-12)` AS REAL) / T1.`Enrollment (K-12)` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.SOC = 66 ORDER BY T1.`FRPM Count (K-12)` DESC LIMIT 5", "difficulty": "moderate" }, { "question_id": 33, "question": "If there are any, what are the websites address of the schools with a free meal count of 1,900-2,000 to students aged 5-17? Include the name of the school.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files into DataFrames\nfrpm_df = pd.read_csv('frpm.csv')\nschools_df = pd.read_csv('schools.csv')\n\n# Filter frpm_df for schools with Free Meal Count (Ages 5-17) between 1900 and 2000\nfiltered_frpm = frpm_df[(frpm_df['Free Meal Count (Ages 5-17)'] >= 1900) & (frpm_df['Free Meal Count (Ages 5-17)'] <= 2000)]\n\n# Merge the filtered DataFrame with schools_df on CDSCode\nmerged_df = pd.merge(filtered_frpm, schools_df, left_on='CDSCode', right_on='CDSCode')\n\n# Select the required columns: School Name and Website\nresult = merged_df[['School Name', 'Website']]\n\n# Print the result\nprint(result)", "sql": "SELECT s.School, s.Website\nFROM schools s\nJOIN frpm f ON s.CDSCode = f.CDSCode\nWHERE f.`Free Meal Count (Ages 5-17)` BETWEEN 1900 AND 2000;", "difficulty": "moderate" }, { "question_id": 34, "question": "What is the free rate for students between the ages of 5 and 17 at the school run by Kacey Gibson?", "db_id": "california_schools", "evidence": "Eligible free rates for students aged 5-17 = `Free Meal Count (Ages 5-17)` / `Enrollment (Ages 5-17)`", "code": "import pandas as pd\n\n# Merge schools and frpm tables\nmerged = pd.merge(schools, frpm, left_on='CDSCode', right_on='CDSCode')\n\n# Filter for Kacey Gibson\nfiltered = merged[(merged['AdmFName1'] == 'Kacey') & (merged['AdmLName1'] == 'Gibson')]\n\n# Calculate free rate for ages 5-17\nresult = filtered['Free Meal Count (Ages 5-17)'] / filtered['Enrollment (Ages 5-17)']", "sql": "SELECT CAST(T2.`Free Meal Count (Ages 5-17)` AS REAL) / T2.`Enrollment (Ages 5-17)` FROM schools AS T1 INNER JOIN frpm AS T2 ON T1.CDSCode = T2.CDSCode WHERE T1.AdmFName1 = 'Kacey' AND T1.AdmLName1 = 'Gibson'", "difficulty": "moderate" }, { "question_id": 35, "question": "What is the administrator's email address of the chartered school with the fewest students enrolled in grades 1 through 12?", "db_id": "california_schools", "evidence": "Charted school means `Charter School (Y/N)` = 1 in the table frpm; Students enrolled in grades 1 through 12 refers to `Enrollment (K-12)`", "code": "import pandas as pd\n\n# Filter chartered schools\nchartered_schools = frpm[frpm['Charter School (Y/N)'] == 1]\n\n# Sort by enrollment and get the school with fewest students\nlowest_enrollment = chartered_schools.sort_values('Enrollment (K-12)').iloc[0]\n\n# Get the CDSCode of the school with lowest enrollment\ncds_code = lowest_enrollment['CDSCode']\n\n# Get the administrator's email from schools table\nresult = schools[schools['CDSCode'] == cds_code]['AdmEmail1'].iloc[0]", "sql": "SELECT T2.AdmEmail1 FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T1.`Charter School (Y/N)` = 1 ORDER BY T1.`Enrollment (K-12)` ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 36, "question": "Under whose administration is the school with the highest number of students scoring 1500 or more on the SAT? Indicate their full names.", "db_id": "california_schools", "evidence": "full name means first name, last name; There are at most 3 administrators for each school; SAT Scores are greater or equal to 1500 refers to NumGE1500", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nsorted_df = merged.sort_values('NumGE1500', ascending=False).head(1)\nresult = sorted_df[['AdmFName1', 'AdmLName1', 'AdmFName2', 'AdmLName2', 'AdmFName3', 'AdmLName3']]", "sql": "SELECT T2.AdmFName1, T2.AdmLName1, T2.AdmFName2, T2.AdmLName2, T2.AdmFName3, T2.AdmLName3 FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.NumGE1500 DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 37, "question": "What is the complete address of the school with the lowest excellence rate? Indicate the Street, City, Zip and State.", "db_id": "california_schools", "evidence": "ratio calculated by dividing NumGE1500 by NumTstTakr;", "code": "import pandas as pd\n\n# Merge satscores with schools\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\n\n# Calculate excellence rate\nmerged['excellence_rate'] = merged['NumGE1500'] / merged['NumTstTakr']\n\n# Sort by excellence rate ascending and get the first row\nlowest = merged.sort_values('excellence_rate').iloc[0]\n\n# Select the address fields\nresult = pd.DataFrame([{\n 'Street': lowest['Street'],\n 'City': lowest['City'],\n 'Zip': lowest['Zip'],\n 'State': lowest['State']\n}])", "sql": "SELECT T2.Street, T2.City, T2.Zip, T2.State FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY CAST(T1.NumGE1500 AS REAL) / T1.NumTstTakr ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 38, "question": "What are the webpages for the Los Angeles County school that has between 2,000 and 3,000 test takers?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[(merged['NumTstTakr'] >= 2000) & (merged['NumTstTakr'] <= 3000) & (merged['County'] == 'Los Angeles')]\nresult = filtered[['Website']]", "sql": "SELECT T2.Website FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T1.NumTstTakr BETWEEN 2000 AND 3000 AND T2.County = 'Los Angeles'", "difficulty": "simple" }, { "question_id": 39, "question": "What is the average number of test takers from Fresno schools that opened between 1/1/1980 and 12/31/1980?", "db_id": "california_schools", "evidence": "year equals 1980 in the database; ratio calculated by dividing 1 by 1; ratio calculated by dividing 12 by 31;", "code": "import pandas as pd\nimport numpy as np\n\n# Convert OpenDate to datetime\nschools['OpenDate'] = pd.to_datetime(schools['OpenDate'])\n\n# Filter schools in Fresno that opened between 1980-01-01 and 1980-12-31\nfresno_schools_1980 = schools[(schools['County'] == 'Fresno') & \n (schools['OpenDate'] >= '1980-01-01') & \n (schools['OpenDate'] <= '1980-12-31')]\n\n# Merge with satscores\nmerged = pd.merge(satscores, fresno_schools_1980, left_on='cds', right_on='CDSCode')\n\n# Calculate average number of test takers\nresult = merged['NumTstTakr'].mean()", "sql": "SELECT AVG(T1.NumTstTakr) FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.OpenDate BETWEEN '1980-01-01' AND '1980-12-31' AND T2.County = 'Fresno'", "difficulty": "simple" }, { "question_id": 40, "question": "What is the telephone number for the school with the lowest average score in reading in Fresno Unified?", "db_id": "california_schools", "evidence": "Fresno Unified is a name of district;", "code": "import pandas as pd\n\n# Merge satscores with schools\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\n\n# Filter for Fresno Unified district and non-null reading scores\nfiltered = merged[(merged['District'] == 'Fresno Unified') & (merged['AvgScrRead'].notna())]\n\n# Sort by AvgScrRead ascending and get the first row\nlowest_reading = filtered.sort_values('AvgScrRead').head(1)\n\n# Get the phone number\nresult = lowest_reading['Phone'].iloc[0]", "sql": "SELECT T2.Phone FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.District = 'Fresno Unified' AND T1.AvgScrRead IS NOT NULL ORDER BY T1.AvgScrRead ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 41, "question": "List the names of virtual schools that are among the top 5 in their respective counties based on average reading scores.", "db_id": "california_schools", "evidence": "Exclusively virtual refers to Virtual = 'F'; respective counties means PARTITION BY County", "code": "import pandas as pd\nimport numpy as np\n\n# Merge satscores with schools\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\n\n# Filter for virtual schools (Virtual = 'F')\nvirtual_schools = merged[merged['Virtual'] == 'F']\n\n# Remove rows with null AvgScrRead\nvirtual_schools = virtual_schools[virtual_schools['AvgScrRead'].notna()]\n\n# Rank schools within each county by AvgScrRead\nvirtual_schools['rnk'] = virtual_schools.groupby('County')['AvgScrRead'].rank(method='min', ascending=False)\n\n# Filter for top 5 in each county\ntop_schools = virtual_schools[virtual_schools['rnk'] <= 5]\n\n# Select only School names\nresult = top_schools[['School']]", "sql": "SELECT School FROM (SELECT T2.School,T1.AvgScrRead, RANK() OVER (PARTITION BY T2.County ORDER BY T1.AvgScrRead DESC) AS rnk FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.Virtual = 'F' ) ranked_schools WHERE rnk <= 5", "difficulty": "simple" }, { "question_id": 42, "question": "What is the type of education offered in the school who scored the highest average in Math?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nmerged_sorted = merged.sort_values('AvgScrMath', ascending=False)\nresult = merged_sorted[['EdOpsName']].head(1)", "sql": "SELECT T2.EdOpsName FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.AvgScrMath DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 43, "question": "What is the average math score of the school with the lowest average score for all subjects, and in which county is it located?", "db_id": "california_schools", "evidence": "Average score for all subjects can be computed by AvgScrMath + AvgScrRead + AvgScrWrite", "code": "import pandas as pd\n\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[merged['AvgScrMath'].notna() & merged['AvgScrRead'].notna() & merged['AvgScrWrite'].notna()]\nfiltered['total_score'] = filtered['AvgScrMath'] + filtered['AvgScrRead'] + filtered['AvgScrWrite']\nlowest_school = filtered.nsmallest(1, 'total_score')\nresult = lowest_school[['AvgScrMath', 'County']]", "sql": "SELECT T1.AvgScrMath, T2.County FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T1.AvgScrMath IS NOT NULL ORDER BY T1.AvgScrMath + T1.AvgScrRead + T1.AvgScrWrite ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 44, "question": "What is the average writing score of the school who has the highest number of test takers whose total SAT sscores are greater or equal to 1500? Indicate the city to where the school is situated.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nresult = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode').query(\"rtype == 'S'\").sort_values(by='NumGE1500', ascending=False).head(1)[['AvgScrWrite', 'City']]", "sql": "SELECT T1.AvgScrWrite, T2.City FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T1.rtype = 'S' ORDER BY T1.NumGE1500 DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 45, "question": "What is the average writing score of each of the schools managed by Ricci Ulrich? List the schools and the corresponding average writing scores.", "db_id": "california_schools", "evidence": "Usually, administrators manage the school stuff.", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[(merged['AdmFName1'] == 'Ricci') & (merged['AdmLName1'] == 'Ulrich')]\nresult = filtered[['School', 'AvgScrWrite']]", "sql": "SELECT T2.School, T1.AvgScrWrite FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.AdmFName1 = 'Ricci' AND T2.AdmLName1 = 'Ulrich'", "difficulty": "moderate" }, { "question_id": 46, "question": "Which state special schools have the highest number of enrollees from grades 1 through 12?", "db_id": "california_schools", "evidence": "State Special Schools refers to DOC = 31; Grades 1 through 12 means K-12", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[merged['DOC'] == 31]\nsorted_df = filtered.sort_values('Enrollment (K-12)', ascending=False)\nresult = sorted_df.head(1)['School']", "sql": "SELECT T2.School FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.DOC = 31 ORDER BY T1.`Enrollment (K-12)` DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 47, "question": "What is the monthly average number of schools that opened in Alameda County under the jurisdiction of the Elementary School District in 1980?", "db_id": "california_schools", "evidence": "Elementary School District refers to DOC = 52; Monthly average number of schools that opened in 1980 = count(schools that opened in 1980) / 12", "code": "import pandas as pd\n\n# Read the CSV file\ndf_schools = pd.read_csv('schools.csv')\n\n# Ensure OpenDate is parsed as datetime\ndf_schools['OpenDate'] = pd.to_datetime(df_schools['OpenDate'], errors='coerce')\n\n# Filter the data\n# SQL: WHERE DOC = 52 AND County = 'Alameda' AND strftime('%Y', OpenDate) = '1980'\n# Note: Cast DOC to string to handle potential integer inference by pandas, ensuring '52' matches 52\nfiltered_schools = df_schools[\n (df_schools['DOC'].astype(str) == '52') & \n (df_schools['County'] == 'Alameda') & \n (df_schools['OpenDate'].dt.year == 1980)\n]\n\n# Calculate the monthly average\n# Count / 12\nresult = len(filtered_schools) / 12\n\nprint(result)", "sql": "SELECT CAST(COUNT(School) AS REAL) / 12 FROM schools WHERE DOC = 52 AND County = 'Alameda' AND strftime('%Y', OpenDate) = '1980'", "difficulty": "moderate" }, { "question_id": 48, "question": "What is the ratio of merged Unified School District schools in Orange County to merged Elementary School District schools?", "db_id": "california_schools", "evidence": "Elementary School District refers to DOC = 52; Unified School District refers to DOC = 54.", "code": "import pandas as pd\n\nschools = pd.read_csv('schools.csv')\n\n# Filter for Merged schools in Orange County\nfiltered_data = schools[\n (schools['StatusType'] == 'Merged') & \n (schools['County'] == 'Orange')\n]\n\n# Convert DOC to numeric to ensure consistent comparison\ndoc_numeric = pd.to_numeric(filtered_data['DOC'], errors='coerce')\n\nunified_count = (doc_numeric == 54).sum()\nelementary_count = (doc_numeric == 52).sum()\n\n# Calculate ratio\nif elementary_count == 0:\n ratio = None\nelse:\n ratio = unified_count / elementary_count\n\n# Format result as list of lists [[ratio]]\nresult = [[ratio]]\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN DOC = '54' THEN 1 ELSE 0 END) AS REAL) / SUM(CASE WHEN DOC = '52' THEN 1 ELSE 0 END) FROM schools WHERE StatusType = 'Merged' AND County = 'Orange'", "difficulty": "moderate" }, { "question_id": 49, "question": "Which different county has the most number of closed schools? Please provide the name of each school as well as the closure date.", "db_id": "california_schools", "evidence": "Closure date and closed date are synonyms; 'Closed' was mentioned in schools.StatusType.", "code": "import pandas as pd\n\nclosed_schools = schools[schools['StatusType'] == 'Closed']\ncounty_counts = closed_schools.groupby('County').size().reset_index(name='count')\ntop_county = county_counts.sort_values('count', ascending=False).iloc[0]['County']\nresult = schools[(schools['County'] == top_county) & (schools['StatusType'] == 'Closed') & (schools['School'].notna())][['County', 'School', 'ClosedDate']].drop_duplicates()", "sql": "SELECT DISTINCT County, School, ClosedDate FROM schools WHERE County = ( SELECT County FROM schools WHERE StatusType = 'Closed' GROUP BY County ORDER BY COUNT(School) DESC LIMIT 1 ) AND StatusType = 'Closed' AND school IS NOT NULL", "difficulty": "moderate" }, { "question_id": 50, "question": "What is the postal street address for the school with the 7th highest Math average? Indicate the school's name.", "db_id": "california_schools", "evidence": "Postal street and mailing street are synonyms.", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nmerged_sorted = merged.sort_values('AvgScrMath', ascending=False)\nseventh_highest = merged_sorted.iloc[6]\nresult = pd.DataFrame({'MailStreet': [seventh_highest['MailStreet']], 'School': [seventh_highest['School']]})", "sql": "SELECT T2.MailStreet, T2.School FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.AvgScrMath DESC LIMIT 1 OFFSET 6", "difficulty": "simple" }, { "question_id": 51, "question": "In which mailing street address can you find the school that has the lowest average score in reading? Also give the school's name.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[merged['AvgScrRead'].notna()]\nsorted_df = filtered.sort_values('AvgScrRead', ascending=True)\nlowest = sorted_df.iloc[0]\nresult = pd.DataFrame({'MailStreet': [lowest['MailStreet']], 'School': [lowest['School']]})", "sql": "SELECT T2.MailStreet, T2.School FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T1.AvgScrRead IS NOT NULL ORDER BY T1.AvgScrRead ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 52, "question": "What is the total number of schools whose total SAT scores are greater or equal to 1500 whose mailing city is Lakeport?", "db_id": "california_schools", "evidence": "Total SAT scores can be computed by AvgScrRead + AvgScrMath + AvgScrWrite", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[merged['MailCity'] == 'Lakeport']\nfiltered['total_score'] = filtered['AvgScrRead'] + filtered['AvgScrMath'] + filtered['AvgScrWrite']\nresult = len(filtered[filtered['total_score'] >= 1500])", "sql": "SELECT COUNT(T1.cds) FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.MailCity = 'Lakeport' AND (T1.AvgScrRead + T1.AvgScrMath + T1.AvgScrWrite) >= 1500", "difficulty": "simple" }, { "question_id": 53, "question": "How many test takers are there at the school/s whose mailing city address is in Fresno?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nfiltered = merged[merged['MailCity'] == 'Fresno']\nresult = filtered['NumTstTakr']", "sql": "SELECT T1.NumTstTakr FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.MailCity = 'Fresno'", "difficulty": "simple" }, { "question_id": 54, "question": "Please specify all of the schools and their related mailing zip codes that are under Avetik Atoian's administration.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nresult = schools[(schools['AdmFName1'] == 'Avetik') & (schools['AdmLName1'] == 'Atoian')][['School', 'MailZip']]", "sql": "SELECT School, MailZip FROM schools WHERE AdmFName1 = 'Avetik' AND AdmLName1 = 'Atoian'", "difficulty": "simple" }, { "question_id": 55, "question": "Of the schools with a mailing state address in California, what is the ratio of the schools located in the county of Colusa against the school located in the county of Humboldt?", "db_id": "california_schools", "evidence": "count of schools in Colusa; count of schools in Humboldt;", "code": "import pandas as pd\n\nca_schools = schools[schools['MailState'] == 'CA']\ncolusa_count = len(ca_schools[ca_schools['County'] == 'Colusa'])\nhumboldt_count = len(ca_schools[ca_schools['County'] == 'Humboldt'])\nresult = colusa_count / humboldt_count", "sql": "SELECT CAST(SUM(CASE WHEN County = 'Colusa' THEN 1 ELSE 0 END) AS REAL) / SUM(CASE WHEN County = 'Humboldt' THEN 1 ELSE 0 END) FROM schools WHERE MailState = 'CA'", "difficulty": "moderate" }, { "question_id": 56, "question": "Of all the schools with a mailing state address in California, how many are active in San Joaquin city?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nresult = len(schools[(schools['City'] == 'San Joaquin') & (schools['MailState'] == 'CA') & (schools['StatusType'] == 'Active')])", "sql": "SELECT COUNT(CDSCode) FROM schools WHERE City = 'San Joaquin' AND MailState = 'CA' AND StatusType = 'Active'", "difficulty": "simple" }, { "question_id": 57, "question": "What is the phone number and extension number for the school that had the 333rd highest average writing score?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Merge satscores with schools\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\n\n# Remove rows with null AvgScrWrite\nmerged = merged[merged['AvgScrWrite'].notna()]\n\n# Sort by AvgScrWrite in descending order\nmerged = merged.sort_values('AvgScrWrite', ascending=False)\n\n# Get the 333rd highest (index 332)\nresult = merged.iloc[332][['Phone', 'Ext']].to_frame().T", "sql": "SELECT T2.Phone, T2.Ext FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.AvgScrWrite DESC LIMIT 332, 1", "difficulty": "simple" }, { "question_id": 58, "question": "What is the phone number and extension number for the school with the zip code 95203-3704? Indicate the school's name.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nresult = schools[schools['Zip'] == '95203-3704'][['Phone', 'Ext', 'School']]", "sql": "SELECT Phone, Ext, School FROM schools WHERE Zip = '95203-3704'", "difficulty": "simple" }, { "question_id": 59, "question": "What is the website for the schools under the administrations of Mike Larson and Dante Alvarez?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nresult = schools[((schools['AdmFName1'] == 'Mike') & (schools['AdmLName1'] == 'Larson')) | ((schools['AdmFName1'] == 'Dante') & (schools['AdmLName1'] == 'Alvarez'))][['Website']]", "sql": "SELECT Website FROM schools WHERE (AdmFName1 = 'Mike' AND AdmLName1 = 'Larson') OR (AdmFName1 = 'Dante' AND AdmLName1 = 'Alvarez')", "difficulty": "simple" }, { "question_id": 60, "question": "What are the websites for all the partially virtual chartered schools located in San Joaquin?", "db_id": "california_schools", "evidence": "Virtual = 'P' means partially virtual; Charter schools refers to Charter = 1 in the table schools", "code": "import pandas as pd\nresult = schools[(schools['County'] == 'San Joaquin') & (schools['Virtual'] == 'P') & (schools['Charter'] == 1)]['Website']", "sql": "SELECT Website FROM schools WHERE County = 'San Joaquin' AND Virtual = 'P' AND Charter = 1", "difficulty": "simple" }, { "question_id": 61, "question": "How many chartered schools located in the city of Hickman are owned by the Elementary School District?", "db_id": "california_schools", "evidence": "Elementary School District refers to DOC = 52; Chartered schools refer to Charter = 1 in the table schools", "code": "import pandas as pd\n\n# Read the tables\nschools_df = pd.read_csv('schools.csv')\nfrpm_df = pd.read_csv('frpm.csv')\nsatscores_df = pd.read_csv('satscores.csv')\n\n# Filter for chartered schools in the city of Hickman owned by the Elementary School District\nchartered_schools_hickman = schools_df[\n (schools_df['Charter'] == 1) & \n (schools_df['City'] == 'Hickman') & \n (schools_df['DOC'] == 52)\n]\n\n# Count the number of such schools\nresult = chartered_schools_hickman.shape[0]\n\nprint(result)", "sql": "SELECT COUNT(School) FROM schools WHERE DOC = 52 AND Charter = 1 AND City = 'Hickman'", "difficulty": "simple" }, { "question_id": 62, "question": "What is the total number of non-chartered schools in the county of Los Angeles with a percent (%) of eligible free meals for grades 1 through 12 that is less than 0.18%?", "db_id": "california_schools", "evidence": "Charter equals 0 in the database;Percent (%) Eligible Free (K-12) calculated by dividing Free Meal Count (K-12) by Enrollment (K-12)", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[(merged['County'] == 'Los Angeles') & (merged['Charter'] == 0) & (merged['Percent (%) Eligible Free (K-12)'] < 0.18)]\nresult = len(filtered)", "sql": "SELECT COUNT(T2.School) FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'Los Angeles' AND T2.Charter = 0 AND T1.`Percent (%) Eligible Free (K-12)` < 0.18;", "difficulty": "challenging" }, { "question_id": 63, "question": "In chartered schools with charter number 00D2, what are the names of all the administrators? Include the name of the school and the city to which it belongs", "db_id": "california_schools", "evidence": "Chartered schools refer to Charter = 1 ,and CharterNum = '00D2' in the table schools; Full name refers to first name, last nameCharterNum refers to the charter number as a string, and values like 00D2 are valid entries", "code": "import pandas as pd\nschools_filtered = schools[(schools['Charter'] == 1) & (schools['CharterNum'] == '00D2')]\nadm1 = schools_filtered[schools_filtered['AdmFName1'].notnull()][['School','City','AdmFName1','AdmLName1']].assign(AdminFullName=lambda x: x['AdmFName1'] + ' ' + x['AdmLName1'])[['School','City','AdminFullName']]\nadm2 = schools_filtered[schools_filtered['AdmFName2'].notnull()][['School','City','AdmFName2','AdmLName2']].assign(AdminFullName=lambda x: x['AdmFName2'] + ' ' + x['AdmLName2'])[['School','City','AdminFullName']]\nadm3 = schools_filtered[schools_filtered['AdmFName3'].notnull()][['School','City','AdmFName3','AdmLName3']].assign(AdminFullName=lambda x: x['AdmFName3'] + ' ' + x['AdmLName3'])[['School','City','AdminFullName']]\nresult = pd.concat([adm1,adm2,adm3], ignore_index=True)", "sql": "SELECT School, City, AdmFName1 || ' ' || AdmLName1 AS AdminFullName FROM schools WHERE Charter = 1 AND CharterNum = '00D2' UNION ALL SELECT School, City, AdmFName2 || ' ' || AdmLName2 FROM schools WHERE Charter = 1 AND CharterNum = '00D2' AND AdmFName2 IS NOT NULL UNION ALL SELECT School, City, AdmFName3 || ' ' || AdmLName3 FROM schools WHERE Charter = 1 AND CharterNum = '00D2' AND AdmFName3 IS NOT NULL;", "difficulty": "simple" }, { "question_id": 64, "question": "What is the total number of schools with a mailing city in Hickman belonging to the charter number 00D4?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nresult = len(schools[(schools['CharterNum'] == '00D4') & (schools['MailCity'] == 'Hickman')])", "sql": "SELECT COUNT(*) FROM schools WHERE CharterNum = '00D4' AND MailCity = 'Hickman'", "difficulty": "simple" }, { "question_id": 65, "question": "What is the ratio in percentage of Santa Clara County schools that are locally funded compared to all other types of charter school funding?", "db_id": "california_schools", "evidence": "count of locally funded schools in Santa Clara; count of all funding type schools in Santa Clara;FundingType refers to school funding type; Charter equals 1 refers to charter schools; County refers to school county name", "code": "import pandas as pd\nfiltered = schools[(schools['County'] == 'Santa Clara') & (schools['Charter'] == 1)]\nmask_local = filtered['FundingType'] == 'Locally funded'\nmask_other = filtered['FundingType'].notnull() & ~mask_local\nlocal_count = mask_local.sum()\nother_count = mask_other.sum()\nresult = (local_count * 100) / other_count if other_count != 0 else float('nan')", "sql": "SELECT \n (CAST(SUM(CASE WHEN FundingType = 'Locally funded' THEN 1 ELSE 0 END) AS REAL) * 100) \n / NULLIF(SUM(CASE WHEN FundingType IS NOT NULL AND FundingType != 'Locally funded' THEN 1 ELSE 0 END), 0)\nFROM schools \nWHERE County = 'Santa Clara' AND Charter = 1", "difficulty": "moderate" }, { "question_id": 66, "question": "Between 1/1/2000 to 12/31/2005, how many directly funded schools opened in the county of Stanislaus?", "db_id": "california_schools", "evidence": "FundingType equals 'Directly Funded' in the database;", "code": "import pandas as pd\nschools['OpenDate'] = pd.to_datetime(schools['OpenDate'])\nfiltered = schools[(schools['OpenDate'].dt.year >= 2000) & (schools['OpenDate'].dt.year <= 2005) & (schools['County'] == 'Stanislaus') & (schools['FundingType'] == 'Directly Funded')]\nresult = len(filtered)", "sql": "SELECT COUNT(School) FROM schools WHERE strftime('%Y', OpenDate) BETWEEN '2000' AND '2005' AND County = 'Stanislaus' AND FundingType = 'Directly Funded'", "difficulty": "simple" }, { "question_id": 67, "question": "What is the total amount of Community College District closure in 1989 in the city of San Francisco?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Filter schools closed in 1989 in San Francisco with DOCType='Community College District'\nfiltered_schools = schools[(schools['ClosedDate'].str[:4] == '1989') & \n (schools['City'] == 'San Francisco') & \n (schools['DOCType'] == 'Community College District')]\n\n# Count the total number of closures\nresult = len(filtered_schools)", "sql": "SELECT COUNT(CDSCode) FROM schools WHERE strftime('%Y', ClosedDate) = '1989' AND City = 'San Francisco' AND DOCType = 'Community College District'", "difficulty": "simple" }, { "question_id": 68, "question": "Which county reported the most number of school closure in the 1980s with school wonership code belonging to Youth Authority Facilities (CEA)?", "db_id": "california_schools", "evidence": "Youth Authority Facilities (CEA) refers to SOC = 11; 1980s = years between 1980 and 1989", "code": "import pandas as pd\nschools_df = pd.read_csv('schools.csv')\nfiltered_df = schools_df[(schools_df['ClosedDate'].notna()) & (schools_df['StatusType'] == 'Closed') & (schools_df['SOC'] == 11)]\nfiltered_df['ClosedYear'] = pd.to_datetime(filtered_df['ClosedDate']).dt.year\nfiltered_df = filtered_df[(filtered_df['ClosedYear'] >= 1980) & (filtered_df['ClosedYear'] <= 1989)]\ngrouped_df = filtered_df.groupby('County').size().reset_index(name='SchoolCount')\nresult = grouped_df.sort_values(by='SchoolCount', ascending=False).head(1)[['County']]\nresult = result.reset_index(drop=True)", "sql": "SELECT County FROM schools WHERE strftime('%Y', ClosedDate) BETWEEN '1980' AND '1989' AND StatusType = 'Closed' AND SOC = 11 GROUP BY County ORDER BY COUNT(School) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 69, "question": "Please provide the National Center for Educational Statistics school district identification number for all schools with a School Ownership Code that are part of the State Special Schools.", "db_id": "california_schools", "evidence": "SOC equals 31 in the database;", "code": "import pandas as pd\n\nschools = pd.read_csv('schools.csv')\n\n# Ensure SOC is numeric for comparison with 31\nschools['SOC'] = pd.to_numeric(schools['SOC'], errors='coerce')\n\n# Filter where SOC is 31\nfiltered_data = schools[schools['SOC'] == 31]\n\n# Extract NCESDist and format as list of lists\nresult_list = filtered_data['NCESDist'].tolist()\nresult = [[x] for x in result_list]\n\nprint(result)", "sql": "SELECT NCESDist FROM schools WHERE SOC = 31", "difficulty": "simple" }, { "question_id": 70, "question": "How many active and closed District Community Day Schools are there in the county of Alpine?", "db_id": "california_schools", "evidence": "District Community Day Schools in SOC is 69", "code": "import pandas as pd\nfiltered = schools[(schools['SOC'] == '69') & (schools['County'] == 'Alpine') & (schools['StatusType'].isin(['Active', 'Closed']))]\nresult = pd.DataFrame({\n 'Active': [(filtered['StatusType'] == 'Active').sum()],\n 'Closed': [(filtered['StatusType'] == 'Closed').sum()]\n})", "sql": "SELECT SUM(CASE WHEN StatusType = 'Active' THEN 1 ELSE 0 END) AS Active, SUM(CASE WHEN StatusType = 'Closed' THEN 1 ELSE 0 END) AS Closed FROM schools WHERE SOC = '69' AND County = 'Alpine' AND StatusType IN ('Active', 'Closed')", "difficulty": "simple" }, { "question_id": 71, "question": "What is the district code for the School that does not offer a magnet program in the city of Fresno?", "db_id": "california_schools", "evidence": "When magent is equal to 0 in the database, it means ths school doesn't offer a magnet program.", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nresult = merged[(merged['City'] == 'Fresno') & (merged['Magnet'] == 0)][['District Code']]", "sql": "SELECT T1.`District Code` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.City = 'Fresno' AND T2.Magnet = 0", "difficulty": "simple" }, { "question_id": 72, "question": "How many students from the ages of 5 to 17 are enrolled at the school in Fremont for the 2014-2015 academic year?", "db_id": "california_schools", "evidence": "EdOpsCode equals 'SSS' in the database;EdOpsCode 'SSS' refers to State Special School; Academic Year '2014-2015' refers to 2014-2015; City 'Fremont' refers to Fremont", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[(merged['EdOpsCode'] == 'SSS') & (merged['City'] == 'Fremont') & (merged['Academic Year'] == '2014-2015')]\nresult = filtered['Enrollment (Ages 5-17)'].sum()", "sql": "SELECT SUM(T1.`Enrollment (Ages 5-17)`) AS total_enrollment FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.EdOpsCode = 'SSS' AND T2.City = 'Fremont' AND T1.`Academic Year` = '2014-2015'", "difficulty": "moderate" }, { "question_id": 73, "question": "What is the free or reduced price meal count for ages 5 to 17 in the Youth Authority School with a mailing street address of PO Box 1040?", "db_id": "california_schools", "evidence": "Youth Authority School means SOCType equals Youth Authority Facilities in the database, and 'price meal count for ages 5 to 17' refers to 'FRPM Count (Ages 5-17)' in frpm", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, left_on='CDSCode', right_on='CDSCode')\nfiltered = merged[(merged['MailStreet'] == 'PO Box 1040') & (merged['SOCType'] == 'Youth Authority Facilities')]\nresult = filtered['FRPM Count (Ages 5-17)'].iloc[0]", "sql": "SELECT T1.`FRPM Count (Ages 5-17)` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.MailStreet = 'PO Box 1040' AND T2.SOCType = 'Youth Authority Facilities'", "difficulty": "simple" }, { "question_id": 74, "question": "What is the lowest grade for the District Special Education Consortia School with National Center for Educational Statistics school district identification number of 0613360?", "db_id": "california_schools", "evidence": "EdOpsCode equals 'SPECON' in the database;", "code": "import pandas as pd\n\n# Read the CSV files\n# Specifying dtype=str for ID columns is crucial to preserve leading zeros (e.g., NCESDist '0613360')\ndf_frpm = pd.read_csv('frpm.csv', dtype={'CDSCode': str})\ndf_schools = pd.read_csv('schools.csv', dtype={'CDSCode': str, 'NCESDist': str})\n\n# Merge the tables on CDSCode\n# SQL: INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode\nmerged_df = pd.merge(df_frpm, df_schools, on='CDSCode')\n\n# Filter for specific NCESDist and EdOpsCode\n# SQL: WHERE T2.NCESDist = '0613360' AND T2.EdOpsCode = 'SPECON'\nfiltered_df = merged_df[\n (merged_df['NCESDist'] == '0613360') & \n (merged_df['EdOpsCode'] == 'SPECON')\n]\n\n# Get the minimum Low Grade\n# SQL: SELECT MIN(T1.`Low Grade`)\n# Note: 'K' is a string, min() works lexicographically or logic depends on data, \n# but simply calling min() matches SQL behavior for text columns.\nresult = filtered_df['Low Grade'].min()\n\nprint(result)", "sql": "SELECT MIN(T1.`Low Grade`) FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.NCESDist = '0613360' AND T2.EdOpsCode = 'SPECON'", "difficulty": "moderate" }, { "question_id": 75, "question": "What is the educational level name for the schools with Breakfast Provision 2 in county code 37? Indicate the name of the school.", "db_id": "california_schools", "evidence": " Breakfast Provision 2 means NSLP Provision Status equals 'Breakfast Provision 2' in the database ", "code": "import pandas as pd\n\n# Read the CSV files\n# reading 'County Code' and 'CDSCode' implies they are identifiers. \n# We explicitly cast them to ensure matching works regardless of CSV format (int/float/str)\ndf_frpm = pd.read_csv('frpm.csv', dtype=str, low_memory=False)\ndf_schools = pd.read_csv('schools.csv', dtype=str, low_memory=False)\n\n# Data Cleaning Function to handle \"37\" vs \"37.0\" vs 37\ndef clean_id_column(series):\n return series.astype(str).str.split('.').str[0]\n\n# Clean the join keys and filter keys\ndf_frpm['CDSCode'] = clean_id_column(df_frpm['CDSCode'])\ndf_schools['CDSCode'] = clean_id_column(df_schools['CDSCode'])\ndf_frpm['County Code'] = clean_id_column(df_frpm['County Code'])\n\n# Filter frpm table\n# SQL: WHERE `NSLP Provision Status` = 'Breakfast Provision 2' AND `County Code` = '37'\nfiltered_frpm = df_frpm[\n (df_frpm['NSLP Provision Status'] == 'Breakfast Provision 2') & \n (df_frpm['County Code'] == '37')\n]\n\n# Merge with schools table\n# SQL: INNER JOIN schools ... ON CDSCode\nmerged_df = pd.merge(filtered_frpm, df_schools, on='CDSCode')\n\n# Select columns\n# SQL: SELECT EILName, School\nresult = merged_df[['EILName', 'School']].values.tolist()\n\nprint(result)", "sql": "SELECT T2.EILName, T2.School FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T1.`NSLP Provision Status` = 'Breakfast Provision 2' AND T1.`County Code` = '37'", "difficulty": "simple" }, { "question_id": 76, "question": "What is the city location of the high school level school with Lunch Provision 2 whose lowest grade is 9 and the highest grade is 12 in the county of Merced?", "db_id": "california_schools", "evidence": "EILCode equals 'HS' in the database; 'Lunch Provision 2' refers to 'NSLP Provision Status' in frpm ", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[(merged['NSLP Provision Status'] == 'Lunch Provision 2') & (merged['County'] == 'Merced') & (merged['Low Grade'] == '9') & (merged['High Grade'] == '12') & (merged['EILCode'] == 'HS')]\nresult = filtered[['City']]", "sql": "SELECT T2.City FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T1.`NSLP Provision Status` = 'Lunch Provision 2' AND T2.County = 'Merced' AND T1.`Low Grade` = '9' AND T1.`High Grade` = '12' AND T2.EILCode = 'HS'", "difficulty": "moderate" }, { "question_id": 77, "question": "Which schools served a grade span of Kindergarten to 9th grade in the county of Los Angeles and what is its Percent (%) Eligible FRPM (Ages 5-17)?", "db_id": "california_schools", "evidence": "Percent (%) Eligible FRPM (Ages 5-17) can be acquired by `FRPM Count (Ages 5-17)` / `Enrollment (Ages 5-17)` * 100 , and 'K-9' can be acquired by 'GSserved'GSserved refers to grade span served by the school; 'K-9' indicates Kindergarten through 9th grade", "code": "import pandas as pd\nresult = pd.merge(frpm, schools, on='CDSCode').query(\"County == 'Los Angeles' and GSserved == 'K-9'\")[['School', 'Percent (%) Eligible FRPM (Ages 5-17)']]", "sql": "SELECT T2.School, T1.`Percent (%) Eligible FRPM (Ages 5-17)` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'Los Angeles' AND T2.GSserved = 'K-9'", "difficulty": "moderate" }, { "question_id": 78, "question": "What is the most common type of grade span served in the city of Adelanto?", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nfiltered = schools[schools['City'] == 'Adelanto']\ngrouped = filtered.groupby('GSserved').size().reset_index(name='count')\nresult = grouped.sort_values('count', ascending=False).head(1)['GSserved'].iloc[0]", "sql": "SELECT GSserved FROM schools WHERE City = 'Adelanto' GROUP BY GSserved ORDER BY COUNT(GSserved) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 79, "question": "Between San Diego and Santa Barbara, which county offers the most number of schools that does not offer physical building? Indicate the amount.", "db_id": "california_schools", "evidence": "'Does not offer physical building' means Virtual = F in the database.", "code": "import pandas as pd\nfiltered = schools[(schools['County'].isin(['San Diego', 'Santa Barbara'])) & (schools['Virtual'] == 'F')]\ngrouped = filtered.groupby('County').size().reset_index(name='count')\nresult = grouped.sort_values('count', ascending=False).head(1)", "sql": "SELECT County, COUNT(Virtual) FROM schools WHERE (County = 'San Diego' OR County = 'Santa Barbara') AND Virtual = 'F' GROUP BY County ORDER BY COUNT(Virtual) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 80, "question": "What is the school type of the school with the highest latitude? Indicate the name of the school as well as the latitude coordinates.", "db_id": "california_schools", "evidence": "School Name refers to the name of the educational institution; Latitude refers to geographic coordinate in schools table; School Type indicates category like K-12 or High School", "code": "import pandas as pd\nmerged = pd.merge(schools, frpm, on='CDSCode')\nresult = merged.sort_values('Latitude', ascending=False).head(1)[['School Type', 'School', 'Latitude']]", "sql": "SELECT T1.`School Type`, T2.School, T2.Latitude FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode ORDER BY T2.Latitude DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 81, "question": "In which city can you find the school in the state of California with the lowest latitude coordinates and what is its lowest grade? Indicate the school name.", "db_id": "california_schools", "evidence": "state equals 'CA' in the database;State refers to the State column in the schools table; Latitude refers to the Latitude column in the schools table; Low Grade refers to the Low Grade column in the frpm table", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[(merged['State'] == 'CA') & merged['Latitude'].notnull()]\nsorted_df = filtered.sort_values('Latitude')\nresult = sorted_df.head(1)[['City', 'Low Grade', 'School']]", "sql": "SELECT T2.City, T1.`Low Grade`, T2.School FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.State = 'CA' AND T2.Latitude IS NOT NULL ORDER BY T2.Latitude ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 82, "question": "What is the grade span offered in the school with the highest longitude?", "db_id": "california_schools", "evidence": "the highest longitude refers to the school with the maximum absolute longitude value.", "code": "import pandas as pd\nresult = schools.loc[schools['Longitude'].abs().idxmax(), 'GSoffered']", "sql": "SELECT GSoffered FROM schools ORDER BY ABS(longitude) DESC LIMIT 1;", "difficulty": "simple" }, { "question_id": 83, "question": "Of the schools that offers a magnet program serving a grade span of Kindergarten to 8th grade, how many offers Multiple Provision Types? List the number of cities that offers a Kindergarten to 8th grade span and indicate how many schools are there serving such grade span for each city.", "db_id": "california_schools", "evidence": "Kindergarten to 8th grade refers to K-8; 'Offers a magnet program' means Magnet = 1; Multiple Provision Types refers to `NSLP Provision Status` = 'Multiple Provision Types'", "code": "import pandas as pd\nmerged = pd.merge(schools, frpm, on='CDSCode', how='left')\nfiltered = merged[(merged['GSoffered'] == 'K-8') & (merged['Magnet'] == 1)]\ngrouped = filtered.groupby('City').agg(MultipleProvisionCount=('NSLP Provision Status', lambda x: (x == 'Multiple Provision Types').sum()), TotalK8Schools=('CDSCode', 'count')).reset_index()\nresult = grouped", "sql": "SELECT \n T2.City,\n COUNT(DISTINCT CASE WHEN T1.`NSLP Provision Status` = 'Multiple Provision Types' THEN T2.CDSCode END) AS MultipleProvisionCount,\n COUNT(DISTINCT T2.CDSCode) AS TotalK8Schools\nFROM schools AS T2\nLEFT JOIN frpm AS T1 ON T2.CDSCode = T1.CDSCode\nWHERE \n T2.GSoffered = 'K-8'\n AND T2.Magnet = 1\nGROUP BY T2.City", "difficulty": "challenging" }, { "question_id": 84, "question": "What are the two most common first names among the school administrators? Indicate the district to which they administer.", "db_id": "california_schools", "evidence": "AdmFName1 refers to first name of administrator; District refers to district name", "code": "import pandas as pd\nmelted = schools.melt(id_vars=['District'], value_vars=['AdmFName1', 'AdmFName2', 'AdmFName3'], value_name='name').dropna(subset=['name'])\ntop_names = melted.groupby('name').size().reset_index(name='count').sort_values('count', ascending=False).head(2)['name']\nfiltered = melted[melted['name'].isin(top_names)]\nresult = filtered[['name', 'District']].drop_duplicates()", "sql": "WITH all_admins AS (\n SELECT AdmFName1 AS name, District FROM schools\n UNION ALL\n SELECT AdmFName2, District FROM schools\n UNION ALL\n SELECT AdmFName3, District FROM schools\n),\ntop_names AS (\n SELECT name \n FROM all_admins \n WHERE name IS NOT NULL\n GROUP BY name \n ORDER BY COUNT(*) DESC \n LIMIT 2\n)\nSELECT a.name, a.District \nFROM all_admins a \nJOIN top_names t ON a.name = t.name \nGROUP BY a.name, a.District", "difficulty": "simple" }, { "question_id": 85, "question": "What is the Percent (%) Eligible Free (K-12) in the school administered by an administrator whose first name is Alusine. List the district code of the school.", "db_id": "california_schools", "evidence": "Percent (%) Eligible Free (K-12) = `Free Meal Count (K-12)` / `Enrollment (K-12)` * 100%", "code": "import pandas as pd\nmerged = pd.merge(frpm, schools, on='CDSCode')\nfiltered = merged[merged['AdmFName1'] == 'Alusine']\nresult = filtered[['District Code']].assign(PercentEligibleFree=filtered['Free Meal Count (K-12)'] / filtered['Enrollment (K-12)'] * 100)", "sql": "SELECT T1.`Free Meal Count (K-12)` * 100 / T1.`Enrollment (K-12)`, T1.`District Code` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.AdmFName1 = 'Alusine'", "difficulty": "moderate" }, { "question_id": 86, "question": "What is the administrator's last name that oversees the school with Charter number 40? Indicate the district, the county where the school is situated, and the name of the school.", "db_id": "california_schools", "evidence": "find Charter number 40 refers to 'CharterNum' = '0040' ", "code": "import pandas as pd\nresult = schools[schools['CharterNum'] == '0040'][['AdmLName1', 'District', 'County', 'School']]", "sql": "SELECT AdmLName1, District, County, School FROM schools WHERE CharterNum = '0040'", "difficulty": "simple" }, { "question_id": 87, "question": "What are the valid e-mail addresses of the administrator of the school located in the San Bernardino county, City of San Bernardino City Unified that opened between 1/1/2009 to 12/31/2010 whose school types are public Intermediate/Middle Schools and Unified Schools?", "db_id": "california_schools", "evidence": "Intermediate/Middle Schools refers to SOC = 62 and Unified School need refers to DOC = 54; years between 2009 and 2010 can refer to 'between 1/1/2009 to 12/31/2010'", "code": "import pandas as pd\nschools['OpenDate'] = pd.to_datetime(schools['OpenDate'])\n\n# 完整的筛选条件\nfiltered_schools = schools[\n (schools['County'] == 'San Bernardino') & \n (schools['City'] == 'San Bernardino') & \n (schools['DOC'] == 54) & # 数值比较\n (schools['OpenDate'] >= '2009-01-01') & \n (schools['OpenDate'] <= '2010-12-31') & \n (schools['SOC'] == 62) # 数值比较\n]\n\n# 合并并获取邮箱信息\nmerged = pd.merge(frpm, filtered_schools, left_on='CDSCode', right_on='CDSCode')\nresult = merged[['AdmEmail1', 'AdmEmail2']].drop_duplicates()\nprint(result)", "sql": "SELECT T2.AdmEmail1, T2.AdmEmail2 FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'San Bernardino' AND T2.City = 'San Bernardino' AND T2.DOC = 54 AND strftime('%Y', T2.OpenDate) BETWEEN '2009' AND '2010' AND T2.SOC = 62", "difficulty": "challenging" }, { "question_id": 88, "question": "What is the administrator's email address for the school with the highest number of test takers who received SAT scores of at least 1500?Provide the name of the school.", "db_id": "california_schools", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(satscores, schools, left_on='cds', right_on='CDSCode')\nmerged_sorted = merged.sort_values('NumGE1500', ascending=False)\nresult = merged_sorted[['AdmEmail1', 'School']].head(1)", "sql": "SELECT T2.AdmEmail1, T2.School FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.NumGE1500 DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 89, "question": "How many accounts who choose issuance after transaction are staying in East Bohemia region?", "db_id": "financial", "evidence": "A3 contains the data of region; 'POPLATEK PO OBRATU' represents for 'issuance after transaction'.", "code": "import pandas as pd\nmerged = pd.merge(district, account, on='district_id')\nmerged = pd.merge(merged, disp, on='account_id')\nfiltered = merged[(merged['A3'] == 'east Bohemia') & (merged['frequency'] == 'POPLATEK PO OBRATU') & (merged['type'] == 'OWNER')]\nresult = filtered['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T2.account_id = T3.account_id WHERE T1.A3 = 'east Bohemia' AND T2.frequency = 'POPLATEK PO OBRATU' AND T3.type = 'OWNER'", "difficulty": "moderate" }, { "question_id": 90, "question": "How many accounts who have region in Prague are eligible for loans?", "db_id": "financial", "evidence": "A3 contains the data of region", "code": "import pandas as pd\nmerged = pd.merge(account, loan, on='account_id')\nmerged = pd.merge(merged, district, on='district_id')\nprague_accounts = merged[merged['A3'] == 'Prague']\nresult = len(prague_accounts['account_id'].unique())", "sql": "SELECT COUNT(T1.account_id) FROM account AS T1 INNER JOIN loan AS T2 ON T1.account_id = T2.account_id INNER JOIN district AS T3 ON T1.district_id = T3.district_id WHERE T3.A3 = 'Prague'", "difficulty": "simple" }, { "question_id": 91, "question": "The average unemployment ratio of 1995 and 1996, which one has higher percentage?", "db_id": "financial", "evidence": "A12 refers to unemploymant rate 1995; A13 refers to unemploymant rate 1996", "code": "import pandas as pd\nimport numpy as np\n\navg_1995 = district['A12'].mean()\navg_1996 = district['A13'].mean()\n\nresult = pd.DataFrame({'year': ['1996' if avg_1996 > avg_1995 else '1995']})\nresult = result['year'].iloc[0]", "sql": "SELECT DISTINCT IIF(AVG(A13) > AVG(A12), '1996', '1995') FROM district", "difficulty": "simple" }, { "question_id": 92, "question": "List out the no. of districts that have female average salary is more than 6000 but less than 10000?", "db_id": "financial", "evidence": "A11 refers to average salary; Female mapps to gender = 'F'", "code": "import pandas as pd\nmerged = pd.merge(client, district, on='district_id')\nfemale_districts = merged[merged['gender'] == 'F']['district_id'].unique()\nfiltered = district[(district['district_id'].isin(female_districts)) & (district['A11'] > 6000) & (district['A11'] < 10000)]\nresult = len(filtered)", "sql": "SELECT COUNT(DISTINCT T2.district_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.gender = 'F' AND T2.A11 BETWEEN 6000 AND 10000", "difficulty": "simple" }, { "question_id": 93, "question": "How many male customers who are living in North Bohemia have average salary greater than 8000?", "db_id": "financial", "evidence": "Male means that gender = 'M'; A3 refers to region; A11 pertains to average salary.A3 refers to region names such as 'north Bohemia'; A11 refers to district average salary", "code": "import pandas as pd\nmerged = pd.merge(client, district, on='district_id')\nresult = merged[(merged['gender'] == 'M') & (merged['A3'] == 'north Bohemia') & (merged['A11'] > 8000)].shape[0]", "sql": "SELECT COUNT(T1.client_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.gender = 'M' AND T2.A3 = 'north Bohemia' AND T2.A11 > 8000", "difficulty": "moderate" }, { "question_id": 94, "question": "List out the account numbers of female clients who are oldest and has lowest average salary, calculate the gap between this lowest average salary with the highest average salary?", "db_id": "financial", "evidence": "Female means gender = 'F'; A11 refers to average salary; Gap = highest average salary - lowest average salary; If the person A's birthdate > B's birthdate, it means that person B is order than person A.", "code": "import pandas as pd\n\naccount = pd.read_csv('account.csv')\nclient = pd.read_csv('client.csv')\ndisp = pd.read_csv('disp.csv')\ndistrict = pd.read_csv('district.csv')\n\nclient['birth_date'] = pd.to_datetime(client['birth_date'])\nfemale_clients = client[client['gender'] == 'F']\noldest_birth = female_clients['birth_date'].min()\n\ndf = (disp.merge(account, on='account_id')\n .merge(client, on='client_id')\n .merge(district, left_on='district_id_y', right_on='district_id'))\n\ndf_oldest = df[df['birth_date'] == oldest_birth]\n\nif not df_oldest.empty:\n target = df_oldest.loc[df_oldest['A11'].idxmin()]\n account_id = int(target['account_id'])\n lowest_salary = target['A11']\n highest_salary = district['A11'].max()\n salary_gap = highest_salary - lowest_salary\n result = [account_id, int(lowest_salary), int(salary_gap)]\nelse:\n result = []\n\nprint(result)", "sql": "SELECT a.account_id, d.A11 AS lowest_avg_salary, (SELECT MAX(A11) FROM district) - d.A11 AS salary_gap FROM account a JOIN disp dp ON a.account_id = dp.account_id JOIN client c ON dp.client_id = c.client_id JOIN district d ON c.district_id = d.district_id WHERE c.gender = 'F' AND c.birth_date = (SELECT MIN(birth_date) FROM client WHERE gender = 'F') AND d.A11 = (SELECT MIN(d2.A11) FROM client c2 JOIN district d2 ON c2.district_id = d2.district_id WHERE c2.gender = 'F' AND c2.birth_date = (SELECT MIN(birth_date) FROM client WHERE gender = 'F'))", "difficulty": "challenging" }, { "question_id": 95, "question": "List out the account numbers of clients who are youngest and have highest average salary?", "db_id": "financial", "evidence": "If the person A's birthdate < B's birthdate, it means that person B is younger than person A; A11 refers to average salaryA11 refers to average salary; highest average salary refers to maximum value of A11", "code": "import pandas as pd\n# Convert birth_date to datetime for proper comparison\nclient['birth_date'] = pd.to_datetime(client['birth_date'])\n# Find youngest client(s)\nyoungest_client = client[client['birth_date'] == client['birth_date'].max()]\n# Merge required tables\nmerged = pd.merge(disp, account, on='account_id')\nmerged = pd.merge(merged, district, on='district_id')\nmerged = pd.merge(merged, youngest_client[['client_id']], on='client_id')\n# Sort by average salary descending and get top result\nresult = merged.sort_values('A11', ascending=False).head(1)[['account_id']]", "sql": "SELECT T1.account_id\nFROM account AS T1\nINNER JOIN disp AS T2 ON T1.account_id = T2.account_id\nINNER JOIN client AS T3 ON T2.client_id = T3.client_id\nINNER JOIN district AS T4 ON T1.district_id = T4.district_id\nWHERE T3.client_id IN (\n SELECT client_id\n FROM client\n ORDER BY birth_date DESC\n LIMIT 1\n)\nORDER BY T4.A11 DESC\nLIMIT 1", "difficulty": "moderate" }, { "question_id": 96, "question": "How many customers who choose statement of weekly issuance are Owner?", "db_id": "financial", "evidence": "'POPLATEK TYDNE' stands for weekly issuance", "code": "import pandas as pd\nmerged = pd.merge(account, disp, on='account_id')\nfiltered = merged[(merged['type'] == 'OWNER') & (merged['frequency'] == 'POPLATEK TYDNE')]\nresult = filtered['client_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.client_id) FROM account AS T1 INNER JOIN disp AS T2 ON T1.account_id = T2.account_id WHERE T2.type = 'OWNER' AND T1.frequency = 'POPLATEK TYDNE'", "difficulty": "simple" }, { "question_id": 97, "question": "List out the id number of client who choose statement of issuance after transaction are Disponent?", "db_id": "financial", "evidence": "'POPLATEK PO OBRATU' stands for issuance after transaction", "code": "import pandas as pd\nmerged = pd.merge(account, disp, on='account_id')\nfiltered = merged[(merged['frequency'] == 'POPLATEK PO OBRATU') & (merged['type'] == 'DISPONENT')]\nresult = filtered[['client_id']]", "sql": "SELECT T2.client_id FROM account AS T1 INNER JOIN disp AS T2 ON T1.account_id = T2.account_id WHERE T1.frequency = 'POPLATEK PO OBRATU' AND T2.type = 'DISPONENT';", "difficulty": "simple" }, { "question_id": 98, "question": "Among the accounts who have approved loan date in 1997, list out the accounts that have the lowest approved amount and choose weekly issuance statement.", "db_id": "financial", "evidence": "'POPLATEK TYDNE' stands for weekly issuance", "code": "import pandas as pd\n\nloan = pd.read_csv('loan.csv')\naccount = pd.read_csv('account.csv')\n\n# Parse date and filter for year 1997\nloan['date'] = pd.to_datetime(loan['date'], errors='coerce')\nloans_1997 = loan[loan['date'].dt.year == 1997]\n\n# Merge loan and account tables\nmerged_data = pd.merge(loans_1997, account, on='account_id', how='inner')\n\n# Filter by frequency\nweekly_accounts = merged_data[merged_data['frequency'] == 'POPLATEK TYDNE']\n\n# Sort by amount and take the top 1\nresult_df = weekly_accounts.sort_values(by='amount', ascending=True).head(1)\n\n# Extract account_id and format as list of lists\nif not result_df.empty:\n account_id = result_df.iloc[0]['account_id']\n result = [[account_id]]\nelse:\n result = []\n\nprint(result)", "sql": "SELECT T2.account_id FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE STRFTIME('%Y', T1.date) = '1997' AND T2.frequency = 'POPLATEK TYDNE' ORDER BY T1.amount LIMIT 1", "difficulty": "moderate" }, { "question_id": 99, "question": "Among the accounts who have loan validity more than 12 months, list out the accounts that have the highest approved amount and have account opening date in 1993.", "db_id": "financial", "evidence": "duration is greater than 12 in the database;", "code": "import pandas as pd\n\nloan = pd.read_csv('loan.csv')\naccount = pd.read_csv('account.csv')\n\n# Parse date in account table to find accounts opened in 1993\naccount['date'] = pd.to_datetime(account['date'], errors='coerce')\naccount_1993 = account[account['date'].dt.year == 1993]\n\n# Merge loan and account data\nmerged_data = pd.merge(loan, account_1993, on='account_id', how='inner')\n\n# Filter by loan duration > 12\nfiltered_data = merged_data[merged_data['duration'] > 12]\n\n# Sort by amount descending and take top 1\ntop_account = filtered_data.sort_values(by='amount', ascending=False).head(1)\n\n# Extract account_id and format as list of lists\nif not top_account.empty:\n account_id = top_account.iloc[0]['account_id']\n result = [[account_id]]\nelse:\n result = []\n\nprint(result)", "sql": "SELECT T1.account_id FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE STRFTIME('%Y', T2.date) = '1993' AND T1.duration > 12 ORDER BY T1.amount DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 100, "question": "Among the account opened, how many female customers who were born before 1950 and stayed in Sokolov?", "db_id": "financial", "evidence": "Customers refer to clients; Female refers to gender = 'F'; Names of districts appear in column A2", "code": "import pandas as pd\n\n# Filter female clients born before 1950\nfemale_clients = client[(client['gender'] == 'F') & (pd.to_datetime(client['birth_date']).dt.year < 1950)]\n\n# Filter districts for Sokolov\nsokolov_districts = district[district['A2'] == 'Sokolov']\n\n# Merge female clients with Sokolov districts\nclients_in_sokolov = pd.merge(female_clients, sokolov_districts, on='district_id')\n\n# Merge with disp to get account relationships\nclients_with_disp = pd.merge(clients_in_sokolov, disp, on='client_id')\n\n# Merge with account to ensure account exists\nclients_with_account = pd.merge(clients_with_disp, account, on='account_id')\n\n# Count distinct client_ids\nresult = clients_with_account['client_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.client_id) FROM district AS T1 INNER JOIN client AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T2.client_id = T3.client_id INNER JOIN account AS T4 ON T3.account_id = T4.account_id WHERE T2.gender = 'F' AND CAST(STRFTIME('%Y', T2.birth_date) AS INTEGER) < 1950 AND T1.A2 = 'Sokolov'", "difficulty": "moderate" }, { "question_id": 101, "question": "List out the accounts who have the earliest trading date in 1995 ?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\ntrans['date'] = pd.to_datetime(trans['date'])\nfiltered_1995 = trans[trans['date'].dt.year == 1995]\nmin_date = filtered_1995['date'].min()\nresult = filtered_1995[filtered_1995['date'] == min_date]['account_id']", "sql": "SELECT account_id FROM trans WHERE STRFTIME('%Y', date) = '1995' AND date = (SELECT MIN(date) FROM trans WHERE STRFTIME('%Y', date) = '1995')", "difficulty": "simple" }, { "question_id": 102, "question": "State different accounts who have account opening date before 1997 and own an amount of money greater than 3000USD", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\ndef solve_query(trans_df, account_df):\n # Ensure date columns are in datetime format\n if 'date' in account_df.columns:\n account_df['date'] = pd.to_datetime(account_df['date'])\n \n # Filter accounts with opening date before 1997\n filtered_accounts = account_df[account_df['date'].dt.year < 1997]\n\n # Merge with transactions data\n merged_data = pd.merge(trans_df, filtered_accounts, on='account_id', how='inner')\n\n # Filter transactions where amount > 3000\n result_data = merged_data[merged_data['amount'] > 3000]\n\n # Select distinct account IDs\n distinct_accounts = result_data['account_id'].drop_duplicates()\n\n return distinct_accounts.tolist()\n\n# Example function call (replace trans_df and account_df with actual DataFrames)\nresult = solve_query(trans_df, account_df)\nprint(result)", "sql": "SELECT DISTINCT T2.account_id FROM trans AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE STRFTIME('%Y', T2.date) < '1997' AND T1.amount > 3000", "difficulty": "simple" }, { "question_id": 103, "question": "Which client issued his/her card in 1994/3/3, give his/her client id.", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Convert issued date to datetime for comparison\ncard['issued'] = pd.to_datetime(card['issued'])\n\n# Filter cards issued on 1994-03-03\nfiltered_cards = card[card['issued'] == '1994-03-03']\n\n# Merge with disp to get client_id\nmerged = pd.merge(filtered_cards, disp, on='disp_id')\n\n# Get unique client_ids\nresult = merged[['client_id']]", "sql": "SELECT T2.client_id FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN card AS T3 ON T2.disp_id = T3.disp_id WHERE T3.issued = '1994-03-03'", "difficulty": "simple" }, { "question_id": 104, "question": "The transaction of 840 USD happened in 1998/10/14, when was this account opened?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter transactions for amount 840 and date 1998-10-14\nfiltered_trans = trans[(trans['amount'] == 840) & (trans['date'] == '1998-10-14')]\n\n# Merge with account table to get account opening date\nresult = pd.merge(account, filtered_trans, on='account_id')[['date_x']]\nresult.columns = ['date']\nresult = result['date']", "sql": "SELECT T1.date FROM account AS T1 INNER JOIN trans AS T2 ON T1.account_id = T2.account_id WHERE T2.amount = 840 AND T2.date = '1998-10-14'", "difficulty": "simple" }, { "question_id": 105, "question": "There was a loan approved in 1994/8/25, where was that account opened, give the district Id of the branch.", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Convert date string to datetime for comparison\nloan_filtered = loan[loan['date'] == '1994-08-25']\n\n# Merge with account table to get district_id\nresult = pd.merge(account[['account_id', 'district_id']], loan_filtered[['account_id']], on='account_id')['district_id']", "sql": "SELECT T1.district_id FROM account AS T1 INNER JOIN loan AS T2 ON T1.account_id = T2.account_id WHERE T2.date = '1994-08-25'", "difficulty": "simple" }, { "question_id": 106, "question": "What is the biggest amount of transaction that the client whose card was opened in 1996/10/21 made?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Merge card with disp\nmerged = pd.merge(card, disp, on='disp_id')\n\n# Merge with account\nmerged = pd.merge(merged, account, on='account_id')\n\n# Merge with trans\nmerged = pd.merge(merged, trans, on='account_id')\n\n# Filter by card issued date\nfiltered = merged[merged['issued'] == '1996-10-21']\n\n# Sort by amount descending and get the biggest amount\nresult = filtered.sort_values('amount', ascending=False).head(1)[['amount']]", "sql": "SELECT T4.amount FROM card AS T1 JOIN disp AS T2 ON T1.disp_id = T2.disp_id JOIN account AS T3 ON T2.account_id = T3.account_id JOIN trans AS T4 ON T3.account_id = T4.account_id WHERE T1.issued = '1996-10-21' ORDER BY T4.amount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 107, "question": "What is the gender of the oldest client who opened his/her account in the highest average salary branch?", "db_id": "financial", "evidence": "Earlier birthdate refers to older age; A11 refers to average salary", "code": "import pandas as pd\nmerged = district.merge(account, on='district_id').merge(disp, on='account_id').merge(client, on='client_id')\nsorted_df = merged.sort_values(['A11', 'birth_date'], ascending=[False, True])\nresult = sorted_df.iloc[0]['gender']", "sql": "SELECT T3.gender FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T4 ON T2.account_id = T4.account_id INNER JOIN client AS T3 ON T4.client_id = T3.client_id ORDER BY T1.A11 DESC, T3.birth_date ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 108, "question": "For the client who applied the biggest loan, what was his/her first amount of transaction after opened the account?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\ndef solve_query(account_df, loan_df, trans_df):\n try:\n # Ensure date columns are datetime type\n account_df['date'] = pd.to_datetime(account_df['date'])\n loan_df['date'] = pd.to_datetime(loan_df['date'])\n trans_df['date'] = pd.to_datetime(trans_df['date'])\n\n # Check for required columns\n required_columns = {'account_id': [account_df, loan_df, trans_df], 'amount': [loan_df, trans_df], 'date': [account_df, trans_df]}\n for col, dfs in required_columns.items():\n for df in dfs:\n if col not in df.columns:\n return pd.DataFrame() # Return empty DataFrame if column is missing\n\n # Step 1: Find the account with the largest loan\n merged_loan_account = pd.merge(loan_df, account_df, on='account_id', suffixes=('_loan', '_account'))\n max_loan = merged_loan_account.loc[merged_loan_account['amount'].idxmax()]\n target_account_id = max_loan['account_id']\n\n # Step 2: Filter transactions for this account where transaction date >= account opening date\n filtered_trans = trans_df[(trans_df['account_id'] == target_account_id) & (trans_df['date'] >= max_loan['date_account'])]\n\n # Step 3: Sort by transaction date ascending and select the first transaction amount\n result = filtered_trans.sort_values(by='date').iloc[:1][['amount']]\n return result\n\n except Exception as e:\n return pd.DataFrame() # Return empty DataFrame in case of error\n\n# Example function call (replace example DataFrames with actual data)\naccount_data = pd.DataFrame({'account_id': [1, 2, 3], 'district_id': [10, 20, 30], 'frequency': ['monthly', 'weekly', 'daily'], 'date': ['2023-01-01', '2023-02-01', '2023-03-01']})\nloan_data = pd.DataFrame({'loan_id': [101, 102, 103], 'account_id': [1, 2, 3], 'date': ['2023-01-05', '2023-02-05', '2023-03-05'], 'amount': [5000, 10000, 15000], 'duration': [12, 24, 36], 'payments': [500, 1000, 1500], 'status': ['A', 'B', 'C']})\ntrans_data = pd.DataFrame({'trans_id': [1001, 1002, 1003], 'account_id': [1, 2, 3], 'date': ['2023-01-10', '2023-02-10', '2023-03-10'], 'type': ['credit', 'debit', 'credit'], 'operation': [None, 'op1', 'op2'], 'amount': [100, 200, 300], 'balance': [500, 1000, 1500], 'k_symbol': [None, 'sym1', 'sym2'], 'bank': [None, 'bank1', 'bank2'], 'account': [None, 123, 456]})\n\nresult = solve_query(account_data, loan_data, trans_data)\nprint(result)", "sql": "SELECT T3.amount FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE T3.date >= T2.date ORDER BY T1.amount DESC, T3.date ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 109, "question": "How many clients opened their accounts in Jesenik branch were women?", "db_id": "financial", "evidence": "A2 has region names; Woman and female share the same meaning; female refers to gender = 'F'", "code": "import pandas as pd\nmerged = pd.merge(client, district, on='district_id')\nfiltered = merged[(merged['gender'] == 'F') & (merged['A2'] == 'Jesenik')]\nresult = filtered['client_id'].count()", "sql": "SELECT COUNT(DISTINCT T1.client_id) FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN district AS T4 ON T3.district_id = T4.district_id WHERE T1.gender = 'F' AND T4.A2 = 'Jesenik'", "difficulty": "simple" }, { "question_id": 110, "question": "What is the disposition id of the client who made 5100 USD transaction in 1998/9/2?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Merge disp with account\nmerged = pd.merge(disp, account, on='account_id')\n\n# Merge with trans\nmerged = pd.merge(merged, trans, on='account_id')\n\n# Filter for the specific date and amount\nfiltered = merged[(merged['date_y'] == '1998-09-02') & (merged['amount'] == 5100)]\n\n# Get the disp_id\nresult = filtered[['disp_id']]", "sql": "SELECT T1.disp_id FROM disp AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE T3.date='1998-09-02' AND T3.amount = 5100", "difficulty": "simple" }, { "question_id": 111, "question": "How many accounts were opened in Litomerice in 1996?", "db_id": "financial", "evidence": "A2 refers to district name; Litomerice is one of district names.", "code": "import pandas as pd\n\n# Filter district data for Litomerice\nlitomerice_district = district[district['A2'] == 'Litomerice']\n\n# Merge with account data\nmerged = pd.merge(litomerice_district[['district_id']], account, on='district_id')\n\n# Convert date to datetime and extract year\nmerged['year'] = pd.to_datetime(merged['date']).dt.year\n\n# Filter for accounts opened in 1996\naccounts_1996 = merged[merged['year'] == 1996]\n\n# Count the number of accounts\nresult = len(accounts_1996)", "sql": "SELECT COUNT(T2.account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id WHERE STRFTIME('%Y', T2.date) = '1996' AND T1.A2 = 'Litomerice'", "difficulty": "simple" }, { "question_id": 112, "question": "For the female client who was born in 1976/1/29, which district did she opened her account?", "db_id": "financial", "evidence": "Female refers to gender = 'F'; A2 refers to district names", "code": "import pandas as pd\n\n# Load the necessary tables\nclient_df = pd.read_csv('client.csv')\naccount_df = pd.read_csv('account.csv')\ndistrict_df = pd.read_csv('district.csv')\n\n# Filter the client DataFrame for the specific female client born on 1976-01-29\nfemale_client = client_df[(client_df['gender'] == 'F') & (client_df['birth_date'] == '1976-01-29')]\n\n# Get the district_id of the female client\ndistrict_id = female_client['district_id'].values[0]\n\n# Find the district name corresponding to the district_id\ndistrict_name = district_df[district_df['district_id'] == district_id]['A2'].values[0]\n\n# Record the final result\nresult = district_name\n\n# Print the final result\nprint(result)", "sql": "SELECT T1.A2 FROM district AS T1 INNER JOIN account AS T3 ON T1.district_id = T3.district_id INNER JOIN disp AS T4 ON T3.account_id = T4.account_id INNER JOIN client AS T2 ON T4.client_id = T2.client_id WHERE T2.birth_date = '1976-01-29' AND T2.gender = 'F' AND T4.type = 'OWNER'", "difficulty": "simple" }, { "question_id": 113, "question": "For the client who applied 98832 USD loan in 1996/1/3, when was his/her birthday?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter loan for the specific date and amount\nloan_filtered = loan[(loan['date'] == '1996-01-03') & (loan['amount'] == 98832)]\n\n# Merge with account\nmerged = pd.merge(loan_filtered, account, on='account_id')\n\n# Merge with disp\nmerged = pd.merge(merged, disp, on='account_id')\n\n# Merge with client to get birth_date\nmerged = pd.merge(merged, client, on='client_id')\n\n# Get the birth_date\nresult = merged[['birth_date']]", "sql": "SELECT T4.birth_date FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN disp AS T3 ON T2.account_id = T3.account_id INNER JOIN client AS T4 ON T3.client_id = T4.client_id WHERE T1.date = '1996-01-03' AND T1.amount = 98832", "difficulty": "simple" }, { "question_id": 114, "question": "For the first client who opened his/her account in Prague, what is his/her account ID?", "db_id": "financial", "evidence": "A3 stands for region names", "code": "import pandas as pd\n\ndef solve_query(account_df, district_df, disp_df, client_df):\n # Ensure date column is in datetime format\n if 'date' in account_df.columns:\n account_df['date'] = pd.to_datetime(account_df['date'])\n\n # Step 1: Filter Prague districts\n prague_districts = district_df[district_df['A3'] == 'Prague']\n\n # Step 2: Join account with Prague districts\n account_prague = pd.merge(account_df, prague_districts, left_on='district_id', right_on='district_id')\n\n # Step 3: Join with disp to find account owners (type='OWNER')\n owner_disp = disp_df[disp_df['type'] == 'OWNER']\n account_owner = pd.merge(account_prague, owner_disp, left_on='account_id', right_on='account_id')\n\n # Step 4: Join with client table\n account_client = pd.merge(account_owner, client_df, left_on='client_id', right_on='client_id')\n\n # Step 5: Sort by account opening date and select the first result\n account_client = account_client.sort_values(by='date')\n if not account_client.empty:\n return account_client.iloc[0]['account_id']\n else:\n return None\n\n# Example usage\ndata_account = pd.DataFrame({'account_id': [1, 2], 'district_id': [101, 102], 'frequency': ['WEEKLY', 'MONTHLY'], 'date': ['1998-01-01', '1998-02-01']})\ndata_district = pd.DataFrame({'district_id': [101, 102], 'A2': ['Region1', 'Region2'], 'A3': ['Prague', 'Other'], 'A4': ['City1', 'City2'], 'A5': ['District1', 'District2'], 'A6': ['Area1', 'Area2'], 'A7': ['Zone1', 'Zone2'], 'A8': [100, 200], 'A9': [50, 60], 'A10': [1.1, 2.2], 'A11': [30, 40], 'A12': [None, 1.5], 'A13': [0.8, 0.9], 'A14': [10, 20], 'A15': [None, 5], 'A16': [100, 200]})\ndata_disp = pd.DataFrame({'disp_id': [1001, 1002], 'client_id': [101, 102], 'account_id': [1, 2], 'type': ['OWNER', 'DISP']})\ndata_client = pd.DataFrame({'client_id': [101, 102], 'gender': ['M', 'F'], 'birth_date': ['1970-01-01', '1980-01-01'], 'district_id': [101, 102]})\n\nresult = solve_query(data_account, data_district, data_disp, data_client)\nprint(result)", "sql": "SELECT T1.account_id FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T1.account_id = T3.account_id INNER JOIN client AS T4 ON T3.client_id = T4.client_id WHERE T2.A3 = 'Prague' AND T3.type = 'OWNER' ORDER BY T1.date ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 115, "question": "For the branch which located in the south Bohemia with biggest number of inhabitants, what is the percentage of the male clients?", "db_id": "financial", "evidence": "Percentage of the male clients = DIVIDE(COUNT(male clients), COUNT(clients)) * 100; Male refers to gender = 'M', A3 is the region name. A4 contains the information about inhabitants.", "code": "import pandas as pd\nmerged = pd.merge(client, district, on='district_id')\nsouth_bohemia = merged[merged['A3'] == 'south Bohemia']\ngrouped = south_bohemia.groupby('A4').agg({'gender': 'count', 'client_id': 'count'})\ngrouped['male_count'] = south_bohemia[south_bohemia['gender'] == 'M'].groupby('A4').size()\ngrouped = grouped.fillna(0)\ngrouped['percentage'] = (grouped['male_count'] / grouped['client_id']) * 100\nresult = grouped.sort_values('A4', ascending=False).head(1)['percentage']", "sql": "SELECT CAST(SUM(T1.gender = 'M') AS REAL) * 100 / COUNT(T1.client_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T2.A3 = 'south Bohemia' AND T2.A4 = (SELECT MAX(A4) FROM district WHERE A3 = 'south Bohemia')", "difficulty": "challenging" }, { "question_id": 116, "question": "For the client whose loan was approved first in 1993/7/5, what is the increase rate of his/her account balance from 1993/3/22 to 1998/12/27?", "db_id": "financial", "evidence": "ratio calculated by dividing his by her;", "code": "import pandas as pd\n\n# Get the first approved loan on 1993-07-05\nloan_1993 = loan[loan['date'] == '1993-07-05'].sort_values('loan_id').head(1)\naccount_id = loan_1993['account_id'].iloc[0]\n\n# Get balance on 1993-03-22\nstart_balance = trans[(trans['account_id'] == account_id) & (trans['date'] == '1993-03-22')]['balance'].iloc[0]\n\n# Get balance on 1998-12-27\nend_balance = trans[(trans['account_id'] == account_id) & (trans['date'] == '1998-12-27')]['balance'].iloc[0]\n\n# Calculate increase rate\nresult = (end_balance - start_balance) * 100.0 / start_balance", "sql": "SELECT (T_end.balance - T_start.balance)*100.0/T_start.balance FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN (SELECT account_id, balance FROM trans WHERE date = '1993-03-22' GROUP BY account_id) AS T_start ON T2.account_id = T_start.account_id INNER JOIN (SELECT account_id, balance FROM trans WHERE date = '1998-12-27' GROUP BY account_id) AS T_end ON T2.account_id = T_end.account_id WHERE T1.date = '1993-07-05' ORDER BY T1.loan_id LIMIT 1", "difficulty": "challenging" }, { "question_id": 117, "question": "What is the percentage of loan amount that has been fully paid with no issue.", "db_id": "financial", "evidence": "status equals 'A' in the database;", "code": "import pandas as pd\nresult = (loan[loan['status'] == 'A']['amount'].sum() * 100) / loan['amount'].sum()", "sql": "SELECT (CAST(SUM(CASE WHEN status = 'A' THEN amount ELSE 0 END) AS REAL) * 100) / SUM(amount) FROM loan", "difficulty": "moderate" }, { "question_id": 118, "question": "For loan amount less than USD100,000, what is the percentage of accounts that is still running with no issue.", "db_id": "financial", "evidence": "Status equals 'C' in the database;", "code": "import pandas as pd\n\nfiltered_loans = loan[loan['amount'] < 100000]\npercentage = (filtered_loans['status'] == 'C').sum() * 100 / len(filtered_loans)\nresult = percentage", "sql": "SELECT CAST(SUM(status = 'C') AS REAL) * 100 / COUNT(account_id) FROM loan WHERE amount < 100000", "difficulty": "moderate" }, { "question_id": 119, "question": "For accounts in 1993 with statement issued after transaction, list the account ID, district name and district region.", "db_id": "financial", "evidence": "Records about district names could be found in A2; A3 contains the information about regions. 'POPLATEK PO OBRATU' stands for issuance after transaction", "code": "import pandas as pd\n\n# Filter accounts from 1993 with 'POPLATEK PO OBRATU' frequency\nfiltered_accounts = account[(account['frequency'] == 'POPLATEK PO OBRATU') & (pd.to_datetime(account['date']).dt.year == 1993)]\n\n# Merge with district table to get district name (A2) and region (A3)\nresult = pd.merge(filtered_accounts[['account_id', 'district_id']], district[['district_id', 'A2', 'A3']], on='district_id')[['account_id', 'A2', 'A3']]", "sql": "SELECT T1.account_id, T2.A2, T2.A3 FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.frequency = 'POPLATEK PO OBRATU' AND STRFTIME('%Y', T1.date)= '1993'", "difficulty": "moderate" }, { "question_id": 120, "question": "From Year 1995 to 2000, who are the accounts holders from 'east Bohemia'. State the account ID the frequency of statement issuance.", "db_id": "financial", "evidence": "Accounts holder refers to the person who own this account.", "code": "import pandas as pd\n\n# Filter accounts from east Bohemia between 1995-2000\nmerged = pd.merge(account, district, on='district_id')\nfiltered = merged[merged['A3'] == 'east Bohemia']\nfiltered['year'] = pd.to_datetime(filtered['date']).dt.year\nfiltered = filtered[(filtered['year'] >= 1995) & (filtered['year'] <= 2000)]\nresult = filtered[['account_id', 'frequency']]", "sql": "SELECT T1.account_id, T1.frequency FROM account AS T1 INNER JOIN disp AS T2 ON T1.account_id = T2.account_id INNER JOIN client AS T3 ON T2.client_id = T3.client_id INNER JOIN district AS T4 ON T3.district_id = T4.district_id WHERE T4.A3 = 'east Bohemia' AND STRFTIME('%Y', T1.date) BETWEEN '1995' AND '2000' AND T2.type = 'OWNER'", "difficulty": "moderate" }, { "question_id": 121, "question": "List account ID and account opening date for accounts from 'Prachatice'.", "db_id": "financial", "evidence": "A2 refers to the names of districts.", "code": "import pandas as pd\n\ndef solve_query(account_data, district_data):\n # Ensure the necessary columns exist\n if 'district_id' not in account_data.columns or 'district_id' not in district_data.columns:\n return pd.DataFrame(columns=['account_id', 'date'])\n\n if 'A2' not in district_data.columns:\n return pd.DataFrame(columns=['account_id', 'date'])\n\n # Merge account and district data on district_id\n merged_data = pd.merge(account_data, district_data, on='district_id', how='inner')\n\n # Filter rows where A2 is 'Prachatice'\n filtered_data = merged_data[merged_data['A2'] == 'Prachatice']\n\n # Select required columns\n result_data = filtered_data[['account_id', 'date']]\n\n return result_data\n\n# Example usage with dummy data\naccount_table = pd.DataFrame({\n 'account_id': [1, 2, 3],\n 'district_id': [101, 102, 103],\n 'frequency': ['WEEKLY', 'MONTHLY', 'WEEKLY'],\n 'date': ['2023-01-01', '2023-02-01', '2023-03-01']\n})\n\ndistrict_table = pd.DataFrame({\n 'district_id': [101, 102, 103],\n 'A2': ['Prachatice', 'OtherDistrict', 'Prachatice'],\n 'A3': ['SomeValue', 'AnotherValue', 'YetAnotherValue']\n})\n\n# Call the function with example data\nresult = solve_query(account_table, district_table)\nprint(result)", "sql": "SELECT T1.account_id, T1.date FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T2.A2 = 'Prachatice'", "difficulty": "simple" }, { "question_id": 122, "question": "State the district and region for loan ID '4990'.", "db_id": "financial", "evidence": "A2, A3 contains the information about district and region respectively.", "code": "import pandas as pd\n\n# Merge loan with account to get district_id\nmerged = pd.merge(loan[loan['loan_id'] == 4990], account, on='account_id')\n\n# Merge with district to get A2 (district) and A3 (region)\nresult = pd.merge(merged, district[['district_id', 'A2', 'A3']], on='district_id')[['A2', 'A3']]", "sql": "SELECT T2.A2, T2.A3 FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN loan AS T3 ON T1.account_id = T3.account_id WHERE T3.loan_id = 4990", "difficulty": "simple" }, { "question_id": 123, "question": "Provide the account ID, district and region for loan amount greater than USD300,000.", "db_id": "financial", "evidence": "A2 contains district names and A3 contains region names.", "code": "import pandas as pd\n\n# Merge account with district\nmerged = pd.merge(account, district, on='district_id')\n\n# Merge with loan\nmerged = pd.merge(merged, loan, on='account_id')\n\n# Filter loans greater than 300000\nfiltered = merged[merged['amount'] > 300000]\n\n# Select required columns\nresult = filtered[['account_id', 'A2', 'A3']]", "sql": "SELECT T1.account_id, T2.A2, T2.A3 FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN loan AS T3 ON T1.account_id = T3.account_id WHERE T3.amount > 300000", "difficulty": "simple" }, { "question_id": 124, "question": "List the loan ID, district and average salary for loan with duration of 60 months.", "db_id": "financial", "evidence": "A3 refers to regions; A11 refers to average salary", "code": "import pandas as pd\nimport re\n\nread_kwargs = dict(low_memory=False)\naccount = pd.read_csv('account.csv', **read_kwargs)\ndistrict = pd.read_csv('district.csv', **read_kwargs)\nloan = pd.read_csv('loan.csv', **read_kwargs)\n\nfor df in (account, district, loan):\n for c in ('account_id', 'district_id'):\n if c in df.columns:\n df[c] = pd.to_numeric(df[c], errors='coerce').astype('Int64')\n\ndef to_int_months(s):\n if pd.isna(s):\n return pd.NA\n s = str(s)\n m = re.search(r'\\d+', s)\n return int(m.group()) if m else pd.NA\n\n\nloan['duration'] = loan['duration'].apply(to_int_months).astype('Int64')\n\n\naccount_cols = [c for c in account.columns if c in ('account_id','district_id')]\ndistrict_cols = [c for c in district.columns if c in ('district_id','A2','A11')]\nloan_cols = [c for c in loan.columns if c in ('loan_id','account_id','duration')]\n\nacc_dist = account[account_cols].merge(district[district_cols], on='district_id', how='inner')\nmerged = acc_dist.merge(loan[loan_cols], on='account_id', how='inner')\n\nfiltered = merged[merged['duration'] == 60]\n\nresult_df = filtered[['loan_id', 'A2', 'A11']].sort_values('loan_id', kind='mergesort')\n\nresult = result_df.values.tolist()\n\nprint(result)", "sql": "SELECT T3.loan_id, T2.A2, T2.A11 FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN loan AS T3 ON T1.account_id = T3.account_id WHERE T3.duration = 60", "difficulty": "simple" }, { "question_id": 125, "question": "For loans contracts which are still running where client are in debt, list the district of the and the state the percentage unemployment rate increment from year 1995 to 1996.", "db_id": "financial", "evidence": "status equals 'D' in the database; A12 refers to unemployment rate in 1995; A13 refers to unemployment rate in 1996;", "code": "import pandas as pd\n\naccount = pd.read_csv('account.csv')\ncard = pd.read_csv('card.csv')\nclient = pd.read_csv('client.csv')\ndisp = pd.read_csv('disp.csv')\ndistrict = pd.read_csv('district.csv')\nloan = pd.read_csv('loan.csv')\norder = pd.read_csv('order.csv')\ntrans = pd.read_csv('trans.csv')\n\nrunning_debt_loans = loan[loan['status'] == 'D']\nrunning_debt_accounts = running_debt_loans[['account_id']].drop_duplicates()\nrunning_debt_disps = pd.merge(running_debt_accounts, disp, on='account_id')\nrunning_debt_clients = pd.merge(running_debt_disps, client, on='client_id')\nrunning_debt_districts = pd.merge(running_debt_clients, district, on='district_id')\nunemployment_rate_change = (running_debt_districts['A13'] - running_debt_districts['A12']) / running_debt_districts['A12'] * 100\nresult = running_debt_districts[['A2', 'A3']].drop_duplicates()\nresult['unemployment_rate_change'] = unemployment_rate_change\n\nprint(result)", "sql": "SELECT T3.A2 AS district_name, (T3.A13 - T3.A12) * 100.0 / T3.A12 AS unemployment_increment FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN disp AS T4 ON T2.account_id = T4.account_id INNER JOIN client AS T5 ON T4.client_id = T5.client_id INNER JOIN district AS T3 ON T5.district_id = T3.district_id WHERE T1.status = 'D' GROUP BY T3.district_id", "difficulty": "challenging" }, { "question_id": 126, "question": "Calculate the percentage of account from 'Decin' district for all accounts are opened in 1993.", "db_id": "financial", "evidence": "A2 contains the information about district.", "code": "import pandas as pd\nimport numpy as np\n\n# Merge district and account tables\nmerged = pd.merge(district, account, on='district_id')\n\n# Filter accounts opened in 1993\nmerged['year'] = pd.to_datetime(merged['date']).dt.year\nfiltered = merged[merged['year'] == 1993]\n\n# Calculate percentage of accounts from 'Decin' district\npercentage = (filtered['A2'] == 'Decin').sum() * 100.0 / len(filtered)\n\nresult = percentage", "sql": "SELECT CAST(SUM(T1.A2 = 'Decin') AS REAL) * 100 / COUNT(account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id WHERE STRFTIME('%Y', T2.date) = '1993'", "difficulty": "simple" }, { "question_id": 127, "question": "List the account IDs with monthly issuance of statements.", "db_id": "financial", "evidence": "'POPLATEK MESICNE' stands for monthly issuance", "code": "import pandas as pd\nresult = account[account['frequency'] == 'POPLATEK MESICNE'][['account_id']]", "sql": "SELECT account_id FROM account WHERE Frequency = 'POPLATEK MESICNE'", "difficulty": "simple" }, { "question_id": 128, "question": "List the top nine districts, by descending order, from the highest to the lowest, the number of female account holders.", "db_id": "financial", "evidence": "A2 refers to districts; Female refers to gender = 'F'", "code": "import pandas as pd\nfemale_clients = client[client['gender'] == 'F']\nclients_disp = pd.merge(female_clients, disp, on='client_id')\nowners = clients_disp[clients_disp['type'] == 'OWNER']\nmerged_district = pd.merge(owners, district, on='district_id')\ncounts = merged_district.groupby(['district_id', 'A2'])['client_id'].nunique().reset_index()\nsorted_counts = counts.sort_values(by='client_id', ascending=False).head(9)\nresult = sorted_counts[['A2', 'client_id']]", "sql": "SELECT T3.A2, COUNT(DISTINCT T1.client_id) FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN account AS T4 ON T2.account_id = T4.account_id INNER JOIN district AS T3 ON T1.district_id = T3.district_id WHERE T1.gender = 'F' AND T2.type = 'OWNER' GROUP BY T3.district_id, T3.A2 ORDER BY COUNT(DISTINCT T1.client_id) DESC LIMIT 9", "difficulty": "moderate" }, { "question_id": 129, "question": "Which are the top ten withdrawals (non-credit card) by district names for the month of January 1996?", "db_id": "financial", "evidence": "Non-credit card withdraws refers to type = 'VYDAJ'; January 1996 can be found by date LIKE '1996-01%' in the database; A2 means district namesNon-credit card withdraws refers to type = 'VYDAJ'; January 1996 can be found by date LIKE '1996-01%'; A2 means district names; count of withdrawals per district requires GROUP BY A2 and ORDER BY COUNT(*) DESC", "code": "import pandas as pd\n# Merge district and account on district_id\ndistrict_account = pd.merge(district, account, on='district_id')\n# Merge with trans on account_id\nall_data = pd.merge(district_account, trans, on='account_id')\n# Filter by withdrawal type and date range\nfiltered = all_data[(all_data['type'] == 'VYDAJ') & (all_data['date_y'].str.startswith('1996-01'))]\n# Group by district name, sum amounts\nresult = filtered.groupby('A2')['amount'].sum().reset_index(name='total_withdrawal')\n# Sort and get top 10\nresult = result.sort_values('total_withdrawal', ascending=False).head(10)", "sql": "SELECT T1.A2, SUM(T3.amount) AS total_withdrawal FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE T3.type = 'VYDAJ' AND T3.date LIKE '1996-01%' GROUP BY T1.A2 ORDER BY total_withdrawal DESC LIMIT 10", "difficulty": "moderate" }, { "question_id": 130, "question": "How many of the account holders in South Bohemia still do not own credit cards?", "db_id": "financial", "evidence": "A3 contains the region names; South Bohemia is one of region names.", "code": "import pandas as pd\nmerged1 = pd.merge(district, client, on='district_id')\nsouth_bohemia = merged1[merged1['A3'] == 'South Bohemia']\nmerged2 = pd.merge(south_bohemia, disp, on='client_id')\nowners = merged2[merged2['type'] == 'OWNER']\nmerged3 = pd.merge(owners, card, on='disp_id', how='left')\no_cards = merged3[merged3['card_id'].isnull()]\nresult = o_cards['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T3.account_id) FROM district AS T1 INNER JOIN client AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T2.client_id = T3.client_id LEFT JOIN card AS T4 ON T3.disp_id = T4.disp_id WHERE T1.A3 = 'South Bohemia' AND T3.type = 'OWNER' AND T4.card_id IS NULL", "difficulty": "moderate" }, { "question_id": 131, "question": "Which district has highest active loan?", "db_id": "financial", "evidence": "A3 refers to district names; Active loan refers to running contracts; Status = 'C' stands for running contract, OK so far; Status = 'D' stands for running contract, client in debt", "code": "import pandas as pd\n\n# Merge account with district\nmerged = pd.merge(account, district, on='district_id')\n\n# Merge with loan\nmerged = pd.merge(merged, loan, on='account_id')\n\n# Filter for active loans (status C or D)\nactive_loans = merged[merged['status'].isin(['C', 'D'])]\n\n# Group by district name (A3) and sum the loan amounts\ndistrict_totals = active_loans.groupby('A3')['amount'].sum().reset_index()\n\n# Sort by amount descending and get the top district\nresult = district_totals.sort_values('amount', ascending=False).head(1)['A3'].iloc[0]", "sql": "SELECT T2.A3 FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN loan AS T3 ON T1.account_id = T3.account_id WHERE T3.status IN ('C', 'D') GROUP BY T2.A3 ORDER BY SUM(T3.amount) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 132, "question": "What is the average loan amount by male borrowers?", "db_id": "financial", "evidence": "gender equals 'M' in the database; gender = 'M' refers to male records;", "code": "import pandas as pd\n\n# Filter male clients\nmale_clients = client[client['gender'] == 'M']\n\n# Join male clients with disp\nmerged1 = pd.merge(male_clients, disp, on='client_id')\n\n# Join with account\nmerged2 = pd.merge(merged1, account, on='account_id')\n\n# Join with loan\nmerged3 = pd.merge(merged2, loan, on='account_id')\n\n# Calculate average loan amount\nresult = merged3['amount'].mean()", "sql": "SELECT AVG(T4.amount) FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN loan AS T4 ON T3.account_id = T4.account_id WHERE T1.gender = 'M'", "difficulty": "simple" }, { "question_id": 133, "question": "In 1996, which districts have the highest unemployment rate? List their branch location and district name.", "db_id": "financial", "evidence": "A2 refers to district names; A13 refers to unemploymant rate in 1996", "code": "import pandas as pd\n\ndistrict = pd.read_csv('district.csv')\n\n# Filter out null values for A13 (Unemployment rate 1996)\nvalid_districts = district[district['A13'].notna()]\n\n# Sort by A13 descending and take the top 1\ntop_district = valid_districts.sort_values(by='A13', ascending=False).head(1)\n\n# Select columns matching SQL output: district_id, A2, A13\nresult_data = top_district[['district_id', 'A2', 'A13']]\n\n# Convert to list of lists\nresult = result_data.values.tolist()\n\nprint(result)", "sql": "SELECT district_id, A2, A13 FROM district WHERE A13 IS NOT NULL ORDER BY A13 DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 134, "question": "In the branch where the largest number of crimes were committed in 1996, how many accounts were opened?", "db_id": "financial", "evidence": "A16 refers to number of crimes in 1996;", "code": "import pandas as pd\n\n# Read the district table\ndistrict_df = pd.read_csv('district.csv')\n\n# Find the district with the largest number of crimes in 1996 (A16)\ndistrict_with_max_crimes = district_df.loc[district_df['A16'].idxmax()]\n\n# Get the district_id of the district with the largest number of crimes\ndistrict_id_with_max_crimes = district_with_max_crimes['district_id']\n\n# Read the account table\naccount_df = pd.read_csv('account.csv')\n\n# Filter the accounts by the district_id with the largest number of crimes\naccounts_in_max_crime_district = account_df[account_df['district_id'] == district_id_with_max_crimes]\n\n# Count the number of accounts opened in that district\nnumber_of_accounts = accounts_in_max_crime_district.shape[0]\n\n# Record the final result\nresult = number_of_accounts\n\n# Print the final result\nprint(result)", "sql": "SELECT COUNT(T2.account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id GROUP BY T1.A16 ORDER BY T1.A16 DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 135, "question": "After making a credit card withdrawal, how many account/s with monthly issuance has a negative balance?", "db_id": "financial", "evidence": "Operation equals 'VYBER KARTOU' in the database; Frequency equals 'POPLATEK MESICNE' in the database; balance is less than 0 in the database;trans refers to set_translations in the database", "code": "import pandas as pd\nmerged = pd.merge(trans, account, on='account_id')\nfiltered = merged[(merged['operation'] == 'VYBER KARTOU') & (merged['frequency'] == 'POPLATEK MESICNE') & (merged['balance'] < 0)]\nresult = filtered['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.account_id) FROM trans AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE T1.balance < 0 AND T1.operation = 'VYBER KARTOU' AND T2.frequency = 'POPLATEK MESICNE'", "difficulty": "moderate" }, { "question_id": 136, "question": "Between 1/1/1995 and 12/31/1997, how many loans in the amount of at least 250,000 per account that chose monthly statement issuance were approved?", "db_id": "financial", "evidence": "Frequency equals 'POPLATEK MESICNE' in the database;monthly statement issuance refers to frequency equals 'POPLATEK MESICNE'", "code": "import pandas as pd\nmerged = pd.merge(account, loan, on='account_id')\nfiltered = merged[(merged['date_y'] >= '1995-01-01') & (merged['date_y'] <= '1997-12-31') & (merged['frequency'] == 'POPLATEK MESICNE') & (merged['amount'] >= 250000) & (merged['status'] == 'A')]\nresult = filtered.groupby('account_id').size().reset_index(name='count')", "sql": "SELECT COUNT(T1.account_id) FROM account AS T1 INNER JOIN loan AS T2 ON T1.account_id = T2.account_id WHERE T2.date BETWEEN '1995-01-01' AND '1997-12-31' AND T1.frequency = 'POPLATEK MESICNE' AND T2.amount >= 250000 AND T2.status = 'A'", "difficulty": "moderate" }, { "question_id": 137, "question": "How many accounts have running contracts in Branch location 1?", "db_id": "financial", "evidence": "Status equals 'C' in the database; Status equals 'D' in the database;Status equals 'C' in the database refers to running contracts; Status equals 'D' in the database refers to running contracts", "code": "import pandas as pd\nmerged_ad = pd.merge(account, district, on='district_id')\nfiltered_ad = merged_ad[merged_ad['A2'] == 'Branch Location 1']\nmerged_loan = pd.merge(filtered_ad, loan, on='account_id')\nfiltered_loan = merged_loan[merged_loan['status'].isin(['C', 'D'])]\nresult = filtered_loan['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.account_id) FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN loan AS T3 ON T1.account_id = T3.account_id WHERE T2.A2 = 'Branch Location 1' AND T3.status = 'C'", "difficulty": "moderate" }, { "question_id": 138, "question": "In the branch where the second-highest number of crimes were committed in 1995 occurred, how many male clients are there?", "db_id": "financial", "evidence": "Male refers to gender = 'M'; A15 stands for no. of commited crimes 1995", "code": "import pandas as pd\n\nclient = pd.read_csv('client.csv')\ndistrict = pd.read_csv('district.csv')\n\n# Sort districts by number of crimes in 1995 (A15) descending\n# SQL logic: ORDER BY T3.A15 DESC LIMIT 1, 1 (Gets the 2nd record)\nsorted_districts = district.sort_values('A15', ascending=False)\n\n# Get the A15 value from the second row\ntarget_a15 = sorted_districts.iloc[1]['A15']\n\n# Merge client and district\nmerged_data = pd.merge(client, district, on='district_id')\n\n# Filter for Male clients in districts with the specific A15 value\nfiltered_clients = merged_data[\n (merged_data['gender'] == 'M') &\n (merged_data['A15'] == target_a15)\n]\n\n# Count the clients and format result as list of lists\ncount = len(filtered_clients)\nresult = [[count]]\n\nprint(result)", "sql": "SELECT COUNT(T1.client_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.gender = 'M' AND T2.A15 = (SELECT T3.A15 FROM district AS T3 ORDER BY T3.A15 DESC LIMIT 1, 1)", "difficulty": "moderate" }, { "question_id": 139, "question": "How many high-level credit cards have \"OWNER\" type of disposition?", "db_id": "financial", "evidence": "High-level credit cards refers to the cards with the gold type.", "code": "import pandas as pd\n\n# Merge card and disp tables\nmerged = pd.merge(card, disp, on='disp_id')\n\n# Filter for gold cards with OWNER disposition\nfiltered = merged[(merged['type_x'] == 'gold') & (merged['type_y'] == 'OWNER')]\n\n# Count the number of card_ids\nresult = len(filtered)", "sql": "SELECT COUNT(T1.card_id) FROM card AS T1 INNER JOIN disp AS T2 ON T1.disp_id = T2.disp_id WHERE T1.type = 'gold' AND T2.type = 'OWNER'", "difficulty": "simple" }, { "question_id": 140, "question": "How many accounts are there in the district of \"Pisek\"?", "db_id": "financial", "evidence": "A2 refers to district name", "code": "import pandas as pd\nmerged = pd.merge(account, district, on='district_id')\nfiltered = merged[merged['A2'] == 'Pisek']\nresult = len(filtered)", "sql": "SELECT COUNT(T1.account_id) FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T2.A2 = 'Pisek'", "difficulty": "simple" }, { "question_id": 141, "question": "Which districts have transactions greater than USS$10,000 in 1997?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter transactions for year 1997\ntrans['date'] = pd.to_datetime(trans['date'])\ntrans_1997 = trans[trans['date'].dt.year == 1997]\n\n# Merge with account to get district_id\nmerged = pd.merge(account[['account_id', 'district_id']], trans_1997[['account_id', 'amount']], on='account_id')\n\n# Group by district_id and sum amounts\ndistrict_sums = merged.groupby('district_id')['amount'].sum().reset_index()\n\n# Filter districts with total amount > 10000\nresult = district_sums[district_sums['amount'] > 10000][['district_id']]", "sql": "SELECT T1.district_id FROM account AS T1 INNER JOIN trans AS T3 ON T1.account_id = T3.account_id WHERE STRFTIME('%Y', T3.date) = '1997' GROUP BY T1.district_id HAVING SUM(T3.amount) > 10000", "difficulty": "simple" }, { "question_id": 142, "question": "Which accounts placed orders for household payment in Pisek?", "db_id": "financial", "evidence": "k_symbol equals 'SIPO' in the database;trans refers to set_translations; k_symbol refers to 'SIPO' in set_translations", "code": "import pandas as pd\nresult = pd.merge(pd.merge(order, account, on='account_id'), district, on='district_id').query(\"k_symbol == 'SIPO' and A2 == 'Pisek'\").account_id.drop_duplicates()", "sql": "SELECT DISTINCT T1.account_id FROM `order` AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN district AS T3 ON T2.district_id = T3.district_id WHERE T1.k_symbol = 'SIPO' AND T3.A2 = 'Pisek'", "difficulty": "simple" }, { "question_id": 143, "question": "What are the accounts that have gold credit cards?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\ndisp = pd.read_csv('disp.csv')\ncard = pd.read_csv('card.csv')\n\n# Merge tables on disp_id with suffixes for overlapping column names\nmerged_data = pd.merge(disp, card, on='disp_id', suffixes=('_disp', '_card'))\n\n# Filter for gold cards\ngold_accounts = merged_data[merged_data['type_card'] == 'gold']\n\n# Extract unique account_ids\naccount_ids = gold_accounts['account_id'].unique()\n\n# Format result as list of lists\nresult = [[x] for x in account_ids]\n\nprint(result)", "sql": "SELECT T2.account_id FROM disp AS T2 INNER JOIN card AS T1 ON T1.disp_id = T2.disp_id WHERE T1.type = 'gold'", "difficulty": "simple" }, { "question_id": 144, "question": "How much is the average amount in credit card made by account holders in a month, in year 2021?", "db_id": "financial", "evidence": "Operation equals 'VYBER KARTOU' in the database;", "code": "import pandas as pd\n\n# Load the datasets\naccount = pd.read_csv('account.csv')\ncard = pd.read_csv('card.csv')\ndisp = pd.read_csv('disp.csv')\ntrans = pd.read_csv('trans.csv')\n\n# 1. Convert date columns to datetime objects strictly\ntrans['date'] = pd.to_datetime(trans['date'])\n\n# 2. Filter transactions strictly according to the prompt\n# Year: 2021\n# Operation: 'VYBER KARTOU' (Matches Standard SQL logic for card withdrawal)\ntrans_filtered = trans[\n (trans['date'].dt.year == 2021) & \n (trans['operation'] == 'VYBER KARTOU')\n]\n\n# 3. Perform Inner Joins to mimic the logical structure of verifying account/card existence\n# Join Chain: card -> disp -> account -> trans\n# This ensures the transaction belongs to an account that actually has an issued card.\nmerged_df = pd.merge(card, disp, on='disp_id', how='inner')\nmerged_df = pd.merge(merged_df, account, on='account_id', how='inner')\nmerged_df = pd.merge(merged_df, trans_filtered, on='account_id', how='inner')\n\n# 4. Calculate the average amount\nif not merged_df.empty:\n result = merged_df['amount'].mean()\nelse:\n result = None\n\nprint(result)", "sql": "SELECT AVG(T4.amount) FROM card AS T1 INNER JOIN disp AS T2 ON T1.disp_id = T2.disp_id INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN trans AS T4 ON T3.account_id = T4.account_id WHERE STRFTIME('%Y', T4.date) = '2021' AND T4.operation = 'VYBER KARTOU'", "difficulty": "moderate" }, { "question_id": 145, "question": "Who are the account holder identification numbers whose who have transactions on the credit card with the amount is less than the average, in 1998?", "db_id": "financial", "evidence": "Operation equals 'VYBER KARTOU' in the database;", "code": "import pandas as pd\n\nclient_df = pd.read_csv('client.csv')\nclient_df['birth_date'] = pd.to_datetime(client_df['birth_date'])\ndisp_df = pd.read_csv('disp.csv')\naccount_df = pd.read_csv('account.csv')\naccount_df['date'] = pd.to_datetime(account_df['date'])\ntrans_df = pd.read_csv('trans.csv')\ntrans_df['date'] = pd.to_datetime(trans_df['date'])\n\nmerged_df = pd.merge(trans_df, account_df, on='account_id')\nmerged_df = pd.merge(merged_df, disp_df, on='account_id')\nmerged_df = pd.merge(merged_df, client_df, on='client_id')\n\nfiltered_df = merged_df[(merged_df['date_x'].dt.year == 1998) & (merged_df['operation'] == 'VYBER KARTOU') & (merged_df['type_y'] == 'OWNER')]\n\noutput = filtered_df[(filtered_df['amount'] 8000) & (merged['A11'] <= 9000)]\nresult = filtered[['type']].drop_duplicates()", "sql": "SELECT DISTINCT T3.type FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T2.account_id = T3.account_id LEFT JOIN loan AS T4 ON T2.account_id = T4.account_id WHERE T4.loan_id IS NULL AND T3.type != 'OWNER' AND T1.A11 > 8000 AND T1.A11 <= 9000", "difficulty": "challenging" }, { "question_id": 150, "question": "How many accounts in North Bohemia has made a transaction with the partner's bank being AB?", "db_id": "financial", "evidence": "A3 contains the region names; North Bohemia is a region.", "code": "import pandas as pd\n# Filter districts in North Bohemia\nnorth_bohemia = district[district['A3'] == 'North Bohemia']\n# Join with accounts to get accounts in North Bohemia\naccounts_north = pd.merge(north_bohemia, account, on='district_id')\n# Filter transactions with bank AB\ntrans_ab = trans[trans['bank'] == 'AB']\n# Join with accounts to get transactions in AB bank\nresult = pd.merge(accounts_north, trans_ab, on='account_id')['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE T3.bank = 'AB' AND T1.A3 = 'North Bohemia'", "difficulty": "moderate" }, { "question_id": 151, "question": "Please list the name of the districts with accounts that made withdrawal transactions.", "db_id": "financial", "evidence": "A2 refers to district name; type = 'VYDAJ' stands for withdrawal transactions", "code": "import pandas as pd\n\n# Merge district with account\nmerged = pd.merge(district, account, on='district_id')\n\n# Merge with trans\nmerged = pd.merge(merged, trans, on='account_id')\n\n# Filter for withdrawal transactions\nwithdrawals = merged[merged['type'] == 'VYDAJ']\n\n# Get distinct district names\nresult = withdrawals[['A2']].drop_duplicates()", "sql": "SELECT DISTINCT T1.A2 FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE T3.type = 'VYDAJ'", "difficulty": "moderate" }, { "question_id": 152, "question": "What is the average number of crimes committed in 1995 in regions where the number exceeds 4000 and the region has accounts that are opened starting from the year 1997?", "db_id": "financial", "evidence": "A3 refers to region names; A15 stands for the average number of crimes commited in 1995.", "code": "import pandas as pd\n\ndistrict_df = pd.read_csv('district.csv')\naccount_df = pd.read_csv('account.csv')\naccount_df['date'] = pd.to_datetime(account_df['date'])\n\nmerged_df = pd.merge(district_df, account_df, on='district_id')\n\nfiltered_df = merged_df[(merged_df['date'].dt.year >= 1997) & (merged_df['A15'] > 4000)]\n\nif filtered_df.empty:\n output = pd.DataFrame({'AVG(A15)': [None]})\noutput = pd.DataFrame({'AVG(A15)': [filtered_df['A15'].mean()]})\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 153, "question": "How many 'classic' cards are eligible for loan?", "db_id": "financial", "evidence": "type equals 'OWNER' in the database;", "code": "import pandas as pd\nmerged_cd = pd.merge(card, disp, on='disp_id')\nfiltered_cd = merged_cd[(merged_cd['type_x'] == 'classic') & (merged_cd['type_y'] == 'OWNER')]\nmerged_cda = pd.merge(filtered_cd, account, on='account_id')\nmerged_cdal = pd.merge(merged_cda, loan, on='account_id')\nfiltered_result = merged_cdal[merged_cdal['status'].isin(['A', 'C'])]\nresult = len(filtered_result)", "sql": "SELECT COUNT(T1.card_id) FROM card AS T1 INNER JOIN disp AS T2 ON T1.disp_id = T2.disp_id INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN loan AS T4 ON T3.account_id = T4.account_id WHERE T1.type = 'classic' AND T2.type = 'OWNER' AND T4.status IN ('A', 'C')", "difficulty": "simple" }, { "question_id": 154, "question": "How many male clients in 'Hl.m. Praha' district?", "db_id": "financial", "evidence": "gender equals 'M' in the database; gender = 'M' refers to male records;", "code": "import pandas as pd\nmerged = pd.merge(client, district, on='district_id')\nfiltered = merged[(merged['gender'] == 'M') & (merged['A2'] == 'Hl.m. Praha')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.client_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.gender = 'M' AND T2.A2 = 'Hl.m. Praha'", "difficulty": "simple" }, { "question_id": 155, "question": "How many percent of 'Gold' cards were issued prior to 1998?", "db_id": "financial", "evidence": "type equals 'gold' in the database; date is less than 1998 in the database; count of type = 'gold' and issued date < 1998; count of all cards;", "code": "import pandas as pd\n\n# Calculate percentage of Gold cards issued before 1998\ntotal_cards = len(card)\ngold_before_1998 = len(card[(card['type'] == 'gold') & (pd.to_datetime(card['issued']).dt.year < 1998)])\nresult = (gold_before_1998 / total_cards) * 100", "sql": "SELECT CAST(SUM(type = 'gold' AND STRFTIME('%Y', issued) < '1998') AS REAL) * 100 / COUNT(card_id) FROM card", "difficulty": "simple" }, { "question_id": 156, "question": "Who is the owner of the account with the largest loan amount?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Merge disp with account\nmerged = pd.merge(disp, account, on='account_id')\n\n# Merge with loan\nmerged = pd.merge(merged, loan, on='account_id')\n\n# Filter for OWNER type\nowners = merged[merged['type'] == 'OWNER']\n\n# Sort by loan amount descending and get the first client_id\nresult = owners.sort_values('amount', ascending=False).head(1)[['client_id']]", "sql": "SELECT T1.client_id FROM disp AS T1 INNER JOIN account AS T3 ON T1.account_id = T3.account_id INNER JOIN loan AS T2 ON T3.account_id = T2.account_id WHERE T1.type = 'OWNER' ORDER BY T2.amount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 157, "question": "What is the number of committed crimes in 1995 in the district of the account with the id 532?", "db_id": "financial", "evidence": "A15 refers to number of crimes in 1995;", "code": "import pandas as pd\n\ndistrict_df = pd.read_csv('district.csv')\naccount_df = pd.read_csv('account.csv')\naccount_df['date'] = pd.to_datetime(account_df['date'])\n\nmerged_df = pd.merge(district_df, account_df, on='district_id')\n\nfiltered_df = merged_df[(merged_df['account_id'] == 532)]\n\nif filtered_df.empty:\n output = pd.DataFrame({'A15': [None]})\noutput = pd.DataFrame({'A15': [filtered_df['A15']]})\n\nprint(output)", "sql": "", "difficulty": "simple" }, { "question_id": 158, "question": "What is the district Id of the account that placed the order with the id 33333?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Merge order and account tables\nmerged = pd.merge(order, account, on='account_id')\n\n# Filter for order_id = 33333\nfiltered = merged[merged['order_id'] == 33333]\n\n# Get the district_id\nresult = filtered['district_id'].values[0]", "sql": "SELECT T2.district_id FROM `order` AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE T1.order_id = 33333", "difficulty": "simple" }, { "question_id": 159, "question": "List all the withdrawals in cash transactions that the client with the id 3356 makes.", "db_id": "financial", "evidence": "operation equals 'VYBER' in the database;", "code": "import pandas as pd\n\n# Merge client with disp\nmerged1 = pd.merge(client[client['client_id'] == 3356], disp, on='client_id')\n\n# Merge with account\nmerged2 = pd.merge(merged1, account, on='account_id')\n\n# Merge with trans and filter for VYBER operations\nmerged3 = pd.merge(merged2, trans, on='account_id')\nresult = merged3[merged3['operation'] == 'VYBER'][['trans_id']]", "sql": "SELECT T4.trans_id FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN trans AS T4 ON T3.account_id = T4.account_id WHERE T1.client_id = 3356 AND T4.operation = 'VYBER'", "difficulty": "simple" }, { "question_id": 160, "question": "Among the weekly issuance accounts, how many have a loan of under 200000?", "db_id": "financial", "evidence": "frequency equals 'POPLATEK TYDNE' in the database;", "code": "import pandas as pd\n\n# Assume account and loan DataFrames exist\nmerged = pd.merge(loan, account, on='account_id')\nfiltered = merged[(merged['frequency'] == 'POPLATEK TYDNE') & (merged['amount'] < 200000)]\nresult = filtered['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.account_id) FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE T2.frequency = 'POPLATEK TYDNE' AND T1.amount < 200000", "difficulty": "simple" }, { "question_id": 161, "question": "What type of credit card does the client with the id 13539 own?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files\ndf_client = pd.read_csv('client.csv')\ndf_disp = pd.read_csv('disp.csv')\ndf_card = pd.read_csv('card.csv')\n\n# Filter client by id 13539\ntarget_client = df_client[df_client['client_id'] == 13539]\n\n# Merge to find the disposition\n# df_disp has a 'type' column (disposition type)\nmerged_disp = pd.merge(target_client, df_disp, on='client_id')\n\n# Merge with card table\n# df_card also has a 'type' column (card type)\n# Pandas will suffix overlapping columns: 'type_x' (from disp) and 'type_y' (from card)\nmerged_card = pd.merge(merged_disp, df_card, on='disp_id')\n\n# Extract the card type\n# SQL target is T3.type (from table card), which corresponds to 'type_y' after the merge\nresult = merged_card['type_y'].values[0]\n\nprint(result)", "sql": "SELECT T3.type FROM disp AS T1 INNER JOIN client AS T2 ON T1.client_id = T2.client_id INNER JOIN card AS T3 ON T1.disp_id = T3.disp_id WHERE T2.client_id = 13539", "difficulty": "simple" }, { "question_id": 162, "question": "What is the region of the client with the id 3541 from?", "db_id": "financial", "evidence": "A3 refers to region", "code": "import pandas as pd\n\ndistrict_df = pd.read_csv('district.csv')\nclient_df = pd.read_csv('client.csv')\nclient_df['birth_date'] = pd.to_datetime(client_df['birth_date'])\n\nmerged_df = pd.merge(district_df, client_df, on='district_id')\n\nfiltered_df = merged_df[(merged_df['client_id']) == 3541]\n\nif filtered_df.empty:\n output = pd.DataFrame({'A3': [None]})\noutput = pd.DataFrame({'A3': [filtered_df['A3']]})\n\nprint(output)", "sql": "SELECT T1.A3 FROM district AS T1 INNER JOIN client AS T2 ON T1.district_id = T2.district_id WHERE T2.client_id = 3541", "difficulty": "simple" }, { "question_id": 163, "question": "Which district has the most accounts with loan contracts finished with no problems?", "db_id": "financial", "evidence": "status equals 'A' in the database;", "code": "import pandas as pd\n\ndistrict_df = pd.read_csv('district.csv')\naccount_df = pd.read_csv('account.csv')\nloan_df = pd.read_csv('loan.csv')\n\nfiltered_df = loan_df[loan_df['status'] == 'A']\nmerged_df = pd.merge(pd.merge(filtered_df, account_df, on='account_id'), district_df, on='district_id')\ngrouped_df = merged_df.groupby('district_id').agg({'account_id': 'nunique', 'A2': 'first'}).reset_index()\noutput = grouped_df.sort_values(by='account_id', ascending=False)[['A2']].head(1)\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 164, "question": "Who placed the order with the id 32423?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter order with id 32423\norder_32423 = order[order['order_id'] == 32423]\n\n# Merge with account\nmerged = pd.merge(order_32423, account, on='account_id')\n\n# Merge with disp where type is OWNER\ndisp_owner = disp[disp['type'] == 'OWNER']\nmerged = pd.merge(merged, disp_owner, on='account_id')\n\n# Merge with client to get client_id\nmerged = pd.merge(merged, client, on='client_id')\n\n# Get the client_id\nresult = merged[['client_id']]", "sql": "SELECT T3.client_id FROM `order` AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN disp AS T4 ON T4.account_id = T2.account_id AND T4.type = 'OWNER' INNER JOIN client AS T3 ON T4.client_id = T3.client_id WHERE T1.order_id = 32423", "difficulty": "simple" }, { "question_id": 165, "question": "Please list all the transactions made by accounts from district 5.", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Merge district with account on district_id\ndistrict_account = pd.merge(district[district['district_id'] == 5], account, on='district_id')\n\n# Merge with trans on account_id\nresult = pd.merge(district_account, trans, on='account_id')[['trans_id']]", "sql": "SELECT T3.trans_id FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE T1.district_id = 5", "difficulty": "simple" }, { "question_id": 166, "question": "How many of the accounts are from Jesenik district?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(district, account, on='district_id')\nfiltered = merged[merged['A2'] == 'Jesenik']\nresult = len(filtered)", "sql": "SELECT COUNT(T2.account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id WHERE T1.A2 = 'Jesenik'", "difficulty": "simple" }, { "question_id": 167, "question": "List all the clients' IDs whose junior credit cards were issued after 1996.", "db_id": "financial", "evidence": "After 1996 means date > = '1997-01-01", "code": "import pandas as pd\n\n# Filter cards for junior type issued after 1996\njunior_cards = card[card['type'] == 'junior']\njunior_cards = junior_cards[pd.to_datetime(junior_cards['issued']) >= '1997-01-01']\n\n# Merge with disp to get client_id\nresult = pd.merge(junior_cards, disp, on='disp_id')[['client_id']]", "sql": "SELECT T2.client_id FROM card AS T1 INNER JOIN disp AS T2 ON T1.disp_id = T2.disp_id WHERE T1.type = 'junior' AND T1.issued >= '1997-01-01'", "difficulty": "simple" }, { "question_id": 168, "question": "What percentage of clients who opened their accounts in the district with an average salary of over 10000 are women?", "db_id": "financial", "evidence": "Female refers to gender = 'F'; Woman and female are closed; Average salary can be found in A11account's district_id refers to district where account was opened", "code": "import pandas as pd\n# 合并表并应用过滤条件\ndf = district.merge(account, on='district_id').merge(disp[disp['type'] == 'OWNER'], on='account_id').merge(client, on='client_id')\n# 筛选高薪地区数据\nfiltered = df[df['A11'] > 10000]\n# 计算女性占比\nfemale = filtered[filtered['gender'] == 'F']['client_id'].nunique()\ntotal = filtered['client_id'].nunique()\nresult = female / total * 100", "sql": "SELECT CAST(SUM(C.gender = 'F') AS REAL)*100/COUNT(DISTINCT C.client_id) FROM district D INNER JOIN account A ON D.district_id = A.district_id INNER JOIN disp DP ON A.account_id = DP.account_id INNER JOIN client C ON DP.client_id = C.client_id WHERE D.A11 > 10000 AND DP.type = 'OWNER'", "difficulty": "moderate" }, { "question_id": 169, "question": "What was the growth rate of the total amount of loans across all accounts for a male client between 1996 and 1997?", "db_id": "financial", "evidence": "Growth rate = (sum of amount_1997 - sum of amount_1996) / (sum of amount_1996) * 100%; Male refers to gender = 'M'", "code": "import pandas as pd\n\nloan_df = pd.read_csv('loan.csv')\nloan_df['date'] = pd.to_datetime(loan_df['date'])\naccount_df = pd.read_csv('account.csv')\naccount_df['date'] = pd.to_datetime(account_df['date'])\ndisp_df = pd.read_csv('disp.csv')\nclient_df = pd.read_csv('client.csv')\nclient_df['birth_date'] = pd.to_datetime(client_df['birth_date'])\n\nmerged_df = pd.merge(loan_df, account_df, on='account_id')\nmerged_df = pd.merge(merged_df, disp_df, on='account_id')\nmerged_df = pd.merge(merged_df, client_df, on='client_id')\n\nfiltered_df = merged_df[(merged_df['gender'] == 'M') & (merged_df['type'] == 'OWNER')]\n\namount_1996 = filtered_df[filtered_df['date_x'].dt.year == 1996]['amount'].sum()\namount_1997 = filtered_df[filtered_df['date_x'].dt.year == 1997]['amount'].sum()\nif amount_1996 == 0:\n growth_rate = None\nelse:\n growth_rate = (amount_1997 - amount_1996) / amount_1996 * 100\n\noutput = pd.DataFrame({'growth_rate': [growth_rate]})\n\nprint(output)", "sql": "", "difficulty": "challenging" }, { "question_id": 170, "question": "How many credit card withdrawals were recorded after 1995?", "db_id": "financial", "evidence": "Operation equals 'VYBER KARTOU' in the database;", "code": "import pandas as pd\nimport numpy as np\n\n# Filter transactions after 1995 with operation 'VYBER KARTOU'\nfiltered_trans = trans[(trans['date'] > '1995-12-31') & (trans['operation'] == 'VYBER KARTOU')]\n\n# Count the number of records\nresult = len(filtered_trans)", "sql": "SELECT COUNT(account_id) FROM trans WHERE STRFTIME('%Y', date) > '1995' AND operation = 'VYBER KARTOU'", "difficulty": "simple" }, { "question_id": 171, "question": "What was the difference in the number of crimes committed in East and North Bohemia in 1996?", "db_id": "financial", "evidence": "A16 refers to number of crimes in 1996;", "code": "import pandas as pd\n\ndistrict_df = pd.read_csv('district.csv')\n\neast_bohemia_crimes = district_df[district_df['A3'] == 'east Bohemia']['A16'].sum()\nnorth_bohemia_crimes = district_df[district_df['A3'] == 'north Bohemia']['A16'].sum()\n\nresult = east_bohemia_crimes - north_bohemia_crimes\noutput = pd.DataFrame({'crime_difference': [result]})\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 172, "question": "How many owner and disponent dispositions are there from account number 1 to account number 10?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nfiltered = disp[(disp['account_id'] >= 1) & (disp['account_id'] <= 10)]\nresult = pd.DataFrame({'owner_count': [(filtered['type'] == 'OWNER').sum()]})[['owner_count']].assign(disponent_count=[(filtered['type'] == 'DISPONENT').sum()])", "sql": "SELECT SUM(type = 'OWNER'), SUM(type = 'DISPONENT') FROM disp WHERE account_id BETWEEN 1 AND 10", "difficulty": "simple" }, { "question_id": 173, "question": "How often does account number 3 request an account statement to be released? What was the aim of debiting 3539 in total?", "db_id": "financial", "evidence": "k_symbol refers to the purpose of payments", "code": "import pandas as pd\n\n# Group orders by account_id and k_symbol, calculate sum of amounts\norder_grouped = order.groupby(['account_id', 'k_symbol'])['amount'].sum().reset_index()\norder_grouped.columns = ['account_id', 'k_symbol', 'total_amount']\n\n# Filter for orders with total amount of 3539\norder_filtered = order_grouped[order_grouped['total_amount'] == 3539]\n\n# Merge with account table\nmerged = pd.merge(account[account['account_id'] == 3], order_filtered, on='account_id')\n\n# Select frequency and k_symbol columns\nresult = merged[['frequency', 'k_symbol']]", "sql": "SELECT T1.frequency, T2.k_symbol FROM account AS T1 INNER JOIN (SELECT account_id, k_symbol, SUM(amount) AS total_amount FROM trans WHERE type = 'DEBIT' GROUP BY account_id, k_symbol) AS T2 ON T1.account_id = T2.account_id WHERE T1.account_id = 3 AND T2.total_amount = 3539", "difficulty": "challenging" }, { "question_id": 174, "question": "What year was account owner number 130 born?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(client, disp, on='client_id')\nmerged = pd.merge(merged, account, on='account_id')\nfiltered = merged[merged['account_id'] == 130]\nresult = pd.to_datetime(filtered['birth_date']).dt.year.iloc[0]", "sql": "SELECT STRFTIME('%Y', T1.birth_date) FROM client AS T1 INNER JOIN disp AS T3 ON T1.client_id = T3.client_id INNER JOIN account AS T2 ON T3.account_id = T2.account_id WHERE T2.account_id = 130", "difficulty": "simple" }, { "question_id": 175, "question": "How many accounts have an owner disposition and request for a statement to be generated upon a transaction?", "db_id": "financial", "evidence": "Frequency equals 'POPLATEK PO OBRATU' in the database;", "code": "import pandas as pd\n\nmerged = pd.merge(account, disp, on='account_id')\nfiltered = merged[(merged['type'] == 'OWNER') & (merged['frequency'] == 'POPLATEK PO OBRATU')]\nresult = filtered['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.account_id) FROM account AS T1 INNER JOIN disp AS T2 ON T1.account_id = T2.account_id WHERE T2.type = 'OWNER' AND T1.frequency = 'POPLATEK PO OBRATU'", "difficulty": "moderate" }, { "question_id": 176, "question": "What is the amount of debt that client number 992 has, and how is this client doing with payments?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nmerged1 = pd.merge(client[client['client_id'] == 992], disp, on='client_id')\nmerged2 = pd.merge(merged1, account, on='account_id')\nmerged3 = pd.merge(merged2, loan, on='account_id')\nresult = merged3[['amount', 'status']]", "sql": "SELECT T4.amount, T4.status FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN loan AS T4 ON T3.account_id = T4.account_id WHERE T1.client_id = 992", "difficulty": "simple" }, { "question_id": 177, "question": "What is the sum that client number 4's account has following transaction 851? Who owns this account, a man or a woman?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Merge client with disp to get account ownership\nowner_disp = disp[disp['type'] == 'OWNER']\nclient_account = pd.merge(client, owner_disp, on='client_id')\n\n# Filter for client_id = 4\nclient_4_account = client_account[client_account['client_id'] == 4]\n\n# Merge with trans to get transaction 851\nmerged = pd.merge(client_4_account, trans, on='account_id')\n\n# Filter for trans_id = 851\nresult = merged[merged['trans_id'] == 851][['balance', 'gender']]", "sql": "SELECT T4.balance, T1.gender FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id AND T2.type = 'OWNER' INNER JOIN account AS T3 ON T2.account_id = T3.account_id INNER JOIN trans AS T4 ON T3.account_id = T4.account_id WHERE T1.client_id = 4 AND T4.trans_id = 851", "difficulty": "simple" }, { "question_id": 178, "question": "Which kind of credit card does client number 9 possess?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\nclient_df = pd.read_csv('client.csv')\nclient_df['birth_date'] = pd.to_datetime(client_df['birth_date'])\ndisp_df = pd.read_csv('disp.csv')\ncard_df = pd.read_csv('card.csv')\n\nmerged_df = pd.merge(client_df, disp_df, on='client_id')\nmerged_df = pd.merge(merged_df, card_df, on='disp_id')\n\nfiltered_df = merged_df[(merged_df['client_id'] == 9)]\n\noutput = filtered_df[['type_y']]\n\nprint(output)", "sql": "", "difficulty": "simple" }, { "question_id": 179, "question": "How much, in total, did client number 617 pay for all of the transactions in 1998?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter client 617\nclient_617 = client[client['client_id'] == 617]\n\n# Get OWNER account for client 617\nowner_disp = disp[disp['type'] == 'OWNER']\nclient_disp = pd.merge(client_617, owner_disp, on='client_id')\n\n# Get account information\nclient_account = pd.merge(client_disp, account, on='account_id')\n\n# Get transactions for 1998\ntrans['year'] = pd.to_datetime(trans['date']).dt.year\ntrans_1998 = trans[trans['year'] == 1998]\n\n# Join with client's account and sum amounts\nclient_trans = pd.merge(client_account[['account_id']], trans_1998, on='account_id')\nresult = client_trans['amount'].sum()", "sql": "SELECT SUM(T3.amount) FROM client AS T1 INNER JOIN disp AS T4 ON T1.client_id = T4.client_id AND T4.type = 'OWNER' INNER JOIN account AS T2 ON T4.account_id = T2.account_id INNER JOIN trans AS T3 ON T2.account_id = T3.account_id WHERE STRFTIME('%Y', T3.date) = '1998' AND T1.client_id = 617", "difficulty": "simple" }, { "question_id": 180, "question": "Please provide a list of clients who were born between 1983 and 1987 and whose account branch is in East Bohemia, along with their IDs.", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter clients born between 1983 and 1987\nclient['birth_year'] = pd.to_datetime(client['birth_date']).dt.year\nfiltered_clients = client[(client['birth_year'] >= 1983) & (client['birth_year'] <= 1987)]\n\n# Filter districts in East Bohemia\neast_bohemia_districts = district[district['A3'] == 'east Bohemia']\n\n# Merge filtered clients with east bohemia districts\nclients_in_east_bohemia = pd.merge(filtered_clients, east_bohemia_districts[['district_id']], on='district_id')\n\n# Merge with disp to get account connections\nclients_with_disp = pd.merge(clients_in_east_bohemia[['client_id', 'district_id']], disp[['client_id', 'account_id']], on='client_id')\n\n# Merge with account to ensure account is in the same district\naccounts_in_east_bohemia = pd.merge(account[['account_id', 'district_id']], east_bohemia_districts[['district_id']], on='district_id')\n\n# Final merge to get clients whose accounts are in East Bohemia\nresult = pd.merge(clients_with_disp, accounts_in_east_bohemia, on=['account_id', 'district_id'])[['client_id', 'account_id']]", "sql": "SELECT T1.client_id, T3.account_id FROM client AS T1\nINNER JOIN disp AS T4 ON T1.client_id = T4.client_id\nINNER JOIN account AS T3 ON T4.account_id = T3.account_id\nINNER JOIN district AS T2 ON T3.district_id = T2.district_id\nWHERE T2.A3 = 'east Bohemia'\nAND STRFTIME('%Y', T1.birth_date) BETWEEN '1983' AND '1987'", "difficulty": "moderate" }, { "question_id": 181, "question": "Please provide the IDs of the 3 female clients with the largest loans.", "db_id": "financial", "evidence": "gender equals 'F' in the database; gender = 'F' refers to female records;", "code": "import pandas as pd\n\n# Merge client with disp to get account connections\nmerged = pd.merge(client[client['gender'] == 'F'], disp, on='client_id')\n\n# Merge with loan to get loan amounts\nmerged = pd.merge(merged, loan, on='account_id')\n\n# Sort by loan amount in descending order and get top 3\nresult = merged.sort_values('amount', ascending=False).head(3)[['client_id']]", "sql": "SELECT T1.client_id FROM client AS T1 INNER JOIN disp AS T4 on T1.client_id= T4.client_id INNER JOIN account AS T2 ON T4.account_id = T2.account_id INNER JOIN loan AS T3 ON T2.account_id = T3.account_id and T4.account_id = T3.account_id WHERE T1.gender = 'F' ORDER BY T3.amount DESC LIMIT 3", "difficulty": "simple" }, { "question_id": 182, "question": "How many male customers who were born between 1974 and 1976 have made a payment on their home in excess of $4000?", "db_id": "financial", "evidence": "Man and male refers to gender = 'M'; 'SIPO' stands for household payment", "code": "import pandas as pd\n# Convert date columns to datetime\ndiscounted_trans = trans[(trans['k_symbol'] == 'SIPO') & (trans['amount'] > 4000)]\nclient['birth_date'] = pd.to_datetime(client['birth_date'])\nfiltered_clients = client[(client['gender'] == 'M') & (client['birth_date'].dt.year.between(1974, 1976))]\n# Merge tables\nmerged = discounted_trans.merge(account, on='account_id')\nmerged = merged.merge(disp[disp['type'] == 'OWNER'], on='account_id')\nmerged = merged.merge(filtered_clients, on='client_id')\n# Count unique clients\nresult = pd.DataFrame({'count': [merged['client_id'].nunique()]})", "sql": "SELECT COUNT(DISTINCT T3.client_id) FROM trans AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN disp AS T4 ON T2.account_id = T4.account_id AND T4.type = 'OWNER' INNER JOIN client AS T3 ON T4.client_id = T3.client_id WHERE STRFTIME('%Y', T3.birth_date) BETWEEN '1974' AND '1976' AND T3.gender = 'M' AND T1.amount > 4000 AND T1.k_symbol = 'SIPO'", "difficulty": "moderate" }, { "question_id": 183, "question": "How many accounts in Beroun were opened after 1996?", "db_id": "financial", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(account, district, on='district_id')\nfiltered = merged[(merged['date'] > '1996-12-31') & (merged['A2'] == 'Beroun')]\nresult = filtered['account_id'].count()", "sql": "SELECT COUNT(account_id) FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.date > DATE('1996-12-31') AND T2.A2 = 'Beroun'", "difficulty": "simple" }, { "question_id": 184, "question": "How many female customers have a junior credit card?", "db_id": "financial", "evidence": "gender equals 'F' in the database; gender = 'F' refers to female records;", "code": "import pandas as pd\nmerged = pd.merge(client, disp, on='client_id')\nmerged = pd.merge(merged, card, on='disp_id')\nfiltered = merged[(merged['gender'] == 'F') & (merged['type_y'] == 'junior') & (merged['type_x'] == 'OWNER')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.client_id) FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id INNER JOIN card AS T3 ON T2.disp_id = T3.disp_id WHERE T1.gender = 'F' AND T3.type = 'junior' AND T2.type = 'OWNER'", "difficulty": "simple" }, { "question_id": 185, "question": "What proportion of customers who have accounts at the Prague branch are female?", "db_id": "financial", "evidence": "Female refers to gender = 'F'; Percentage of female clients in Prague branch = count[female clients with accounts in Prague branch / count(clients with accounts in Prague branch)] * 100%; A3 may contain information about Pragueaccount's district_id refers to the branch where the account is held; disp table connects client to account via account_id and client_id", "code": "import pandas as pd\nprague_district = district[district['A3'] == 'Prague']\nprague_accounts = pd.merge(prague_district, account, on='district_id')\nowner_disps = disp[disp['type'] == 'OWNER']\nprague_owners = pd.merge(prague_accounts, owner_disps, on='account_id')\nclients_info = pd.merge(prague_owners, client, on='client_id')\nfemale_count = clients_info['gender'].eq('F').sum()\ntotal_count = len(clients_info)\nresult = (female_count / total_count) * 100", "sql": "SELECT CAST(SUM(C.gender='F') AS REAL)/COUNT(*)*100 FROM district D JOIN account A ON D.district_id=A.district_id JOIN disp DP ON A.account_id=DP.account_id JOIN client C ON DP.client_id=C.client_id WHERE D.A3='Prague' AND DP.type='OWNER'", "difficulty": "moderate" }, { "question_id": 186, "question": "What percentage of male clients request for weekly statements to be issued?", "db_id": "financial", "evidence": "gender equals 'M' in the database; gender = 'M' refers to male records; ratio calculated by dividing statements by count; count of male clients who requested weekly statements / count(clients who requested weekly statements;POPLATEK TYDNE refers to weekly statements", "code": "import pandas as pd\nmerged = pd.merge(pd.merge(client, disp[disp['type'] == 'OWNER'], on='client_id'), account[account['frequency'] == 'POPLATEK TYDNE'], on='account_id')\nunique_clients = merged[['client_id', 'gender']].drop_duplicates()\nmale_count = unique_clients[unique_clients['gender'] == 'M'].shape[0]\ntotal_count = unique_clients.shape[0]\npercentage = (male_count / total_count) * 100\nresult = percentage", "sql": "SELECT (CAST(SUM(T1.gender = 'M') AS REAL) / COUNT(DISTINCT T1.client_id)) * 100.0 FROM client AS T1 INNER JOIN disp AS T4 ON T1.client_id = T4.client_id AND T4.type = 'OWNER' INNER JOIN account AS T2 ON T4.account_id = T2.account_id WHERE T2.frequency = 'POPLATEK TYDNE'", "difficulty": "moderate" }, { "question_id": 187, "question": "How many clients who choose statement of weekly issuance are Owner?", "db_id": "financial", "evidence": "Frequency equals 'POPLATEK TYDNE' in the database;", "code": "import pandas as pd\nmerged = pd.merge(account, disp, on='account_id')\nfiltered = merged[(merged['frequency'] == 'POPLATEK TYDNE') & (merged['type'] == 'OWNER')]\nresult = filtered['client_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.client_id) FROM account AS T1 INNER JOIN disp AS T2 ON T2.account_id = T1.account_id WHERE T1.frequency = 'POPLATEK TYDNE' AND T2.type = 'OWNER'", "difficulty": "simple" }, { "question_id": 188, "question": "Among the accounts who have loan validity more than 24 months, list out the accounts that have the lowest approved amount and have account opening date before 1997.", "db_id": "financial", "evidence": "", "code": "import pandas as pd\n\n# Filter loans with duration > 24 months\nloans_filtered = loan[loan['duration'] > 24]\n\n# Filter accounts with date before 1997\naccounts_filtered = account[pd.to_datetime(account['date']).dt.year < 1997]\n\n# Merge filtered loans with filtered accounts\nmerged = pd.merge(loans_filtered, accounts_filtered, on='account_id')\n\n# Sort by loan amount and get the account with lowest amount\nresult = merged.sort_values('amount').head(1)[['account_id']]", "sql": "SELECT T1.account_id FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id WHERE T1.duration > 24 AND STRFTIME('%Y', T2.date) < '1997' ORDER BY T1.amount ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 189, "question": "Name the account numbers of female clients who are oldest and have lowest average salary?", "db_id": "financial", "evidence": "Female refers to 'F' in the gender; A11 contains information about average salary", "code": "import pandas as pd\nfemale_clients = client[client['gender'] == 'F']\nclient_district = pd.merge(female_clients, district, on='district_id')\nowners = disp[disp['type'] == 'OWNER']\nclient_owners = pd.merge(client_district, owners, on='client_id')\nsorted_clients = client_owners.sort_values(by=['birth_date', 'A11'], ascending=[True, True])\nresult = pd.DataFrame({'account_id': [sorted_clients.iloc[0]['account_id']]})", "sql": "SELECT T3.account_id FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN account AS T3 ON T2.district_id = T3.district_id INNER JOIN disp AS T4 ON T1.client_id = T4.client_id AND T4.account_id = T3.account_id WHERE T1.gender = 'F' AND T4.type = 'OWNER' ORDER BY T1.birth_date ASC, T2.A11 ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 190, "question": "How many clients who were born in 1920 stay in east Bohemia?", "db_id": "financial", "evidence": "East Bohemia appears in the column A3, which refers to the region.", "code": "import pandas as pd\n\n# Merge client with district\nmerged = pd.merge(client, district, on='district_id')\n\n# Filter for clients born in 1920 and living in east Bohemia\nfiltered = merged[(pd.to_datetime(merged['birth_date']).dt.year == 1920) & (merged['A3'] == 'east Bohemia')]\n\n# Count the number of clients\nresult = len(filtered)", "sql": "SELECT COUNT(T1.client_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE STRFTIME('%Y', T1.birth_date) = '1920' AND T2.A3 = 'east Bohemia'", "difficulty": "simple" }, { "question_id": 191, "question": "How many loan accounts are for pre-payment of duration of 24 months with weekly issuance of statement.", "db_id": "financial", "evidence": "Frequency equals 'POPLATEK TYDNE' in the database;'POPLATEK TYDNE' refers to weekly issuance", "code": "import pandas as pd\nmerged = pd.merge(account, loan, on='account_id')\nresult = merged[(merged['duration'] == 24) & (merged['frequency'] == 'POPLATEK TYDNE')]['account_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.account_id) FROM account AS T1 INNER JOIN loan AS T2 ON T1.account_id = T2.account_id WHERE T2.duration = 24 AND T1.frequency = 'POPLATEK TYDNE'", "difficulty": "simple" }, { "question_id": 192, "question": "What is the average amount of loan which are still on running contract with statement issuance after each transaction?", "db_id": "financial", "evidence": "status equals 'C' in the database; status equals 'D' in the database;", "code": "import pandas as pd\n\n# Merge account and loan tables on account_id\nmerged = pd.merge(account, loan, on='account_id')\n\n# Filter for running contracts (status C or D) and statement issuance after each transaction\nfiltered = merged[(merged['status'].isin(['C', 'D'])) & (merged['frequency'] == 'POPLATEK PO OBRATU')]\n\n# Calculate average loan amount\nresult = filtered['amount'].mean()", "sql": "SELECT AVG(T2.amount) FROM account AS T1 INNER JOIN loan AS T2 ON T1.account_id = T2.account_id INNER JOIN trans AS T3 ON T1.account_id = T3.account_id WHERE T2.status = 'C' AND T1.frequency = 'POPLATEK PO OBRATU' AND T3.k_symbol = 'STATEMENT'", "difficulty": "moderate" }, { "question_id": 193, "question": "List all ID and district for clients that can only have the right to issue permanent orders or apply for loans.", "db_id": "financial", "evidence": "Only the owner accounts have the right to issue permanent orders or apply for loans", "code": "import pandas as pd\nmerged = pd.merge(account, disp, on='account_id')\nmerged = pd.merge(merged, district, on='district_id')\nfiltered = merged[merged['type'] == 'OWNER']\nresult = filtered[['client_id', 'district_id', 'A2']]", "sql": "SELECT T3.client_id, T2.district_id, T2.A2 FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T1.account_id = T3.account_id WHERE T3.type = 'OWNER'", "difficulty": "moderate" }, { "question_id": 194, "question": "Provide the IDs and age of the client with high level credit card, which is eligible for loans.", "db_id": "financial", "evidence": "the credit card is high-level refers to card.type = 'gold'; eligible for loans refers to disp.type = 'OWNER'", "code": "import pandas as pd\nfrom datetime import datetime\n\n# Merge disp with card on disp_id\nmerged = pd.merge(disp, card, on='disp_id')\n\n# Filter for gold cards and OWNER type\nfiltered = merged[(merged['type_y'] == 'gold') & (merged['type_x'] == 'OWNER')]\n\n# Merge with client to get birth_date\nfinal = pd.merge(filtered, client, on='client_id')\n\n# Calculate age\ncurrent_year = datetime.now().year\nfinal['age'] = current_year - pd.to_datetime(final['birth_date']).dt.year\n\n# Select client_id and age\nresult = final[['client_id', 'age']]", "sql": "SELECT T1.client_id, STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T3.birth_date) FROM disp AS T1 INNER JOIN card AS T2 ON T2.disp_id = T1.disp_id INNER JOIN client AS T3 ON T1.client_id = T3.client_id WHERE T2.type = 'gold' AND T1.type = 'OWNER'", "difficulty": "moderate" }, { "question_id": 195, "question": "What is the most common bond type?", "db_id": "toxicology", "evidence": "count of bond_type;", "code": "import pandas as pd\nbond_counts = bond.groupby('bond_type').size().reset_index(name='count')\nresult = bond_counts.nlargest(1, 'count')[['bond_type']]", "sql": "SELECT T.bond_type FROM ( SELECT bond_type, COUNT(bond_id) FROM bond GROUP BY bond_type ORDER BY COUNT(bond_id) DESC LIMIT 1 ) AS T", "difficulty": "simple" }, { "question_id": 196, "question": "In the non-carcinogenic molecules, how many contain chlorine atoms?", "db_id": "toxicology", "evidence": "non-carcinogenic molecules refers to label = '-'; chlorine atoms refers to element = 'cl'", "code": "import pandas as pd\n\nmolecule_df = pd.read_csv('molecule.csv')\natom_df = pd.read_csv('atom.csv')\n\nmerged_df = pd.merge(molecule_df, atom_df, on='molecule_id')\nfiltered_df = merged_df[(merged_df['element'] == 'cl') & (merged_df['label'] == '-')]\n\noutput = filtered_df[['molecule_id']].drop_duplicates().shape[0]\n\nprint(output)", "sql": "", "difficulty": "simple" }, { "question_id": 197, "question": "Calculate the average number of oxygen atoms in single-bonded molecules.", "db_id": "toxicology", "evidence": "single-bonded molecules refers to bond_type = '-' ; average number of oxygen atom = AVG(element = 'o')", "code": "import pandas as pd\nsingle_bonded = bond[bond['bond_type'] == '-']['molecule_id']\noxygens = atom[(atom['element'] == 'o') & (atom['molecule_id'].isin(single_bonded))]\nper_molecule = oxygens.groupby('molecule_id')['atom_id'].nunique().reset_index()\nresult = pd.DataFrame({'avg_oxygen': [per_molecule['atom_id'].mean()]})", "sql": "SELECT AVG(oxygen_count) FROM (SELECT T1.molecule_id, COUNT(DISTINCT T1.atom_id) AS oxygen_count FROM atom AS T1 WHERE T1.element = 'o' AND EXISTS (SELECT 1 FROM bond AS T2 WHERE T2.molecule_id = T1.molecule_id AND T2.bond_type = '-') GROUP BY T1.molecule_id) AS oxygen_counts", "difficulty": "moderate" }, { "question_id": 198, "question": "On average how many carcinogenic molecules are single bonded?", "db_id": "toxicology", "evidence": "carcinogenic molecules refers to label = '+'; single-bonded refers to bond_type = '-'; average = DIVIDE(SUM(bond_type = '-'), COUNT(atom_id))", "code": "import pandas as pd\n# 找到致癌分子ID\nmolecule_id_carcinogenic = molecule[molecule['label'] == '+']['molecule_id']\n# 筛选单键的致癌分子\nsingle_bonds = bond[(bond['bond_type'] == '-') & (bond['molecule_id'].isin(molecule_id_carcinogenic))]\n# 统计单键数量\nsingle_bond_count = single_bonds.shape[0]\n# 筛选致癌分子的原子\natoms_carcinogenic = atom[atom['molecule_id'].isin(molecule_id_carcinogenic)]\n# 统计原子数量\natom_count = atoms_carcinogenic.shape[0]\n# 计算平均值\nresult = single_bond_count * 1.0 / atom_count if atom_count > 0 else 0", "sql": "SELECT \n (SELECT COUNT(*) FROM bond WHERE bond_type = '-' AND molecule_id IN (SELECT molecule_id FROM molecule WHERE label = '+')) \n * 1.0 \n / \n (SELECT COUNT(*) FROM atom WHERE molecule_id IN (SELECT molecule_id FROM molecule WHERE label = '+')) \nAS avg_carcinogenic_single_bond_ratio", "difficulty": "challenging" }, { "question_id": 199, "question": "In the molecule containing sodium atoms, how many are non-carcinogenic?", "db_id": "toxicology", "evidence": "non-carcinogenic refers to label = '-'; sodium atoms refers to element = 'na'", "code": "import pandas as pd\n\natom_df = pd.read_csv('atom.csv')\nmolecule_df = pd.read_csv('molecule.csv')\n\nmerged_df = pd.merge(molecule_df, atom_df, on='molecule_id')\nfiltered_df = merged_df[(merged_df['element'] == 'na') & (merged_df['label'] == '-')]\n\noutput = filtered_df[['molecule_id']].drop_duplicates().shape[0]\n\nprint(output)", "sql": "", "difficulty": "simple" }, { "question_id": 200, "question": "Find the triple-bonded molecules which are carcinogenic.", "db_id": "toxicology", "evidence": "triple-bonded molecules refers to bond_type = '#'; carcinogenic refers to label = '+'", "code": "import pandas as pd\n\n# Merge bond and molecule tables\nmerged = pd.merge(bond, molecule, on='molecule_id')\n\n# Filter for triple bonds and carcinogenic molecules\nfiltered = merged[(merged['bond_type'] == '#') & (merged['label'] == '+')]\n\n# Get distinct molecule_ids\nresult = filtered[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT T2.molecule_id FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.bond_type = '#' AND T2.label = '+'", "difficulty": "simple" }, { "question_id": 201, "question": "What is the percentage of carbon in double-bond molecules?", "db_id": "toxicology", "evidence": "carbon refers to element = 'c'; double-bond molecules refers to bond_type = '='; percentage = DIVIDE(SUM(element = 'c'), COUNT(atom_id))", "code": "import pandas as pd\n\n# Merge atom and bond tables on molecule_id\nmerged = pd.merge(atom, bond, on='molecule_id')\n\n# Filter for double-bond molecules\ndouble_bond_molecules = merged[merged['bond_type'] == '=']\n\n# Get unique atoms in double-bond molecules\nunique_atoms = double_bond_molecules.drop_duplicates(subset=['atom_id'])\n\n# Count carbon atoms\ncarbon_count = len(unique_atoms[unique_atoms['element'] == 'c'])\n\n# Count total atoms\ntotal_count = len(unique_atoms)\n\n# Calculate percentage\nresult = (carbon_count / total_count) * 100.0", "sql": "SELECT CAST(COUNT(DISTINCT CASE WHEN T1.element = 'c' THEN T1.atom_id END) AS REAL) * 100.0 / COUNT(DISTINCT T1.atom_id) FROM atom AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.bond_type = '='", "difficulty": "moderate" }, { "question_id": 202, "question": "How many triple type bonds are there?", "db_id": "toxicology", "evidence": "bond_type equals '#' in the database;", "code": "import pandas as pd\nimport numpy as np\nresult = bond[bond['bond_type'] == '#']['bond_id'].count()", "sql": "SELECT COUNT(T.bond_id) FROM bond AS T WHERE T.bond_type = '#'", "difficulty": "simple" }, { "question_id": 203, "question": "In how many atoms is there no bromine?", "db_id": "toxicology", "evidence": "atoms with no bromine refers to element ! = 'br'", "code": "import pandas as pd\nresult = atom[atom['element'] != 'br']['atom_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T.atom_id) FROM atom AS T WHERE T.element <> 'br'", "difficulty": "simple" }, { "question_id": 204, "question": "Of the first 100 molecules in number order, how many are carcinogenic?", "db_id": "toxicology", "evidence": "first 100 molecules in number order refers to molecule_id between 'TR000' and 'TR099'; label = '+' means molecules are carcinogenic", "code": "import pandas as pd\n\n# Filter molecules with IDs between TR000 and TR099 that are carcinogenic\nfiltered_molecules = molecule[(molecule['molecule_id'] >= 'TR000') & (molecule['molecule_id'] <= 'TR099') & (molecule['label'] == '+')]\n\n# Count the number of carcinogenic molecules\nresult = len(filtered_molecules)", "sql": "SELECT COUNT(T.molecule_id) FROM molecule AS T WHERE molecule_id BETWEEN 'TR000' AND 'TR099' AND T.label = '+'", "difficulty": "simple" }, { "question_id": 205, "question": "Identify by their ID the molecules in which there is carbon.", "db_id": "toxicology", "evidence": "carbon refers to element = 'c';molecule_id in atom table refers to the molecule containing the atom; use DISTINCT to avoid duplicate molecule_ids", "code": "import pandas as pd\nresult = pd.merge(molecule, atom, on='molecule_id').query(\"element == 'c'\")[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT M.molecule_id FROM molecule AS M JOIN atom AS A ON M.molecule_id = A.molecule_id WHERE A.element = 'c';", "difficulty": "simple" }, { "question_id": 206, "question": "What elements are in the TR004_8_9 bond atoms?", "db_id": "toxicology", "evidence": "TR004_8_9 bond atoms refers to bond_id = 'TR004_8_9';", "code": "import pandas as pd\n\n# Get connections for bond TR004_8_9\ntr004_connections = connected[connected['bond_id'] == 'TR004_8_9']\n\n# Get all atom_ids from both sides of the connection\natom_ids = pd.concat([tr004_connections['atom_id'], tr004_connections['atom_id2']]).unique()\n\n# Get elements for these atoms\nresult = atom[atom['atom_id'].isin(atom_ids)][['element']].drop_duplicates()", "sql": "SELECT DISTINCT T1.element FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id IN (T2.atom_id, T2.atom_id2) WHERE T2.bond_id = 'TR004_8_9'", "difficulty": "challenging" }, { "question_id": 207, "question": "What elements are in a double type bond?", "db_id": "toxicology", "evidence": "double type bond refers to bond_type = '=';", "code": "import pandas as pd\nmerged_ab = pd.merge(atom, bond, on='molecule_id', how='inner')\nmerged_abc = pd.merge(merged_ab, connected, on='bond_id', how='inner')\nfiltered = merged_abc[merged_abc['bond_type'] == '=']\nresult = filtered[['element']].drop_duplicates()", "sql": "SELECT DISTINCT T1.element FROM atom AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN connected AS T3 ON T2.bond_id = T3.bond_id WHERE T2.bond_type = '='", "difficulty": "challenging" }, { "question_id": 208, "question": "Which type of label is the most numerous in atoms with hydrogen?", "db_id": "toxicology", "evidence": "with hydrogen refers to element = 'h'; label most numerous in atoms refers to MAX(COUNT(label)); ", "code": "import pandas as pd\n\n# 假设数据已存在\n# atom, bond, connected, molecule\n\n# 筛选含氢原子\nhydrogen_atoms = atom[atom['element'] == 'h']\n\n# 连接分子信息\nmerged = pd.merge(hydrogen_atoms, molecule, on='molecule_id')\n\n# 按标签分组计数\nlabel_counts = merged.groupby('label').size().reset_index(name='count')\n\n# 找出计数最多的标签\nresult = label_counts.loc[label_counts['count'].idxmax(), 'label']", "sql": "SELECT T.label FROM ( SELECT T2.label, COUNT(T2.molecule_id) FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'h' GROUP BY T2.label ORDER BY COUNT(T2.molecule_id) DESC LIMIT 1 ) t", "difficulty": "moderate" }, { "question_id": 209, "question": "Chlorine is in what type of bond?", "db_id": "toxicology", "evidence": "type of bond refers to bond_type; chlorine refers to element = 'cl'", "code": "import pandas as pd\n\n# Merge the three tables\nmerged = pd.merge(bond, connected, on='bond_id')\nmerged = pd.merge(merged, atom, on='atom_id')\n\n# Filter for chlorine atoms\nfiltered = merged[merged['element'] == 'cl']\n\n# Get distinct bond types\nresult = filtered[['bond_type']].drop_duplicates()", "sql": "SELECT DISTINCT T1.bond_type FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id INNER JOIN atom AS T3 ON T2.atom_id = T3.atom_id WHERE T3.element = 'cl'", "difficulty": "simple" }, { "question_id": 210, "question": "What atoms are connected in single type bonds?", "db_id": "toxicology", "evidence": "single type bond refers to bond_type = '-';", "code": "import pandas as pd\nresult = pd.merge(bond[bond['bond_type'] == '-'], connected, on='bond_id')[['atom_id', 'atom_id2']]", "sql": "SELECT T2.atom_id, T2.atom_id2 FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id WHERE T1.bond_type = '-'", "difficulty": "simple" }, { "question_id": 211, "question": "Indicate which atoms are connected in non-carcinogenic type molecules.", "db_id": "toxicology", "evidence": "label equals '-' in the database;", "code": "import pandas as pd\n\n# Merge atom with molecule to get molecule labels\natom_molecule = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for non-carcinogenic molecules (label = '-')\nnon_carcinogenic = atom_molecule[atom_molecule['label'] == '-']\n\n# Merge with connected table to get connected atoms\nconnected_atoms = pd.merge(non_carcinogenic, connected, on='atom_id')\n\n# Get distinct atom_ids that are connected in non-carcinogenic molecules\nresult = connected_atoms[['atom_id']].drop_duplicates()", "sql": "SELECT DISTINCT T1.atom_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN connected AS T3 ON T1.atom_id = T3.atom_id WHERE T2.label = '-'", "difficulty": "simple" }, { "question_id": 212, "question": "Which element is the least numerous in non-carcinogenic molecules?", "db_id": "toxicology", "evidence": "label = '-' means molecules are non-carcinogenic; least numerous refers to MIN(COUNT(element));", "code": "import pandas as pd\n\nmolecule_df = pd.read_csv('molecule.csv')\natom_df = pd.read_csv('atom.csv')\n\nfiltered_df = atom_df[atom_df['molecule_id'].isin(molecule_df[molecule_df['label'] == '-']['molecule_id'])]\n\noutput = filtered_df.groupby('element').size().reset_index(name='count').sort_values(by='count').head(1)\n\nprint(output)", "sql": "", "difficulty": "challenging" }, { "question_id": 213, "question": "What type of bond is there between the atoms TR004_8 and TR004_20?", "db_id": "toxicology", "evidence": "type of bond refers to bond_type; between the atoms TR004_8 and TR004_20 refers to atom_id = 'TR004_8' AND atom_id2 = 'TR004_20' OR another way around", "code": "import pandas as pd\n\nbond_df = pd.read_csv('bond.csv')\nconnected_df = pd.read_csv('connected.csv')\n\nmerged_df = pd.merge(bond_df, connected_df, on='bond_id')\n\nfiltered_df = merged_df[((merged_df['atom_id'] == 'TR004_8') & (merged_df['atom_id2'] == 'TR004_20')) | ((merged_df['atom_id2'] == 'TR004_8') & (merged_df['atom_id'] == 'TR004_20'))]\n\noutput = filtered_df[['bond_type']]\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 214, "question": "What type of label is not on molecules with atoms with tin?", "db_id": "toxicology", "evidence": "tin refers to element ! = 'sn'; label = '+' mean molecules are carcinogenic; label = '-' means molecules are non-carcinogenic", "code": "import pandas as pd\n\n# Get molecules that have tin atoms\nmolecules_with_tin = atom[atom['element'] == 'sn']['molecule_id'].unique()\n\n# Get molecules that don't have tin atoms\nmolecules_without_tin = molecule[~molecule['molecule_id'].isin(molecules_with_tin)]\n\n# Get distinct labels\nresult = molecules_without_tin['label'].unique()", "sql": "SELECT DISTINCT T2.label FROM molecule AS T2 WHERE NOT EXISTS (SELECT 1 FROM atom AS T1 WHERE T1.molecule_id = T2.molecule_id AND T1.element = 'sn')", "difficulty": "simple" }, { "question_id": 215, "question": "How many atoms with iodine and with sulfur type elements are there in single bond molecules?", "db_id": "toxicology", "evidence": "with iodine element refer to element = 'i'; with sulfur element refers to element = 's'; single type bond refers to bond_type = '-'; Should consider the distinct atoms when counting;", "code": "import pandas as pd\n\n# Join atom with connected\nmerged1 = pd.merge(atom, connected, on='atom_id')\n\n# Join with bond on bond_id\nmerged2 = pd.merge(merged1, bond, on='bond_id')\n\n# Filter for matching molecule_id between atom and bond\nfiltered = merged2[merged2['molecule_id_x'] == merged2['molecule_id_y']]\n\n# Filter for single bonds\nsingle_bonds = filtered[filtered['bond_type'] == '-']\n\n# Count distinct atoms by element\niodine_count = single_bonds[single_bonds['element'] == 'i']['atom_id'].nunique()\nsulfur_count = single_bonds[single_bonds['element'] == 's']['atom_id'].nunique()\n\n# Create result DataFrame\nresult = pd.DataFrame({'iodine_nums': [iodine_count], 'sulfur_nums': [sulfur_count]})", "sql": "SELECT COUNT(DISTINCT CASE WHEN T1.element = 'i' THEN T1.atom_id END) AS iodine_nums, COUNT(DISTINCT CASE WHEN T1.element = 's' THEN T1.atom_id END) AS sulfur_nums FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id INNER JOIN bond AS T3 ON T2.bond_id = T3.bond_id AND T1.molecule_id = T3.molecule_id WHERE T3.bond_type = '-'", "difficulty": "challenging" }, { "question_id": 216, "question": "Identify all connected atoms with a triple bond.", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#';", "code": "import pandas as pd\n\n# Merge bond and connected tables on bond_id\nmerged = pd.merge(bond, connected, on='bond_id')\n\n# Filter for triple bonds\ntriple_bonds = merged[merged['bond_type'] == '#']\n\n# Select only the atom_id columns\nresult = triple_bonds[['atom_id', 'atom_id2']]", "sql": "SELECT T2.atom_id, T2.atom_id2 FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id WHERE T1.bond_type = '#'", "difficulty": "simple" }, { "question_id": 217, "question": "Identify all the atoms that are connected to the atoms of the TR181 molecule.", "db_id": "toxicology", "evidence": "molecule_id equals 'TR181' in the database;", "code": "import pandas as pd\n\n# Filter atoms that belong to molecule TR181\ntr181_atoms = atom[atom['molecule_id'] == 'TR181']\n\n# Get all connections where TR181 atoms are involved\nconnections = pd.merge(tr181_atoms[['atom_id']], connected, on='atom_id')\n\n# Select only the connection columns\nresult = connections[['atom_id', 'atom_id2']]", "sql": "SELECT DISTINCT T3.atom_id AS connected_atom FROM atom AS T1 INNER JOIN connected AS T2 ON T2.atom_id = T1.atom_id INNER JOIN atom AS T3 ON T3.atom_id = T2.atom_id2 WHERE T1.molecule_id = 'TR181' UNION SELECT DISTINCT T4.atom_id AS connected_atom FROM atom AS T1 INNER JOIN connected AS T2 ON T2.atom_id2 = T1.atom_id INNER JOIN atom AS T4 ON T4.atom_id = T2.atom_id WHERE T1.molecule_id = 'TR181';", "difficulty": "simple" }, { "question_id": 218, "question": "What percentage of carcinogenic-type molecules does not contain fluorine?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; contain fluorine refers to element = 'f'; percentage = DIVIDE(SUM(element = 'f') * 100, COUNT(molecule_id)) where label = '+'; Should consider the distinct atoms when counting;molecule does not contain fluorine refers to no atom in the molecule has element = 'f'", "code": "import pandas as pd\nimport numpy as np\n# Assume all tables are already loaded as DataFrames\ncarcinogenic = molecule[molecule['label'] == '+'][['molecule_id']]\nmerged = pd.merge(carcinogenic, atom, on='molecule_id', how='left')\nhas_fluorine = merged.groupby('molecule_id')['element'].apply(lambda x: (x == 'f').any()).reset_index(name='has_fluorine')\nno_fluorine_count = (~has_fluorine['has_fluorine']).sum()\ntotal = len(has_fluorine)\nresult = (no_fluorine_count / total) * 100.0", "sql": "SELECT \n CAST(COUNT(DISTINCT CASE WHEN sub.has_fluorine = 0 THEN sub.molecule_id END) AS REAL) * 100.0 \n / COUNT(DISTINCT sub.molecule_id)\nFROM (\n SELECT \n T2.molecule_id,\n MAX(CASE WHEN T1.element = 'f' THEN 1 ELSE 0 END) AS has_fluorine\n FROM molecule AS T2\n LEFT JOIN atom AS T1 ON T2.molecule_id = T1.molecule_id\n WHERE T2.label = '+'\n GROUP BY T2.molecule_id\n) AS sub", "difficulty": "challenging" }, { "question_id": 219, "question": "What is the percentage of carcinogenic molecules in triple type bonds?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; triple bond refers to bond_type = '#'; percentage = DIVIDE(SUM(bond_type = '#') * 100, COUNT(bond_id)) as percent where label = '+'percentage = CAST(COUNT(DISTINCT CASE WHEN label = '+' THEN molecule_id END) AS REAL) * 100 / COUNT(DISTINCT molecule_id) WHERE bond_type = '#'", "code": "import pandas as pd\nmerged = pd.merge(molecule, bond, on='molecule_id', how='inner')\nfiltered = merged[merged['bond_type'] == '#']\nplus_count = filtered[filtered['label'] == '+']['molecule_id'].nunique()\ntotal_count = filtered['molecule_id'].nunique()\nresult = (plus_count / total_count) * 100", "sql": "SELECT CAST(COUNT(DISTINCT CASE WHEN T1.label = '+' THEN T1.molecule_id END) AS REAL)*100/COUNT(DISTINCT T1.molecule_id) FROM molecule AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.bond_type = '#'", "difficulty": "challenging" }, { "question_id": 220, "question": "Please list top three elements of the toxicology of the molecule TR000 in alphabetical order.", "db_id": "toxicology", "evidence": "TR000 is the molecule id;", "code": "import pandas as pd\nresult = atom[atom['molecule_id'] == 'TR000']['element'].drop_duplicates().sort_values().head(3)", "sql": "SELECT DISTINCT T.element FROM atom AS T WHERE T.molecule_id = 'TR000' ORDER BY T.element LIMIT 3", "difficulty": "challenging" }, { "question_id": 221, "question": "What are the atoms that are bonded in the molecule TR001 with the bond ID of TR001_2_6?", "db_id": "toxicology", "evidence": "TR001 is the molecule id; TR001_2_6 is the bond id", "code": "import pandas as pd\nvalid_bond = bond[(bond['molecule_id'] == 'TR001') & (bond['bond_id'] == 'TR001_2_6')]['bond_id']\nresult = connected[connected['bond_id'].isin(valid_bond)][['atom_id', 'atom_id2']]", "sql": "SELECT c.atom_id, c.atom_id2 FROM connected c JOIN bond b ON c.bond_id = b.bond_id WHERE b.molecule_id = 'TR001' AND c.bond_id = 'TR001_2_6'", "difficulty": "simple" }, { "question_id": 222, "question": "What is the difference between the number of molecules that are carcinogenic and those that are not?", "db_id": "toxicology", "evidence": "label equals '+' in the database; label equals '-' in the database; sum of label = '+'; sum of label = '-';", "code": "import pandas as pd\n\nmolecule_df = pd.read_csv('molecule.csv')\n\nresult = molecule_df[molecule_df['label'] == '+'].shape[0] - molecule_df[molecule_df['label'] == '-'].shape[0]\n\noutput = pd.DataFrame({'diff_car_notcar': [result]})\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 223, "question": "What are the atom IDs of the bond TR000_2_5?", "db_id": "toxicology", "evidence": "TR000_2_5 is the bond id", "code": "import pandas as pd\nresult = connected[connected['bond_id'] == 'TR000_2_5'][['atom_id', 'atom_id2']].values.flatten()", "sql": "SELECT T.atom_id FROM connected AS T WHERE T.bond_id = 'TR000_2_5'", "difficulty": "simple" }, { "question_id": 224, "question": "What are the bond IDs that have the same atom ID 2 of TR000_2?", "db_id": "toxicology", "evidence": "TR000_2 is the atom id; atom ID 2 refers to atom_id2", "code": "import pandas as pd\nresult = connected[connected['atom_id2'] == 'TR000_2']['bond_id']", "sql": "SELECT T.bond_id FROM connected AS T WHERE T.atom_id2 = 'TR000_2'", "difficulty": "simple" }, { "question_id": 225, "question": "Please list top five molecules that have double bonds in alphabetical order.", "db_id": "toxicology", "evidence": "double bond refers to bond_type = ' = ';", "code": "import pandas as pd\nresult = bond[bond['bond_type'] == '=']['molecule_id'].drop_duplicates().sort_values().head(5)", "sql": "SELECT DISTINCT T.molecule_id FROM bond AS T WHERE T.bond_type = '=' ORDER BY T.molecule_id LIMIT 5", "difficulty": "simple" }, { "question_id": 226, "question": "What is the percentage of double bonds in the molecule TR008? Please provide your answer as a percentage with five decimal places.", "db_id": "toxicology", "evidence": "double bond refers to bond_type = '='; TR008 is the molecule id; percentage = DIVIDE(SUM(bond_type = '='), COUNT(bond_id)) as percent where molecule_id = 'TR008'", "code": "import pandas as pd\n\n# Filter bonds for molecule TR008\ntr008_bonds = bond[bond['molecule_id'] == 'TR008']\n\n# Count double bonds (bond_type = '=')\ndouble_bonds_count = len(tr008_bonds[tr008_bonds['bond_type'] == '='])\n\n# Count total bonds\ntotal_bonds_count = len(tr008_bonds)\n\n# Calculate percentage with 5 decimal places\npercentage = round((double_bonds_count / total_bonds_count) * 100, 5)\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT ROUND(CAST(COUNT(CASE WHEN T.bond_type = '=' THEN T.bond_id ELSE NULL END) AS REAL) * 100 / COUNT(T.bond_id),5) FROM bond AS T WHERE T.molecule_id = 'TR008'", "difficulty": "moderate" }, { "question_id": 227, "question": "What is the percentage of molecules that are carcinogenic? Please provide your answer as a percentage with three decimal places.", "db_id": "toxicology", "evidence": "label equals '+' in the database; count of molecule_id; sum of label = '+';", "code": "import pandas as pd\n\ncarcinogenic_count = molecule[molecule['label'] == '+'].shape[0]\ntotal_count = molecule.shape[0]\npercentage = round((carcinogenic_count / total_count) * 100, 3)\nresult = percentage", "sql": "SELECT ROUND(CAST(COUNT(CASE WHEN T.label = '+' THEN T.molecule_id ELSE NULL END) AS REAL) * 100 / COUNT(T.molecule_id),3) FROM molecule t", "difficulty": "simple" }, { "question_id": 228, "question": "How much of the hydrogen in molecule TR206 is accounted for? Please provide your answer as a percentage with four decimal places.", "db_id": "toxicology", "evidence": "hydrogen refers to element = 'h'; TR206 is the molecule id; percentage = DIVIDE(SUM(element = 'h'), COUNT(atom_id)) as percent where molecule_id = 'TR206'", "code": "import pandas as pd\nfiltered_atoms = atom[atom['molecule_id'] == 'TR206']\nhydrogen_count = (filtered_atoms['element'] == 'h').sum()\ntotal_count = len(filtered_atoms)\npercentage = round((hydrogen_count / total_count) * 100, 4)\nresult = percentage", "sql": "SELECT ROUND(CAST(COUNT(CASE WHEN T.element = 'h' THEN T.atom_id ELSE NULL END) AS REAL) * 100 / COUNT(T.atom_id),4) FROM atom AS T WHERE T.molecule_id = 'TR206'", "difficulty": "moderate" }, { "question_id": 229, "question": "What is the type of bond that molecule TR000 has when involved in any bonds?", "db_id": "toxicology", "evidence": "type of bond refers to bond_type; TR000 is the molecule id", "code": "import pandas as pd\nresult = bond[bond['molecule_id'] == 'TR000']['bond_type'].drop_duplicates()", "sql": "SELECT DISTINCT T.bond_type FROM bond AS T WHERE T.molecule_id = 'TR000'", "difficulty": "simple" }, { "question_id": 230, "question": "What are the elements of the toxicology and label of molecule TR060?", "db_id": "toxicology", "evidence": "TR060 is the molecule id;", "code": "import pandas as pd\n\n# Assume DataFrames exist as atom, molecule\nfiltered_molecule = molecule[molecule['molecule_id'] == 'TR060']\nmerged = pd.merge(atom, filtered_molecule, on='molecule_id')\nresult = merged[['element', 'label']].drop_duplicates()", "sql": "SELECT DISTINCT T1.element, T2.label FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.molecule_id = 'TR060'", "difficulty": "challenging" }, { "question_id": 231, "question": "Which bond type accounted for the majority of the bonds found in molecule TR010 and state whether or not this molecule is carcinogenic?", "db_id": "toxicology", "evidence": "TR010 is the molecule id; majority of the bond found refers to MAX(COUNT(bond_type)); ", "code": "import pandas as pd\n# Find majority bond type in TR010\ntr_bonds = bond[bond['molecule_id'] == 'TR010']\nbond_counts = tr_bonds.groupby('bond_type').size()\nmajority_bond = bond_counts.idxmax()\n# Get carcinogenic status\ncarcinogenic = molecule[molecule['molecule_id'] == 'TR010']['label'].iloc[0]\n# Create result DataFrame\nresult = pd.DataFrame([{'bond_type': majority_bond, 'carcinogenic_status': carcinogenic}])", "sql": "SELECT T.bond_type, (SELECT label FROM molecule WHERE molecule_id = 'TR010') AS carcinogenic_status\nFROM (\n SELECT T1.bond_type, COUNT(*) AS cnt\n FROM bond AS T1\n WHERE T1.molecule_id = 'TR010'\n GROUP BY T1.bond_type\n ORDER BY cnt DESC\n LIMIT 1\n) AS T", "difficulty": "challenging" }, { "question_id": 232, "question": "Please list top three molecules that have single bonds between two atoms and are not carcinogenic in alphabetical order.", "db_id": "toxicology", "evidence": "label = '-' means molecules are not carcinogenic; single type bond refers to bond_type = '-'; list top three molecules refers to return molecule_id and order by molecule_id;", "code": "import pandas as pd\n\nbond_df = pd.read_csv('bond.csv')\nmolecule_df = pd.read_csv('molecule.csv')\n\nmerged_df = pd.merge(bond_df, molecule_df, on='molecule_id')\nfiltered_df = merged_df[(merged_df['bond_type'] == '-') & (merged_df['label'] == '-')]\n\noutput = filtered_df[['molecule_id']].drop_duplicates().sort_values(by='molecule_id').head(3).reset_index(drop=True)\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 233, "question": "Please list top two bonds that happened with the molecule TR006 in alphabetical order.", "db_id": "toxicology", "evidence": "TR006 is the molecule id", "code": "import pandas as pd\nresult = bond[bond['molecule_id'] == 'TR006']['bond_id'].drop_duplicates().sort_values().head(2)", "sql": "SELECT DISTINCT bond.bond_id FROM bond WHERE bond.molecule_id = 'TR006' ORDER BY bond.bond_id LIMIT 2", "difficulty": "simple" }, { "question_id": 234, "question": "How many bonds which involved atom 12 does molecule TR009 have?", "db_id": "toxicology", "evidence": "TR009 is the molecule id; involved atom 12 refers to atom_id = 'TR009_12' or atom_id2 = 'TR009_12'", "code": "import pandas as pd\nbond_molecule = bond[bond['molecule_id'] == 'TR009']\nconnected_atom = connected[(connected['atom_id'] == 'TR009_12') | (connected['atom_id2'] == 'TR009_12')]\nmerged = pd.merge(bond_molecule, connected_atom, on='bond_id')\nresult = merged['bond_id'].count()", "sql": "SELECT COUNT(T2.bond_id) FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id WHERE T1.molecule_id = 'TR009' AND (T2.atom_id = 'TR009_12' OR T2.atom_id2 = 'TR009_12')", "difficulty": "moderate" }, { "question_id": 235, "question": "How many molecules are carcinogenic and have the bromine element?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; have bromine element refers to element = 'br'", "code": "import pandas as pd\nimport numpy as np\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for carcinogenic molecules (label = '+') and bromine element (element = 'br')\nfiltered = merged[(merged['label'] == '+') & (merged['element'] == 'br')]\n\n# Count distinct molecules\nresult = filtered['molecule_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.molecule_id) FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+' AND T1.element = 'br'", "difficulty": "simple" }, { "question_id": 236, "question": "What are the bond type and the atoms of the bond ID of TR001_6_9?", "db_id": "toxicology", "evidence": "atoms refer to atom_id or atom_id2", "code": "import pandas as pd\n\nbond_df = pd.read_csv('bond.csv')\nconnected_df = pd.read_csv('connected.csv')\n\nmerged_df = pd.merge(bond_df, connected_df, on='bond_id')\n\nfiltered_df = merged_df[merged_df['bond_id'] == 'TR001_6_9']\n\noutput = filtered_df[['bond_type', 'atom_id', 'atom_id2']].reset_index(drop=True)\n\nprint(output)", "sql": "", "difficulty": "moderate" }, { "question_id": 237, "question": "Which molecule does the atom TR001_10 belong to? Please state whether this molecule is carcinogenic or not.", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\n\n# Assuming DataFrames are already loaded\n# atom, molecule, bond, connected\n\n# Filter atom table for TR001_10\natom_filtered = atom[atom['atom_id'] == 'TR001_10']\n\n# Join with molecule table\nresult = pd.merge(atom_filtered, molecule, on='molecule_id')\n\n# Add carcinogenic flag\nresult['flag_carcinogenic'] = result['label'].apply(lambda x: 'YES' if x == '+' else 'NO')\n\n# Select only molecule_id and flag_carcinogenic columns\nresult = result[['molecule_id', 'flag_carcinogenic']]", "sql": "SELECT T2.molecule_id, IIF(T2.label = '+', 'YES', 'NO') AS flag_carcinogenic FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.atom_id = 'TR001_10'", "difficulty": "moderate" }, { "question_id": 238, "question": "How many molecules have a triple bond type?", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#';", "code": "import pandas as pd\nresult = bond[bond['bond_type'] == '#']['molecule_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T.molecule_id) FROM bond AS T WHERE T.bond_type = '#'", "difficulty": "simple" }, { "question_id": 239, "question": "How many connections does the atom 19 have?", "db_id": "toxicology", "evidence": "connections refers to bond_id; atom 19 refers to atom_id like 'TR%_19';", "code": "import pandas as pd\nresult = connected[connected['atom_id'].str.endswith('_19')]['bond_id'].count()", "sql": "SELECT COUNT(DISTINCT bond_id) FROM connected WHERE atom_id LIKE 'TR%_19' OR atom_id2 LIKE 'TR%_19'", "difficulty": "simple" }, { "question_id": 240, "question": "List all the elements of the toxicology of the molecule \"TR004\".", "db_id": "toxicology", "evidence": "TR004 is the molecule id;", "code": "import pandas as pd\nresult = atom[atom['molecule_id'] == 'TR004']['element'].drop_duplicates()", "sql": "SELECT DISTINCT element FROM atom WHERE molecule_id = 'TR004'", "difficulty": "challenging" }, { "question_id": 241, "question": "How many of the molecules are not carcinogenic?", "db_id": "toxicology", "evidence": "label equals '-' in the database;", "code": "import pandas as pd\n\nresult = len(molecule[molecule['label'] == '-'])", "sql": "SELECT COUNT(T.molecule_id) FROM molecule AS T WHERE T.label = '-'", "difficulty": "simple" }, { "question_id": 242, "question": "Among all the atoms from 21 to 25, list all the molecules that are carcinogenic.", "db_id": "toxicology", "evidence": "atoms from 21 to 25 refers to SUBSTR(atom_id, 7, 2) between '21' and '25'; label = '+' mean molecules are carcinogenic", "code": "import pandas as pd\n\n# Filter atoms with IDs ending in 21-25\natom_filtered = atom[atom['atom_id'].str[-2:].between('21', '25')]\n\n# Merge with molecule table\nmerged = pd.merge(atom_filtered, molecule, on='molecule_id')\n\n# Filter carcinogenic molecules (label = '+')\ncarcinogenic = merged[merged['label'] == '+']\n\n# Get distinct molecule IDs\nresult = carcinogenic[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT T2.molecule_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE SUBSTR(T1.atom_id, -2) BETWEEN '21' AND '25' AND T2.label = '+'", "difficulty": "moderate" }, { "question_id": 243, "question": "What are the bonds that have phosphorus and nitrogen as their atom elements?", "db_id": "toxicology", "evidence": "have phosphorus as atom elements refers to element = 'p'; have nitrogen as atom elements refers to element = 'n'", "code": "import pandas as pd\nmerged1 = pd.merge(connected, atom[['atom_id', 'element']], on='atom_id', how='inner')\nmerged2 = pd.merge(merged1, atom[['atom_id', 'element']].rename(columns={'element':'element2'}), left_on='atom_id2', right_on='atom_id', how='inner')\nfiltered = merged2[(merged2['element'] == 'p') & (merged2['element2'] == 'n') | (merged2['element'] == 'n') & (merged2['element2'] == 'p')]\nresult = filtered['bond_id'].drop_duplicates()", "sql": "SELECT DISTINCT T2.bond_id FROM connected AS T2 INNER JOIN atom AS T1 ON T2.atom_id = T1.atom_id INNER JOIN atom AS T3 ON T2.atom_id2 = T3.atom_id WHERE (T1.element = 'p' AND T3.element = 'n') OR (T1.element = 'n' AND T3.element = 'p')", "difficulty": "moderate" }, { "question_id": 244, "question": "Is the molecule with the most double bonds carcinogenic?", "db_id": "toxicology", "evidence": "double bond refers to bond_type = ' = '; label = '+' mean molecules are carcinogenic", "code": "import pandas as pd\nmost_double_mol = bond[bond['bond_type'] == '\\x3d'].groupby('molecule_id').size().idxmax()\nlabel = molecule[molecule['molecule_id'] == most_double_mol]['label'].iloc[0]\nresult = pd.DataFrame({'is_carcinogenic': ['Yes' if label == '+' else 'No']})", "sql": "SELECT CASE WHEN T1.label = '+' THEN 'Yes' ELSE 'No' END AS is_carcinogenic FROM molecule AS T1 INNER JOIN ( SELECT T.molecule_id, COUNT(T.bond_type) AS double_bond_count FROM bond AS T WHERE T.bond_type = '=' GROUP BY T.molecule_id ORDER BY COUNT(T.bond_type) DESC LIMIT 1 ) AS T2 ON T1.molecule_id = T2.molecule_id;", "difficulty": "moderate" }, { "question_id": 245, "question": "What is the average number of bonds the atoms with the element iodine have?", "db_id": "toxicology", "evidence": "atoms with the element iodine refers to element = 'i'; average = DIVIDE(COUND(bond_id), COUNT(atom_id)) where element = 'i'", "code": "import pandas as pd\niodine = atom[atom['element'] == 'i']\nmask = connected['atom_id'].isin(iodine.atom_id) | connected['atom_id2'].isin(iodine.atom_id)\nbond_count = connected[mask].shape[0]\natom_count = iodine.shape[0]\naverage = bond_count / atom_count\nresult = pd.DataFrame({'average': [average]})", "sql": "SELECT CAST(COUNT(T2.bond_id) AS REAL) / COUNT(DISTINCT T1.atom_id) FROM atom AS T1 LEFT JOIN connected AS T2 ON T1.atom_id = T2.atom_id OR T1.atom_id = T2.atom_id2 WHERE T1.element = 'i'", "difficulty": "moderate" }, { "question_id": 246, "question": "List the bond type and the bond ID of the atom 45.", "db_id": "toxicology", "evidence": "bond ID of atom 45 refers to SUBSTR(atom_id, 7, 2) + 0 = 45; double bond refers to bond_type = ' = '; single bond refers to bond_type = '-'; triple bond refers to bond_type = '#';bond ID of atom 45 refers to SUBSTR(atom_id, 7, 2) = '45'; bond ID of atom 45 also refers to SUBSTR(atom_id2, 7, 2) = '45'", "code": "import pandas as pd\nbond_ids = connected[(connected['atom_id'].str[6:8] == '45') | (connected['atom_id2'].str[6:8] == '45')]['bond_id']\nresult = bond[bond['bond_id'].isin(bond_ids)].assign(bond_type=lambda x: x['bond_type'].map({' = ': 'double bond', '-': 'single bond', '#': 'triple bond'}).fillna('unknown'))[['bond_type', 'bond_id']]", "sql": "SELECT CASE T1.bond_type WHEN ' = ' THEN 'double bond' WHEN '-' THEN 'single bond' WHEN '#' THEN 'triple bond' ELSE 'unknown' END AS bond_type, T1.bond_id FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id WHERE CAST(SUBSTR(T2.atom_id, 7, 2) AS INTEGER) = 45", "difficulty": "moderate" }, { "question_id": 247, "question": "List all the elements of atoms that can not bond with any other atoms.", "db_id": "toxicology", "evidence": "atoms cannot bond with other atoms means atom_id NOT in connected table;atoms cannot bond with other atoms means atom_id NOT IN (connected.atom_id OR connected.atom_id2)", "code": "import pandas as pd\nconnected_atom_ids = pd.concat([connected['atom_id'], connected['atom_id2']]).unique()\nunbonded_atoms = atom[~atom['atom_id'].isin(connected_atom_ids)]\nresult = unbonded_atoms[['element']].drop_duplicates()", "sql": "SELECT DISTINCT T.element FROM atom AS T WHERE T.atom_id NOT IN ( SELECT T2.atom_id FROM connected AS T2 UNION SELECT T2.atom_id2 FROM connected AS T2 )", "difficulty": "challenging" }, { "question_id": 248, "question": "What are the atoms of the triple bond with the molecule \"TR041\"?", "db_id": "toxicology", "evidence": "TR041 is the molecule id; triple bond refers to bond_type = '#';", "code": "import pandas as pd\n\nconnected_df = pd.read_csv('connected.csv')\natom_df = pd.read_csv('atom.csv')\nbond_df = pd.read_csv('bond.csv')\n\nmerged_df = pd.merge(connected_df, bond_df, on='bond_id')\nmerged_df = pd.merge(merged_df, atom_df, on='atom_id')\nmerged_df = pd.merge(merged_df, atom_df, left_on='atom_id2', right_on='atom_id', how='inner')\n\nfiltered_df = merged_df[(merged_df['bond_type'] == '#') & (merged_df['molecule_id'] == 'TR041') & (merged_df['molecule_id_x'] == 'TR041') & (merged_df['molecule_id_y'] == 'TR041')]\\n\\noutput = filtered_df[['atom_id_x','atom_id2']]\\n\\nprint(output)", "sql": "", "difficulty": "simple" }, { "question_id": 249, "question": "What are the elements of the atoms of TR144_8_19?", "db_id": "toxicology", "evidence": "TR144_8_19 is the bond id;", "code": "import pandas as pd\n\n# Get atoms connected by bond TR144_8_19\nfiltered_connections = connected[connected['bond_id'] == 'TR144_8_19']\n\n# Get elements from atom_id\natoms1 = pd.merge(filtered_connections[['atom_id']], atom, on='atom_id')[['element']]\n\n# Get elements from atom_id2\natoms2 = pd.merge(filtered_connections[['atom_id2']], atom, left_on='atom_id2', right_on='atom_id')[['element']]\n\n# Union the results\nresult = pd.concat([atoms1, atoms2]).drop_duplicates().reset_index(drop=True)", "sql": "SELECT T2.element FROM connected AS T1 INNER JOIN atom AS T2 ON T1.atom_id = T2.atom_id WHERE T1.bond_id = 'TR144_8_19' UNION SELECT T3.element FROM connected AS T1 INNER JOIN atom AS T3 ON T1.atom_id2 = T3.atom_id WHERE T1.bond_id = 'TR144_8_19'", "difficulty": "challenging" }, { "question_id": 250, "question": "Of all the carcinogenic molecules, which one has the most double bonds?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; double bond refers to bond_type = ' = ';", "code": "import pandas as pd\nmerged = pd.merge(bond, molecule, on='molecule_id')\nfiltered = merged[(merged['label'] == '+') & (merged['bond_type'] == '=')]\nbond_counts = filtered.groupby('molecule_id').size().reset_index(name='double_bond_count')\nmax_count = bond_counts['double_bond_count'].max()\nresult = bond_counts[bond_counts['double_bond_count'] == max_count]['molecule_id']", "sql": "SELECT T3.molecule_id FROM bond AS T1 INNER JOIN molecule AS T3 ON T1.molecule_id = T3.molecule_id WHERE T3.label = '+' AND T1.bond_type = '=' GROUP BY T3.molecule_id HAVING COUNT(T1.bond_type) = (SELECT MAX(double_bond_count) FROM (SELECT COUNT(T1.bond_type) AS double_bond_count FROM bond AS T1 INNER JOIN molecule AS T3 ON T1.molecule_id = T3.molecule_id WHERE T3.label = '+' AND T1.bond_type = '=' GROUP BY T3.molecule_id))", "difficulty": "moderate" }, { "question_id": 251, "question": "What is the least common element of all carcinogenic molecules?", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\n# 筛选致癌分子\nvalid_mols = molecule[molecule['label'] == '+']['molecule_id']\n# 过滤原子表\nfiltered = atom[atom['molecule_id'].isin(valid_mols)]\n# 统计元素分布\nelement_counts = filtered.groupby('element')['molecule_id'].nunique().reset_index()\n# 找最小值并筛选\nmin_count = element_counts['molecule_id'].min()\nresult = element_counts[element_counts['molecule_id'] == min_count]['element']", "sql": "SELECT T2.element FROM molecule AS T1 INNER JOIN atom AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.label = '+' GROUP BY T2.element HAVING COUNT(DISTINCT T2.molecule_id) = (SELECT MIN(cnt) FROM (SELECT COUNT(DISTINCT T2.molecule_id) AS cnt FROM molecule AS T1 INNER JOIN atom AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.label = '+' GROUP BY T2.element))", "difficulty": "moderate" }, { "question_id": 252, "question": "What are the atoms that can bond with the atom that has the element lead?", "db_id": "toxicology", "evidence": "element equals 'pb' in the database;", "code": "import pandas as pd\n\n# Filter atoms with element 'pb' (lead)\nlead_atoms = atom[atom['element'] == 'pb']\n\n# Join with connected table to find atoms that can bond with lead atoms\nresult = pd.merge(lead_atoms[['atom_id']], connected, on='atom_id')[['atom_id', 'atom_id2']]", "sql": "SELECT DISTINCT\n CASE WHEN T1.element = 'pb' THEN T2.atom_id2\n WHEN T3.element = 'pb' THEN T2.atom_id\n END AS bonded_atom\nFROM connected AS T2\nLEFT JOIN atom AS T1 ON T2.atom_id = T1.atom_id\nLEFT JOIN atom AS T3 ON T2.atom_id2 = T3.atom_id\nWHERE (T1.element = 'pb' OR T3.element = 'pb')", "difficulty": "simple" }, { "question_id": 253, "question": "List the elements of all the triple bonds.", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#';", "code": "import pandas as pd\n\n# Merge bond with connected on bond_id\nmerged = pd.merge(bond[bond['bond_type'] == '#'], connected, on='bond_id')\n\n# Merge with atom table to get elements\nresult = pd.merge(merged, atom, on='atom_id')[['element']].drop_duplicates()\n\nresult = result", "sql": "SELECT DISTINCT T3.element FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id INNER JOIN atom AS T3 ON T2.atom_id = T3.atom_id WHERE T1.bond_type = '#'", "difficulty": "challenging" }, { "question_id": 254, "question": "What percentage of bonds have the most common combination of atoms' elements?", "db_id": "toxicology", "evidence": "count of bond_id; count of atom_id where MAX(COUNT(atom_id;combination of elements refers to elements from atom_id and atom_id2 in connected table", "code": "import pandas as pd\nmerged = connected.merge(atom[['atom_id', 'element']], on='atom_id', how='inner').rename(columns={'element': 'element1'})\nmerged = merged.merge(atom[['atom_id', 'element']], left_on='atom_id2', right_on='atom_id', how='inner').rename(columns={'element': 'element2'})\nmerged['element_combo'] = merged['element1'] + '-' + merged['element2']\npair_counts = merged.groupby('element_combo')['bond_id'].nunique()\npercentage = (pair_counts.max() / bond.shape[0]) * 100.0\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "WITH element_pairs AS ( SELECT c.bond_id, a1.element || '-' || a2.element AS element_combo FROM connected AS c JOIN atom AS a1 ON c.atom_id = a1.atom_id JOIN atom AS a2 ON c.atom_id2 = a2.atom_id ), pair_counts AS ( SELECT element_combo, COUNT(DISTINCT bond_id) AS combo_count FROM element_pairs GROUP BY element_combo ) SELECT (MAX(combo_count) * 100.0 / (SELECT COUNT(*) FROM bond)) AS percentage FROM pair_counts;", "difficulty": "moderate" }, { "question_id": 255, "question": "What proportion of single bonds are carcinogenic? Please provide your answer as a percentage with five decimal places.", "db_id": "toxicology", "evidence": "single bond refers to bond_type = '-'; label = '+' mean molecules are carcinogenic; proportion = DIVIDE(SUM(label = '+') * 100, COUNT(bond_id)) where bond_type = '-'", "code": "import pandas as pd\n\n# Merge bond and molecule tables\nmerged = pd.merge(bond, molecule, on='molecule_id')\n\n# Filter for single bonds (bond_type = '-')\nsingle_bonds = merged[merged['bond_type'] == '-']\n\n# Count carcinogenic single bonds (label = '+')\ncarcinogenic_count = single_bonds[single_bonds['label'] == '+'].shape[0]\n\n# Count total single bonds\ntotal_count = single_bonds.shape[0]\n\n# Calculate proportion as percentage with 5 decimal places\nproportion = (carcinogenic_count / total_count) * 100\nresult = round(proportion, 5)", "sql": "SELECT ROUND(CAST(COUNT(CASE WHEN T2.label = '+' THEN T1.bond_id ELSE NULL END) AS REAL) * 100 / COUNT(T1.bond_id),5) FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.bond_type = '-'", "difficulty": "moderate" }, { "question_id": 256, "question": "Calculate the total atoms consisting of the element carbon and hydrogen.", "db_id": "toxicology", "evidence": "consisting of element carbon and hydrogen refers to element in('c', 'h')", "code": "import pandas as pd\nresult = atom[atom['element'].isin(['c', 'h'])].shape[0]", "sql": "SELECT COUNT(T.atom_id) FROM atom AS T WHERE T.element = 'c' OR T.element = 'h'", "difficulty": "simple" }, { "question_id": 257, "question": "List down atom id2 for atoms with element sulfur.", "db_id": "toxicology", "evidence": "element equals 's' in the database;", "code": "import pandas as pd\nfiltered_atoms = atom[atom['element'] == 's']\nmerged = pd.merge(filtered_atoms, connected, on='atom_id')\nresult = merged[['atom_id2']].drop_duplicates()", "sql": "SELECT DISTINCT T2.atom_id2 FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id WHERE T1.element = 's'", "difficulty": "simple" }, { "question_id": 258, "question": "What are the bond type for atoms with element Tin?", "db_id": "toxicology", "evidence": "element Tin refers to element = 'sn'; double bond refers to bond_type = ' = '; single bond refers to bond_type = '-'; triple bond refers to bond_type = '#'", "code": "import pandas as pd\n\n# Merge connected with atom table for atom_id\nmerged1 = pd.merge(connected, atom[['atom_id', 'element']], on='atom_id')\n\n# Merge connected with atom table for atom_id2\nmerged2 = pd.merge(connected, atom[['atom_id', 'element']], left_on='atom_id2', right_on='atom_id')\n\n# Filter for Tin element (sn) from both sides\ntin_bonds = pd.concat([\n merged1[merged1['element'] == 'sn']['bond_id'],\n merged2[merged2['element'] == 'sn']['bond_id']\n]).drop_duplicates()\n\n# Get bond types for these bonds\nresult = bond[bond['bond_id'].isin(tin_bonds)]['bond_type'].drop_duplicates().reset_index(drop=True)", "sql": "SELECT DISTINCT T3.bond_type FROM connected AS T2 INNER JOIN atom AS T1 ON T1.atom_id = T2.atom_id INNER JOIN atom AS T4 ON T4.atom_id = T2.atom_id2 INNER JOIN bond AS T3 ON T3.bond_id = T2.bond_id WHERE T1.element = 'sn' OR T4.element = 'sn'", "difficulty": "moderate" }, { "question_id": 259, "question": "How many elements are there for single bond molecules?", "db_id": "toxicology", "evidence": "single bond refers to bond_type = '-';", "code": "import pandas as pd\nsingle_mols = bond.groupby('molecule_id').apply(lambda g: (g['bond_type'] == '-').all()).loc[lambda x: x].index\nresult = atom[atom['molecule_id'].isin(single_mols)]['element'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.element) FROM atom T1 WHERE T1.molecule_id IN (SELECT molecule_id FROM bond GROUP BY molecule_id HAVING SUM(bond_type != '-') = 0)", "difficulty": "simple" }, { "question_id": 260, "question": "Calculate the total atoms with triple-bond molecules containing the element phosphorus or bromine.", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#'; phosphorus refers to element = 'p'; bromine refers to element = 'br'", "code": "import pandas as pd\n\n# Merge atom with molecule\nmerged1 = pd.merge(atom, molecule, on='molecule_id')\n\n# Merge with bond\nmerged2 = pd.merge(merged1, bond, on='molecule_id')\n\n# Filter for triple bonds and elements p or br\nfiltered = merged2[(merged2['bond_type'] == '#') & (merged2['element'].isin(['p', 'br']))]\n\n# Count unique atoms\nresult = filtered['atom_id'].nunique()", "sql": "SELECT COUNT(T1.atom_id) FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN bond AS T3 ON T2.molecule_id = T3.molecule_id WHERE T3.bond_type = '#' AND T1.element IN ('p', 'br')", "difficulty": "moderate" }, { "question_id": 261, "question": "Write down bond id for molecules that are carcinogenic.", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\ncarcinogenic_molecules = molecule[molecule['label'] == '+']\nmerged = pd.merge(bond, carcinogenic_molecules, on='molecule_id')\nresult = merged[['bond_id']].drop_duplicates()", "sql": "SELECT DISTINCT T1.bond_id FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+'", "difficulty": "simple" }, { "question_id": 262, "question": "Among the single bond molecule id, which molecules are not carcinogenic?", "db_id": "toxicology", "evidence": "label = '-' means molecules are non-carcinogenic; single bond refers to bond_type = '-';", "code": "import pandas as pd\nnon_carcinogenic = molecule[molecule['label'] == '-'][['molecule_id']]\nhas_other_bond = bond[bond['bond_type'] != '-'][['molecule_id']]\nresult = non_carcinogenic[~non_carcinogenic['molecule_id'].isin(has_other_bond['molecule_id'])]", "sql": "SELECT T2.molecule_id\nFROM molecule T2\nWHERE T2.label = '-'\nAND NOT EXISTS (\n SELECT 1 FROM bond\n WHERE molecule_id = T2.molecule_id\n AND bond_type != '-'\n)", "difficulty": "simple" }, { "question_id": 263, "question": "What is the composition of element chlorine in percentage among the single bond molecules?", "db_id": "toxicology", "evidence": "element chlorine refers to element = 'cl'; single bond refers to bond_type = '-'; percentage = DIVIDE(SUM(element = 'cl'), COUNT(atom_id)) as percent where bond_type = '-'", "code": "import pandas as pd\n\natom_df = pd.read_csv('atom.csv')\nbond_df = pd.read_csv('bond.csv')\nmolecule_df = pd.read_csv('molecule.csv')\n\nmerged_df = pd.merge(atom_df, molecule_df, on='molecule_id')\nmerged_df = pd.merge(merged_df, bond_df, on='molecule_id')\nfiltered_df = merged_df[merged_df['bond_type'] == '-']\ntotal_atoms = len(filtered_df)\nchlorine_atoms = len(filtered_df[filtered_df['element'] == 'cl'])\npercentage = (chlorine_atoms / total_atoms) * 100 if total_atoms > 0 else 0\nresult = pd.DataFrame({'percent': [percentage]})", "sql": "SELECT CAST(COUNT(CASE WHEN T.element = 'cl' THEN T.atom_id ELSE NULL END) AS REAL) * 100 / COUNT(T.atom_id) FROM ( SELECT T1.atom_id, T1.element FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN bond AS T3 ON T2.molecule_id = T3.molecule_id WHERE T3.bond_type = '-' ) AS T", "difficulty": "challenging" }, { "question_id": 264, "question": "What are the labels for TR000, TR001 and TR002?", "db_id": "toxicology", "evidence": "label equals '+' in the database; label equals '-' in the database;", "code": "import pandas as pd\n\nmolecule_df = pd.read_csv('molecule.csv')\n\nfiltered_df = molecule_df[molecule_df['molecule_id'].isin(['TR000', 'TR001', 'TR002'])]\n\noutput = filtered_df[['molecule_id', 'label']].reset_index(drop=True)\n\nprint(output),", "sql": "", "difficulty": "simple" }, { "question_id": 265, "question": "List down the molecule id for non carcinogenic molecules.", "db_id": "toxicology", "evidence": "label equals '-' in the database;", "code": "import pandas as pd\nresult = molecule[molecule['label'] == '-'][['molecule_id']]", "sql": "SELECT T.molecule_id FROM molecule AS T WHERE T.label = '-'", "difficulty": "simple" }, { "question_id": 266, "question": "Calculate the total carcinogenic molecules for molecule id from TR000 to TR030.", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\n\n# Filter molecules with id between TR000 and TR030 and label = '+'\nfiltered_molecules = molecule[(molecule['molecule_id'] >= 'TR000') & (molecule['molecule_id'] <= 'TR030') & (molecule['label'] == '+')]\n\n# Count the total number of carcinogenic molecules\nresult = len(filtered_molecules)", "sql": "SELECT COUNT(T.molecule_id) FROM molecule AS T WHERE T.molecule_id BETWEEN 'TR000' AND 'TR030' AND T.label = '+'", "difficulty": "simple" }, { "question_id": 267, "question": "List down the bond type for molecules from molecule id TR000 to TR050.", "db_id": "toxicology", "evidence": "double bond refers to bond_type = ' = '; single bond refers to bond_type = '-'; triple bond refers to bond_type = '#';", "code": "import pandas as pd\n\n# Filter molecules between TR000 and TR050\nfiltered_molecules = molecule[(molecule['molecule_id'] >= 'TR000') & (molecule['molecule_id'] <= 'TR050')]\n\n# Merge with bond table to get bond types\nresult = pd.merge(filtered_molecules[['molecule_id']], bond[['molecule_id', 'bond_type']], on='molecule_id', how='inner')", "sql": "SELECT T2.molecule_id, T2.bond_type FROM molecule AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.molecule_id BETWEEN 'TR000' AND 'TR050'", "difficulty": "moderate" }, { "question_id": 268, "question": "What are the elements for bond id TR001_10_11?", "db_id": "toxicology", "evidence": "TR001_10_11 is the bond id;", "code": "import pandas as pd\n\n# Merge connected and atom tables on atom_id\nmerged = pd.merge(connected, atom, on='atom_id')\n\n# Filter for bond_id TR001_10_11\nfiltered = merged[merged['bond_id'] == 'TR001_10_11']\n\n# Select only the element column\nresult = filtered[['element']]", "sql": "SELECT T2.element FROM connected AS T1 INNER JOIN atom AS T2 ON T1.atom_id = T2.atom_id WHERE T1.bond_id = 'TR001_10_11'", "difficulty": "challenging" }, { "question_id": 269, "question": "How many bond id have element iodine?", "db_id": "toxicology", "evidence": "element equals 'i' in the database;", "code": "import pandas as pd\nmask = connected['atom_id'].isin(atom[atom['element'] == 'i']['atom_id']) | connected['atom_id2'].isin(atom[atom['element'] == 'i']['atom_id'])\nbond_ids = connected.loc[mask, 'bond_id']\nresult = pd.DataFrame({'count': [bond_ids.nunique()]})", "sql": "SELECT COUNT(DISTINCT T3.bond_id) FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id OR T1.atom_id = T2.atom_id2 INNER JOIN bond AS T3 ON T2.bond_id = T3.bond_id WHERE T1.element = 'i'", "difficulty": "simple" }, { "question_id": 270, "question": "Among the molecules with element Calcium, are they mostly carcinogenic or non carcinogenic?", "db_id": "toxicology", "evidence": "calcium refers to element = 'ca'; label = '+' mean molecules are carcinogenic; label = '-' means molecules are non-carcinogenic; MAX(label)", "code": "import pandas as pd\n\n# Filter atoms with calcium element\nca_atoms = atom[atom['element'] == 'ca']\n\n# Get unique molecule_ids with calcium\nca_molecules = ca_atoms[['molecule_id']].drop_duplicates()\n\n# Merge with molecule table to get labels\nmerged = pd.merge(ca_molecules, molecule, on='molecule_id')\n\n# Group by label and count\nlabel_counts = merged.groupby('label').size().reset_index(name='count')\n\n# Sort by count descending and get the most common label\nresult = label_counts.sort_values('count', ascending=False).head(1)['label'].values[0]", "sql": "SELECT T2.label FROM (SELECT DISTINCT molecule_id FROM atom WHERE element = 'ca') AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id GROUP BY T2.label ORDER BY COUNT(T2.label) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 271, "question": "Does bond id TR001_1_8 have both element of chlorine and carbon?", "db_id": "toxicology", "evidence": "chlorine refers to element = 'cl'; carbon refers to element = 'c'", "code": "import pandas as pd\n\n# Read the CSV files\ndf_connected = pd.read_csv('connected.csv')\ndf_atom = pd.read_csv('atom.csv')\n\n# Merge connected table with atom table twice to get elements for both atoms in the bond\n# SQL: JOIN atom a ON (c.atom_id = a.atom_id OR c.atom_id2 = a.atom_id)\n# Merge for atom_id\nmerged = pd.merge(df_connected, df_atom[['atom_id', 'element']], left_on='atom_id', right_on='atom_id')\nmerged = merged.rename(columns={'element': 'element_1'})\n\n# Merge for atom_id2\nmerged = pd.merge(merged, df_atom[['atom_id', 'element']], left_on='atom_id2', right_on='atom_id')\nmerged = merged.rename(columns={'element': 'element_2'})\n\n# Filter for the specific bond_id\n# SQL: WHERE b.bond_id = 'TR001_1_8'\ntarget_bond = merged[merged['bond_id'] == 'TR001_1_8']\n\n# Initialize result as 'no' (default case)\nresult = 'no'\n\nif not target_bond.empty:\n # Get elements, convert to lower case string for comparison\n e1 = str(target_bond.iloc[0]['element_1']).lower()\n e2 = str(target_bond.iloc[0]['element_2']).lower()\n \n # Check if we have exactly one Carbon ('c') and one Chlorine ('cl')\n # Set comparison {e1, e2} == {'c', 'cl'} handles order independence\n if {e1, e2} == {'c', 'cl'}:\n result = 'yes'\n\nprint(result)", "sql": "SELECT CASE WHEN COUNT(DISTINCT CASE WHEN a.element IN ('c', 'cl') THEN a.element END) = 2 THEN 'yes' ELSE 'no' END AS result FROM bond b JOIN connected c ON b.bond_id = c.bond_id JOIN atom a ON (c.atom_id = a.atom_id OR c.atom_id2 = a.atom_id) WHERE b.bond_id = 'TR001_1_8' AND a.element IN ('c', 'cl')", "difficulty": "simple" }, { "question_id": 272, "question": "List down two molecule id of triple bond non carcinogenic molecules with element carbon.", "db_id": "toxicology", "evidence": "carbon refers to element = 'c'; triple bond refers to bond_type = '#'; label = '-' means molecules are non-carcinogenic", "code": "import pandas as pd\n\n# Filter atoms with carbon element\ncarbon_atoms = atom[atom['element'] == 'c']\n\n# Filter bonds with triple bond type\ntriple_bonds = bond[bond['bond_type'] == '#']\n\n# Filter non-carcinogenic molecules\nnon_carcinogenic = molecule[molecule['label'] == '-']\n\n# Merge carbon atoms with non-carcinogenic molecules\nmerged1 = pd.merge(carbon_atoms, non_carcinogenic, on='molecule_id')\n\n# Merge with triple bonds\nmerged2 = pd.merge(merged1, triple_bonds, on='molecule_id')\n\n# Merge with connected table to verify bond exists\nmerged3 = pd.merge(merged2, connected, on='bond_id')\n\n# Get distinct molecule_ids and limit to 2\nresult = merged3[['molecule_id']].drop_duplicates().head(2)", "sql": "SELECT DISTINCT T2.molecule_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN bond AS T3 ON T2.molecule_id = T3.molecule_id INNER JOIN connected AS T4 ON T3.bond_id = T4.bond_id WHERE T3.bond_type = '#' AND T1.element = 'c' AND T2.label = '-' LIMIT 2", "difficulty": "moderate" }, { "question_id": 273, "question": "What is the percentage of element chlorine in carcinogenic molecules?", "db_id": "toxicology", "evidence": "chlorine refers to element = 'cl'; label = '+' mean molecules are carcinogenic; percentage = DIVIDE(SUM(element = 'pb'); COUNT(molecule_id)) as percentage where label = '+'", "code": "import pandas as pd\nmerged = pd.merge(atom, molecule, on='molecule_id')\ncarcinogenic = merged[merged['label'] == '+']\nchlorine_count = len(carcinogenic[carcinogenic['element'] == 'cl'])\ntotal_count = len(carcinogenic)\npercentage = (chlorine_count / total_count) * 100 if total_count > 0 else 0\nresult = percentage", "sql": "SELECT CAST(COUNT( CASE WHEN T1.element = 'cl' THEN T1.element ELSE NULL END) AS REAL) * 100 / COUNT(T1.element) FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+'", "difficulty": "moderate" }, { "question_id": 274, "question": "List the toxicology elements associated with molecule TR001.", "db_id": "toxicology", "evidence": "TR001 is the molecule id", "code": "import pandas as pd\nresult = atom[atom['molecule_id'] == 'TR001'][['element']].drop_duplicates()", "sql": "SELECT DISTINCT T.element FROM atom AS T WHERE T.molecule_id = 'TR001'", "difficulty": "simple" }, { "question_id": 275, "question": "Give me the molecule ID of the double bond type.", "db_id": "toxicology", "evidence": "double bond refers to bond_type = '=';", "code": "import pandas as pd\nresult = bond[bond['bond_type'] == '=']['molecule_id'].unique()", "sql": "SELECT DISTINCT T.molecule_id FROM bond AS T WHERE T.bond_type = '='", "difficulty": "simple" }, { "question_id": 276, "question": "Write down the atom IDs of the first and second atoms of triple bond type molecules.", "db_id": "toxicology", "evidence": "first atom refers to atom_id; second atom refers to atom_id2; triple bond refers to bond_type = '#';", "code": "import pandas as pd\nmerged = pd.merge(bond, connected, on='bond_id')\nresult = merged[merged['bond_type'] == '#'][['atom_id', 'atom_id2']]", "sql": "SELECT T2.atom_id, T2.atom_id2 FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id WHERE T1.bond_type = '#';", "difficulty": "simple" }, { "question_id": 277, "question": "What are the toxicology elements associated with bond ID TR000_1_2?", "db_id": "toxicology", "evidence": "TR000_1_2 is the bond id;", "code": "import pandas as pd\n\n# Filter connected table for the specific bond_id\nconnected_filtered = connected[connected['bond_id'] == 'TR000_1_2']\n\n# Get elements from atom_id column\natoms1 = pd.merge(connected_filtered[['atom_id']], atom, on='atom_id')[['element']]\n\n# Get elements from atom_id2 column\natoms2 = pd.merge(connected_filtered[['atom_id2']], atom, left_on='atom_id2', right_on='atom_id')[['element']]\n\n# Union the results and remove duplicates\nresult = pd.concat([atoms1, atoms2]).drop_duplicates().reset_index(drop=True)", "sql": "SELECT T1.element FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id WHERE T2.bond_id = 'TR000_1_2' UNION SELECT T3.element FROM atom AS T3 INNER JOIN connected AS T2 ON T3.atom_id = T2.atom_id2 WHERE T2.bond_id = 'TR000_1_2'", "difficulty": "challenging" }, { "question_id": 278, "question": "How many of the single bond type molecules are non-carcinogenic?", "db_id": "toxicology", "evidence": "label = '-' means molecules are non-carcinogenic; single bond refers to bond_type = '-';", "code": "import pandas as pd\nsingle_bond_mols = bond.groupby('molecule_id').filter(lambda g: (g['bond_type'] == '-').all())['molecule_id'].unique()\nresult = molecule[(molecule['label'] == '-') & (molecule['molecule_id'].isin(single_bond_mols))].shape[0]", "sql": "SELECT COUNT(*) FROM molecule WHERE label = '-' AND molecule_id IN (SELECT molecule_id FROM bond GROUP BY molecule_id HAVING COUNT(bond_type) = SUM(bond_type = '-'))", "difficulty": "simple" }, { "question_id": 279, "question": "What is the label for bond ID TR001_10_11?", "db_id": "toxicology", "evidence": "label equals '+' in the database; label equals '-' in the database;", "code": "import pandas as pd\n\n# Merge bond and molecule tables on molecule_id\nmerged = pd.merge(bond, molecule, on='molecule_id')\n\n# Filter for the specific bond_id\nresult = merged[merged['bond_id'] == 'TR001_10_11'][['label']]", "sql": "SELECT T2.label FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.bond_id = 'TR001_10_11'", "difficulty": "simple" }, { "question_id": 280, "question": "Enumerate the bond ID of triple bond type molecules and tell me if they are carcinogenic or not.", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#'; label = '+' mean molecules are carcinogenic; label = '-' means molecules are non-carcinogenic", "code": "import pandas as pd\nfiltered_bonds = bond[bond['bond_type'] == '#']\nmerged = pd.merge(filtered_bonds, molecule, on='molecule_id')\nresult = merged[['bond_id', 'label']].drop_duplicates()", "sql": "SELECT DISTINCT T1.bond_id, T2.label FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.bond_type = '#'", "difficulty": "moderate" }, { "question_id": 281, "question": "Tally the toxicology element of the 4th atom of each molecule that was carcinogenic.", "db_id": "toxicology", "evidence": "label = '+' means molecules are carcinogenic; 4th atom of each molecule refers to substr(atom_id, 7, 1) = '4'; ['atom_id length constraint equals 7 for valid atoms']", "code": "import pandas as pd\nmerged = pd.merge(atom, molecule, on='molecule_id')\nfiltered = merged[(merged['label'] == '+') & (merged['atom_id'].str[6] == '4')]\nresult = filtered['element'].drop_duplicates()", "sql": "SELECT DISTINCT T1.element FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+' AND SUBSTR(T1.atom_id, 7, 1) = '4'", "difficulty": "challenging" }, { "question_id": 282, "question": "What is the ratio of Hydrogen elements in molecule ID TR006? List the ratio with its label.", "db_id": "toxicology", "evidence": "hydrogen refers to element = 'h'; ratio = DIVIDE(SUM(element = 'h'), count(element)) where molecule_id = 'TR006' ; label = '+' mean molecules are carcinogenic; label = '-' means molecules are non-carcinogenic", "code": "import pandas as pd\n\n# 筛选TR006分子的原子\ntr006_atoms = atom[atom['molecule_id'] == 'TR006']\n\n# 合并molecule表获取label\ntr006_with_label = pd.merge(tr006_atoms, molecule[['molecule_id', 'label']], on='molecule_id')\n\n# 计算氢原子比例\ngrouped = tr006_with_label.groupby('label')\nhydrogen_count = grouped.apply(lambda x: (x['element'] == 'h').sum())\ntotal_count = grouped.size()\nratio = hydrogen_count / total_count\n\n# 构建结果\nresult = pd.DataFrame({\n 'ratio': ratio,\n 'label': ratio.index\n}).reset_index(drop=True)", "sql": "WITH SubQuery AS (SELECT DISTINCT T1.atom_id, T1.element, T1.molecule_id, T2.label FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.molecule_id = 'TR006') SELECT CAST(COUNT(CASE WHEN element = 'h' THEN atom_id ELSE NULL END) AS REAL) / (CASE WHEN COUNT(atom_id) = 0 THEN NULL ELSE COUNT(atom_id) END) AS ratio, label FROM SubQuery GROUP BY label", "difficulty": "challenging" }, { "question_id": 283, "question": "Identify whether the chemical compound that contains Calcium is carcinogenic.", "db_id": "toxicology", "evidence": "calcium refers to element = 'ca'; label = '+' mean molecules are carcinogenic; label = '-' means molecules are non-carcinogenic;", "code": "import pandas as pd\n\n# Merge atom and molecule tables to find molecules containing calcium\nca_molecules = pd.merge(atom[atom['element'] == 'ca'], molecule, on='molecule_id')\n\n# Get the carcinogenic labels for molecules containing calcium\nresult = ca_molecules[['label']].rename(columns={'label': 'flag_carcinogenic'})", "sql": "SELECT T2.label AS flag_carcinogenic FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'ca'", "difficulty": "moderate" }, { "question_id": 284, "question": "Determine the bond type that is formed in the chemical compound containing element Carbon.", "db_id": "toxicology", "evidence": "Carbon refers to element = 'c'; double bond refers to bond_type = ' = '; single bond refers to bond_type = '-'; triple bond refers to bond_type = '#';", "code": "import pandas as pd\nmerged = pd.merge(atom[atom['element'] == 'c'], bond, on='molecule_id')\nresult = merged['bond_type'].drop_duplicates().reset_index(drop=True)", "sql": "SELECT DISTINCT T2.bond_type FROM atom AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'c'", "difficulty": "moderate" }, { "question_id": 285, "question": "Name chemical elements that form a bond TR001_10_11.", "db_id": "toxicology", "evidence": "element = 'cl' means Chlorine; element = 'c' means Carbon; element = 'h' means Hydrogen; element = 'o' means Oxygen, element = 's' means Sulfur; element = 'n' means Nitrogen, element = 'p' means Phosphorus, element = 'na' means Sodium, element = 'br' means Bromine, element = 'f' means Fluorine; element = 'i' means Iodine; element = 'sn' means Tin; element = 'pb' means Lead; element = 'te' means Tellurium; element = 'ca' means Calcium; TR001_10_11 is the bond id; molecule id refers to SUBSTR(bond_id, 1, 5); atom 1 refers to SUBSTR(bond_id, 7, 2); atom 2 refers to SUBSTR(bond_id, 10, 2)", "code": "import pandas as pd\n\n# Filter connected table for the specific bond\nconnected_filtered = connected[connected['bond_id'] == 'TR001_10_11']\n\n# Get unique atom_ids from both atom_id and atom_id2 columns\natom_ids = pd.concat([connected_filtered['atom_id'], connected_filtered['atom_id2']]).unique()\n\n# Filter atom table for these atom_ids and get their elements\nresult = atom[atom['atom_id'].isin(atom_ids)][['element']]", "sql": "SELECT T1.element FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id INNER JOIN bond AS T3 ON T2.bond_id = T3.bond_id WHERE T3.bond_id = 'TR001_10_11'", "difficulty": "challenging" }, { "question_id": 286, "question": "Among all chemical compounds identified in the database, what percent of compounds form a triple-bond.", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#';", "code": "import pandas as pd\n\nmolecule_df = pd.read_csv('molecule.csv')\nbond_df = pd.read_csv('bond.csv')\n\nmerged_df = pd.merge(molecule_df, bond_df, on='molecule_id', how='left')\n\noutput = pd.DataFrame({'percent': [(merged_df[merged_df['bond_type'] == '#']['molecule_id'].nunique() * 100.0) / merged_df['molecule_id'].nunique()]})\n\nprint(output)", "sql": "", "difficulty": "simple" }, { "question_id": 287, "question": "Among all chemical compounds that contain molecule TR047, identify the percent that form a double-bond.", "db_id": "toxicology", "evidence": "TR047 is the molecule id; double bond refers to bond_type = ' = '; percentage = DIVIDE(SUM(bond_type = ' = '), COUNT(all bond_id)) as percent where molecule_id = 'TR047'", "code": "import pandas as pd\n\n# Filter bonds for molecule TR047\ntr047_bonds = bond[bond['molecule_id'] == 'TR047']\n\n# Calculate percentage of double bonds\ndouble_bonds = tr047_bonds[tr047_bonds['bond_type'] == '=']\npercentage = (len(double_bonds) / len(tr047_bonds)) * 100\n\nresult = percentage", "sql": "SELECT CAST(COUNT(CASE WHEN T.bond_type = '=' THEN T.bond_id ELSE NULL END) AS REAL) * 100 / COUNT(T.bond_id) FROM bond AS T WHERE T.molecule_id = 'TR047'", "difficulty": "moderate" }, { "question_id": 288, "question": "Identify whether the molecule that contains atom TR001_1 is carcinogenic.", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for the specific atom_id\nfiltered = merged[merged['atom_id'] == 'TR001_1']\n\n# Select only the label column and rename it\nresult = filtered[['label']].rename(columns={'label': 'flag_carcinogenic'})", "sql": "SELECT T2.label AS flag_carcinogenic FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.atom_id = 'TR001_1'", "difficulty": "simple" }, { "question_id": 289, "question": "Is molecule TR151 carcinogenic?", "db_id": "toxicology", "evidence": "label equals '+' in the database;'+' refers to carcinogenic; '-' refers to non-carcinogenic", "code": "import pandas as pd\nfiltered = molecule[molecule['molecule_id'] == 'TR151']\nresult = filtered.assign(is_carcinogenic=filtered['label'].map({'+': 'Yes', '-': 'No'}))[['is_carcinogenic']]", "sql": "SELECT (CASE WHEN T.label = '+' THEN 'Yes' ELSE 'No' END) AS is_carcinogenic FROM molecule AS T WHERE T.molecule_id = 'TR151'", "difficulty": "simple" }, { "question_id": 290, "question": "Which toxic element can be found in the molecule TR151?", "db_id": "toxicology", "evidence": "element equals 'cl' in the database; element equals 'c' in the database; element equals 'h' in the database; element equals 'o' in the database; element equals 's' in the database; element equals 'n' in the database; element equals 'p' in the database; element equals 'na' in the database; element equals 'br' in the database; element equals 'f' in the database; element equals 'i' in the database; element equals 'sn' in the database; element equals 'pb' in the database; element equals 'te' in the database; element equals 'ca' in the database;", "code": "import pandas as pd\nresult = atom[atom['molecule_id'] == 'TR151']['element'].unique()", "sql": "SELECT DISTINCT T.element FROM atom AS T WHERE T.molecule_id = 'TR151'", "difficulty": "challenging" }, { "question_id": 291, "question": "How many chemical compounds in the database are identified as carcinogenic.", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\nresult = molecule[molecule['label'] == '+'].shape[0]", "sql": "SELECT COUNT(T.molecule_id) FROM molecule AS T WHERE T.label = '+'", "difficulty": "simple" }, { "question_id": 292, "question": "Identify the atoms belong to the molecule with ID between TR010 to TR050 that contain the element carbon.", "db_id": "toxicology", "evidence": "carbon refers to element = 'c'; between TR010 to TR050 refers to substr(molecule_id, 3, 3)>=10 AND substr(molecule_id, 3, 3) <= 50", "code": "import pandas as pd\n\n# Filter atoms table for molecules between TR010 and TR050 with carbon element\nresult = atom[(atom['molecule_id'] >= 'TR010') & (atom['molecule_id'] <= 'TR050') & (atom['element'] == 'c')][['atom_id']]", "sql": "SELECT T.atom_id FROM atom AS T WHERE T.molecule_id BETWEEN 'TR010' AND 'TR050' AND T.element = 'c'", "difficulty": "simple" }, { "question_id": 293, "question": "How many atoms belong to the molecule labeled with carcinogenic compounds?", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for carcinogenic compounds (label = '+')\ncarcinogenic = merged[merged['label'] == '+']\n\n# Count the number of atoms\nresult = len(carcinogenic)", "sql": "SELECT COUNT(T1.atom_id) FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+'", "difficulty": "simple" }, { "question_id": 294, "question": "Which bond ids are double-bond with carcinogenic compound?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; double bond refers to bond_type = ' = ';", "code": "import pandas as pd\nresult = pd.merge(bond[bond['bond_type'] == '='], molecule[molecule['label'] == '+'], on='molecule_id')['bond_id']", "sql": "SELECT T1.bond_id FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+' AND T1.bond_type = '='", "difficulty": "simple" }, { "question_id": 295, "question": "How many atoms belong to the molecule that element is hydrogen and labeled with carcinogenic compound?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; hydrogen refers to element = h'", "code": "import pandas as pd\nimport numpy as np\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for carcinogenic molecules (label = '+') and hydrogen atoms (element = 'h')\nfiltered = merged[(merged['label'] == '+') & (merged['element'] == 'h')]\n\n# Count the number of hydrogen atoms\nresult = len(filtered)", "sql": "SELECT COUNT(T1.atom_id) AS atomnums_h FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+' AND T1.element = 'h'", "difficulty": "simple" }, { "question_id": 296, "question": "Indicate the molecule id is belonging to the TR000_1_2 bond that has the first atom named TR000_1.", "db_id": "toxicology", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(connected, bond, on='bond_id', how='inner')\nfiltered = merged[(merged['bond_id'] == 'TR000_1_2') & ((merged['atom_id'] == 'TR000_1') | (merged['atom_id2'] == 'TR000_1'))]\nresult = filtered[['molecule_id', 'bond_id', 'atom_id']]", "sql": "SELECT T2.molecule_id, T2.bond_id, T1.atom_id\nFROM connected AS T1\nINNER JOIN bond AS T2 ON T1.bond_id = T2.bond_id\nWHERE T2.bond_id = 'TR000_1_2'\n AND (T1.atom_id = 'TR000_1' OR T1.atom_id2 = 'TR000_1')", "difficulty": "simple" }, { "question_id": 297, "question": "Among the atoms that contain element carbon, which one does not contain compound carcinogenic?", "db_id": "toxicology", "evidence": "label = '-' means molecules are non-carcinogenic; carbon refers to element = 'c'", "code": "import pandas as pd\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for carbon atoms in non-carcinogenic molecules\nresult = merged[(merged['element'] == 'c') & (merged['label'] == '-')][['atom_id']]", "sql": "SELECT T1.atom_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'c' AND T2.label = '-'", "difficulty": "simple" }, { "question_id": 298, "question": "Calculate the percentage of molecules containing carcinogenic compounds that element is hydrogen.", "db_id": "toxicology", "evidence": "hydrogen refers to element = 'h'; label = '+' mean molecules are carcinogenic; percentage = DIVIDE(SUM(label = '+' and element = 'h'), COUNT(molecule_id)) * 100.0", "code": "import pandas as pd\n# 读取各表数据\natom = pd.read_csv('atom.csv')\nmolecule = pd.read_csv('molecule.csv')\n\n# 连接 atom 和 molecule 表\natom_mol = pd.merge(atom, molecule, on='molecule_id')\n\n# 筛选 label = '+' 的分子(致癌分子)\ncarcinogenic_molecules = atom_mol[atom_mol['label'] == '+']\n\n# 计算分子总数(label = '+')\ntotal_carcinogenic = carcinogenic_molecules['molecule_id'].nunique()\n\n# 筛选同时满足 label = '+' 且 element = 'h' 的原子\nhydrogen_in_carcinogenic = carcinogenic_molecules[carcinogenic_molecules['element'] == 'h']\n\n# 计算满足条件的分子数量\nunique_molecules_with_h = hydrogen_in_carcinogenic['molecule_id'].nunique()\n\n# 计算百分比\npercentage = (unique_molecules_with_h / total_carcinogenic) * 100.0 if total_carcinogenic > 0 else 0.0\n\n# 输出结果\nresult = pd.DataFrame({'percentage': [percentage]})\nprint(result)", "sql": "SELECT \n CASE \n WHEN COUNT(DISTINCT m.molecule_id) > 0 THEN\n ROUND(\n (COUNT(DISTINCT CASE WHEN a.element = 'h' THEN a.molecule_id END) * 100.0) \n / COUNT(DISTINCT m.molecule_id), \n 2\n )\n ELSE 0.0 \n END AS percentage\nFROM molecule m\nLEFT JOIN atom a ON m.molecule_id = a.molecule_id\nWHERE m.label = '+';", "difficulty": "moderate" }, { "question_id": 299, "question": "Is molecule TR124 carcinogenic?", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\nresult = molecule[molecule['molecule_id'] == 'TR124']['label']", "sql": "SELECT T.label FROM molecule AS T WHERE T.molecule_id = 'TR124'", "difficulty": "simple" }, { "question_id": 300, "question": "What atoms comprise TR186?", "db_id": "toxicology", "evidence": "TR186 is a molecule id", "code": "import pandas as pd\nresult = atom[atom['molecule_id'] == 'TR186'][['atom_id']]", "sql": "SELECT T.atom_id FROM atom AS T WHERE T.molecule_id = 'TR186'", "difficulty": "simple" }, { "question_id": 301, "question": "What is the bond type of TR007_4_19?", "db_id": "toxicology", "evidence": "double bond refers to bond_type = ' = '; single bond refers to bond_type = '-'; triple bond refers to bond_type = '#';", "code": "import pandas as pd\nresult = bond[bond['bond_id'] == 'TR007_4_19']['bond_type']", "sql": "SELECT T.bond_type FROM bond AS T WHERE T.bond_id = 'TR007_4_19'", "difficulty": "simple" }, { "question_id": 302, "question": "Name the elements that comprise the atoms of bond TR001_2_4.", "db_id": "toxicology", "evidence": "element equals 'cl' in the database; element equals 'c' in the database; element equals 'h' in the database; element equals 'o' in the database; element equals 's' in the database; element equals 'n' in the database; element equals 'p' in the database; element equals 'na' in the database; element equals 'br' in the database; element equals 'f' in the database; element equals 'i' in the database; element equals 'sn' in the database; element equals 'pb' in the database; element equals 'te' in the database; element equals 'ca' in the database;", "code": "import pandas as pd\nmerged = pd.merge(atom, connected, on='atom_id')\nfiltered = merged[merged['bond_id'] == 'TR001_2_4']\nresult = filtered[['element']].drop_duplicates()", "sql": "SELECT DISTINCT T1.element FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id WHERE T2.bond_id = 'TR001_2_4'", "difficulty": "challenging" }, { "question_id": 303, "question": "How many double bonds does TR006 have and is it carcinogenic?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; label = '-' means molecules are non-carcinogenic; double bond refers to bond_type = ' = ';", "code": "import pandas as pd\n\n# Filter bonds for TR006 and bond_type = '='\ntr006_bonds = bond[(bond['molecule_id'] == 'TR006') & (bond['bond_type'] == '=')]\n\n# Get the molecule label for TR006\ntr006_molecule = molecule[molecule['molecule_id'] == 'TR006']\n\n# Count double bonds and get label\nif len(tr006_molecule) > 0:\n double_bond_count = len(tr006_bonds)\n label = tr006_molecule['label'].iloc[0]\n result = pd.DataFrame({\n 'count': [double_bond_count],\n 'label': [label]\n })\nelse:\n result = pd.DataFrame(columns=['count', 'label'])\n", "sql": "SELECT COUNT(T1.bond_id), T2.label FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.bond_type = '=' AND T2.molecule_id = 'TR006' GROUP BY T2.label", "difficulty": "moderate" }, { "question_id": 304, "question": "List all carcinogenic molecules and their elements.", "db_id": "toxicology", "evidence": "label equals '+' in the database; element equals 'cl' in the database; element equals 'c' in the database; element equals 'h' in the database; element equals 'o' in the database; element equals 's' in the database; element equals 'n' in the database; element equals 'p' in the database; element equals 'na' in the database; element equals 'br' in the database; element equals 'f' in the database; element equals 'i' in the database; element equals 'sn' in the database; element equals 'pb' in the database; element equals 'te' in the database; element equals 'ca' in the database;", "code": "import pandas as pd\ncarcinogenic_molecules = molecule[molecule['label'] == '+']\nresult = pd.merge(atom, carcinogenic_molecules, on='molecule_id')[['molecule_id', 'element']].drop_duplicates()", "sql": "SELECT DISTINCT T2.molecule_id, T1.element FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+'", "difficulty": "challenging" }, { "question_id": 305, "question": "Name all bonds with single bond types and what atoms are connected to the molecules.", "db_id": "toxicology", "evidence": "single bond refers to bond_type = '-';", "code": "import pandas as pd\nfiltered_bond = bond[bond['bond_type'] == '-']\nmerged = pd.merge(filtered_bond, connected, on='bond_id')\nresult = merged[['bond_id', 'molecule_id', 'atom_id', 'atom_id2']]", "sql": "SELECT T1.bond_id, T1.molecule_id, T2.atom_id, T2.atom_id2 FROM bond AS T1 INNER JOIN connected AS T2 ON T1.bond_id = T2.bond_id WHERE T1.bond_type = '-'", "difficulty": "simple" }, { "question_id": 306, "question": "Which molecules have triple bonds and list all the elements they contain.", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#'; element = 'cl' means Chlorine; element = 'c' means Carbon; element = 'h' means Hydrogen; element = 'o' means Oxygen, element = 's' means Sulfur; element = 'n' means Nitrogen, element = 'p' means Phosphorus, element = 'na' means Sodium, element = 'br' means Bromine, element = 'f' means Fluorine; element = 'i' means Iodine; element = 'sn' means Tin; element = 'pb' means Lead; element = 'te' means Tellurium; element = 'ca' means Calcium", "code": "import pandas as pd\n\n# Filter bonds with triple bond type\ntriple_bonds = bond[bond['bond_type'] == '#']\n\n# Get valid bonds by joining with connected table\nvalid_triple_bonds = pd.merge(triple_bonds, connected, on='bond_id')[['molecule_id', 'bond_id']].drop_duplicates()\n\n# Get all atoms for molecules with triple bonds\natoms_with_triple = pd.merge(valid_triple_bonds[['molecule_id']], atom, on='molecule_id')\n\n# Get distinct molecule_id and element combinations\nresult = atoms_with_triple[['molecule_id', 'element']].drop_duplicates()", "sql": "SELECT DISTINCT T1.molecule_id, T2.element FROM bond AS T1 INNER JOIN connected AS T3 ON T1.bond_id = T3.bond_id INNER JOIN atom AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.bond_type = '#'", "difficulty": "challenging" }, { "question_id": 307, "question": "Name the atoms' elements that form bond TR000_2_3.", "db_id": "toxicology", "evidence": "element equals 'cl' in the database; element equals 'c' in the database; element equals 'h' in the database; element equals 'o' in the database; element equals 's' in the database; element equals 'n' in the database; element equals 'p' in the database; element equals 'na' in the database; element equals 'br' in the database; element equals 'f' in the database; element equals 'i' in the database; element equals 'sn' in the database; element equals 'pb' in the database; element equals 'te' in the database; element equals 'ca' in the database;", "code": "import pandas as pd\nmerged = pd.merge(connected[connected['bond_id'] == 'TR000_2_3'], atom, on='atom_id')\nresult = merged[['element']]", "sql": "SELECT T2.element FROM connected AS T1 INNER JOIN atom AS T2 ON T1.atom_id = T2.atom_id WHERE T1.bond_id = 'TR000_2_3'", "difficulty": "challenging" }, { "question_id": 308, "question": "How many bonds are created by bonding atoms with chlorine element?", "db_id": "toxicology", "evidence": "element equals 'cl' in the database;", "code": "import pandas as pd\n\n# Assuming DataFrames are already loaded\n# atom, bond, connected, molecule\n\n# Filter atoms with chlorine element\ncl_atoms = atom[atom['element'] == 'cl']\n\n# Merge connected with chlorine atoms\nmerged = pd.merge(connected, cl_atoms[['atom_id']], on='atom_id')\n\n# Count unique bonds\nresult = len(merged['bond_id'].unique())", "sql": "SELECT COUNT(T1.bond_id) FROM connected AS T1 INNER JOIN atom AS T2 ON T1.atom_id = T2.atom_id WHERE T2.element = 'cl'", "difficulty": "simple" }, { "question_id": 309, "question": "List out the atom id that belongs to the TR346 molecule and how many bond type can be created by this molecule?", "db_id": "toxicology", "evidence": "", "code": "import pandas as pd\n# 假设数据已加载为DataFrame变量\n# 过滤TR346分子的原子\nfiltered_atom = atom[atom['molecule_id'] == 'TR346']\n# 与键表进行内连接\nmerged = pd.merge(filtered_atom, bond, on='molecule_id')\n# 按原子ID分组并统计唯一键类型数量\nresult = merged.groupby('atom_id')['bond_type'].nunique().reset_index(name='bond_type_count')", "sql": "SELECT T1.atom_id, COUNT(DISTINCT T2.bond_type) FROM atom AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.molecule_id = 'TR346' GROUP BY T1.atom_id", "difficulty": "simple" }, { "question_id": 310, "question": "How many molecules have a double bond type and among these molecule, how many are labeled as carcinogenic compound?", "db_id": "toxicology", "evidence": "double bond refers to bond_type = ' = '; label = '+' mean molecules are carcinogenic;", "code": "import pandas as pd\nmolecule_ids = bond[bond['bond_type'] == '=']['molecule_id'].drop_duplicates()\nfiltered = molecule[molecule['molecule_id'].isin(molecule_ids)]\ntotal = len(filtered)\ncarcinogenic = (filtered['label'] == '+').sum()\nresult = pd.DataFrame([[total, carcinogenic]], columns=['total', 'carcinogenic'])", "sql": "SELECT COUNT(DISTINCT T2.molecule_id), SUM(CASE WHEN T2.label = '+' THEN 1 ELSE 0 END) FROM (SELECT DISTINCT molecule_id FROM bond WHERE bond_type = '=') AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id", "difficulty": "moderate" }, { "question_id": 311, "question": "How many molecules without sulphur element is not having double bond?", "db_id": "toxicology", "evidence": "double bond refers to bond_type = ' = '; bond_type ! = ' = '; sulphur refers to element = 's'", "code": "import pandas as pd\ns_mols = atom[atom['element'] == 's']['molecule_id'].dropna().unique()\ndouble_bonds = bond[bond['bond_type'] == '=']['molecule_id'].dropna().unique()\nresult = molecule[~molecule['molecule_id'].isin(s_mols) & ~molecule['molecule_id'].isin(double_bonds)].shape[0]", "sql": "SELECT COUNT(DISTINCT T1.molecule_id) FROM molecule AS T1 WHERE T1.molecule_id NOT IN (SELECT T2.molecule_id FROM atom AS T2 WHERE T2.element = 's') AND T1.molecule_id NOT IN (SELECT T3.molecule_id FROM bond AS T3 WHERE T3.bond_type = '=')", "difficulty": "simple" }, { "question_id": 312, "question": "What is the carcinogenic label for bond TR001_2_4?", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\n\n# Merge bond with molecule to get label\nmerged = pd.merge(bond, molecule, on='molecule_id')\n\n# Filter for the specific bond_id\nfiltered = merged[merged['bond_id'] == 'TR001_2_4']\n\n# Get distinct labels\nresult = filtered[['label']].drop_duplicates()", "sql": "SELECT DISTINCT T2.label FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN bond AS T3 ON T2.molecule_id = T3.molecule_id WHERE T3.bond_id = 'TR001_2_4'", "difficulty": "simple" }, { "question_id": 313, "question": "How many atoms belong to molecule id TR001?", "db_id": "toxicology", "evidence": "", "code": "import pandas as pd\nresult = atom[atom['molecule_id'] == 'TR001']['atom_id'].count()", "sql": "SELECT COUNT(T.atom_id) FROM atom AS T WHERE T.molecule_id = 'TR001'", "difficulty": "simple" }, { "question_id": 314, "question": "How many single bonds are there in the list?", "db_id": "toxicology", "evidence": "single bond refers to bond_type = '-';", "code": "import pandas as pd\nresult = bond[bond['bond_type'] == '-'].shape[0]", "sql": "SELECT COUNT(T.bond_id) FROM bond AS T WHERE T.bond_type = '-'", "difficulty": "simple" }, { "question_id": 315, "question": "Among the molecules which contain \"cl\" element, which of them are carcinogenic?", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\nmerged = pd.merge(atom[atom['element'] == 'cl'], molecule[molecule['label'] == '+'], on='molecule_id')\nresult = merged[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT T1.molecule_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'cl' AND T2.label = '+'", "difficulty": "simple" }, { "question_id": 316, "question": "Among the molecules which contain \"c\" element, which of them are not carcinogenic?", "db_id": "toxicology", "evidence": "label equals '-' in the database;", "code": "import pandas as pd\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for carbon atoms and non-carcinogenic molecules\nfiltered = merged[(merged['element'] == 'c') & (merged['label'] == '-')]\n\n# Get distinct molecule_ids\nresult = filtered[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT T1.molecule_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'c' AND T2.label = '-'", "difficulty": "simple" }, { "question_id": 317, "question": "Calculate the percentage of carcinogenic molecules which contain the Chlorine element.", "db_id": "toxicology", "evidence": "label equals '+' in the database; element equals 'cl' in the database; count of molecule_id; sum of label = '+' and element = 'cl';", "code": "import pandas as pd\npositive = molecule[molecule['label'] == '+']\nwith_atom = pd.merge(positive, atom, on='molecule_id', how='left')\ncl_mols = with_atom[with_atom['element'] == 'cl']['molecule_id'].nunique()\ntotal = positive['molecule_id'].nunique()\nresult = pd.DataFrame([[(cl_mols / total) * 100]], columns=['percentage'])", "sql": "SELECT \n (COUNT(DISTINCT CASE WHEN T1.element = 'cl' THEN T2.molecule_id END) * 100.0) \n / COUNT(DISTINCT T2.molecule_id) \nFROM molecule AS T2 \nLEFT JOIN atom AS T1 ON T2.molecule_id = T1.molecule_id \nWHERE T2.label = '+'", "difficulty": "moderate" }, { "question_id": 318, "question": "What is the molecule id of bond id TR001_1_7?", "db_id": "toxicology", "evidence": "", "code": "import pandas as pd\n\n# Merge atom and connected tables on atom_id\nmerged = pd.merge(atom, connected, on='atom_id')\n\n# Filter by bond_id\nfiltered = merged[merged['bond_id'] == 'TR001_1_7']\n\n# Get unique molecule_id values\nresult = filtered[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT T1.molecule_id FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id WHERE T2.bond_id = 'TR001_1_7'", "difficulty": "simple" }, { "question_id": 319, "question": "How many elements are contained in bond_id TR001_3_4?", "db_id": "toxicology", "evidence": "element equals 'cl' in the database; element equals 'c' in the database; element equals 'h' in the database; element equals 'o' in the database; element equals 's' in the database; element equals 'n' in the database; element equals 'p' in the database; element equals 'na' in the database; element equals 'br' in the database; element equals 'f' in the database; element equals 'i' in the database; element equals 'sn' in the database; element equals 'pb' in the database; element equals 'te' in the database; element equals 'ca' in the database;", "code": "import pandas as pd\n\n# Merge connected and atom tables to get elements for the specific bond\nmerged = pd.merge(connected, atom, on='atom_id')\n\n# Filter for the specific bond_id\nfiltered = merged[merged['bond_id'] == 'TR001_3_4']\n\n# Count distinct elements\nresult = filtered['element'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.element) FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id WHERE T2.bond_id = 'TR001_3_4'", "difficulty": "challenging" }, { "question_id": 320, "question": "What is the type of the bond which is presenting the connection between two atoms TR000_1 and TR000_2?", "db_id": "toxicology", "evidence": "type of bond refers to bond_type; double bond refers to bond_type = ' = '; single bond refers to bond_type = '-'; triple bond refers to bond_type = '#';", "code": "import pandas as pd\n\n# Filter connected table for the specific atom pair\nconnected_filtered = connected[(connected['atom_id'] == 'TR000_1') & (connected['atom_id2'] == 'TR000_2')]\n\n# Get bond_id from the filtered connection\nbond_id = connected_filtered['bond_id'].iloc[0] if len(connected_filtered) > 0 else None\n\n# Get bond type from bond table\nif bond_id is not None:\n result = bond[bond['bond_id'] == bond_id]['bond_type'].iloc[0]\nelse:\n result = None", "sql": "SELECT T1.bond_type FROM bond T1 JOIN connected T2 ON T1.bond_id = T2.bond_id JOIN atom a1 ON T2.atom_id = a1.atom_id JOIN atom a2 ON T2.atom_id2 = a2.atom_id WHERE a1.atom_id = 'TR000_1' AND a2.atom_id = 'TR000_2' AND T1.molecule_id = a1.molecule_id AND T1.molecule_id = a2.molecule_id", "difficulty": "moderate" }, { "question_id": 321, "question": "What is the molecule of atom id \"TR000_2\" and atom id 2 \"TR000_4\"?", "db_id": "toxicology", "evidence": "", "code": "import pandas as pd\n\n# Filter connected table for the specific atom pair\nconnection = connected[(connected['atom_id'] == 'TR000_2') & (connected['atom_id2'] == 'TR000_4')]\n\n# Merge with atom table to get molecule_id for first atom\nmerged1 = pd.merge(connection, atom, left_on='atom_id', right_on='atom_id')\n\n# Merge with atom table to get molecule_id for second atom\nmerged2 = pd.merge(merged1, atom, left_on='atom_id2', right_on='atom_id', suffixes=('_1', '_2'))\n\n# Filter where both atoms belong to the same molecule\nfiltered = merged2[merged2['molecule_id_1'] == merged2['molecule_id_2']]\n\n# Get the molecule_id\nresult = filtered[['molecule_id_1']].rename(columns={'molecule_id_1': 'molecule_id'}).head(1)", "sql": "SELECT T3.molecule_id FROM connected AS T1 INNER JOIN atom AS T2 ON T1.atom_id = T2.atom_id INNER JOIN atom AS T3 ON T1.atom_id2 = T3.atom_id WHERE T1.atom_id = 'TR000_2' AND T1.atom_id2 = 'TR000_4' AND T2.molecule_id = T3.molecule_id LIMIT 1", "difficulty": "simple" }, { "question_id": 322, "question": "What is the element of toxicology for the atom with the ID of TR000_1?", "db_id": "toxicology", "evidence": "atom with ID refers to atom_id; element = 'cl' means Chlorine; element = 'c' means Carbon; element = 'h' means Hydrogen; element = 'o' means Oxygen, element = 's' means Sulfur; element = 'n' means Nitrogen, element = 'p' means Phosphorus, element = 'na' means Sodium, element = 'br' means Bromine, element = 'f' means Fluorine; element = 'i' means Iodine; element = 'sn' means Tin; element = 'pb' means Lead; element = 'te' means Tellurium; element = 'ca' means Calcium", "code": "import pandas as pd\nresult = atom[atom['atom_id'] == 'TR000_1']['element'].iloc[0]", "sql": "SELECT T.element FROM atom AS T WHERE T.atom_id = 'TR000_1'", "difficulty": "challenging" }, { "question_id": 323, "question": "Is molecule TR000 is carcinogenic or not?", "db_id": "toxicology", "evidence": "label equals '+' in the database; label equals '-' in the database;", "code": "import pandas as pd\nresult = molecule[molecule['molecule_id'] == 'TR000'][['label']]", "sql": "SELECT label FROM molecule AS T WHERE T.molecule_id = 'TR000'", "difficulty": "simple" }, { "question_id": 324, "question": "Find the percentage of atoms with single bond.", "db_id": "toxicology", "evidence": "single bond refers to bond_type = '-'; percentage = DIVIDE(SUM(bond_type = '-'), COUNT(bond_id)) as percentageconnected table links atom_id to bond_id; bond_type in bond table indicates bond type for connected atoms", "code": "import pandas as pd\nmerged_ac = pd.merge(atom, connected, on='atom_id', how='left')\nmerged_acb = pd.merge(merged_ac, bond, on='bond_id', how='left')\nsingle_atoms = merged_acb[merged_acb['bond_type'] == '-']['atom_id'].unique()\ntotal_atom_count = atom['atom_id'].nunique()\npercentage = (len(single_atoms) / total_atom_count) * 100\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(COUNT(DISTINCT CASE WHEN b.bond_type = '-' THEN a.atom_id ELSE NULL END) AS REAL) * 100 / COUNT(DISTINCT a.atom_id) AS percentage FROM atom a LEFT JOIN connected c ON a.atom_id = c.atom_id LEFT JOIN bond b ON c.bond_id = b.bond_id", "difficulty": "simple" }, { "question_id": 325, "question": "How many carcinogenic molecules that consisted of Nitrogen?", "db_id": "toxicology", "evidence": "nitrogen refers to element = 'n'; label = '+' mean molecules are carcinogenic;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge molecule and atom tables\nmerged = pd.merge(molecule, atom, on='molecule_id')\n\n# Filter for nitrogen atoms and carcinogenic molecules\nfiltered = merged[(merged['element'] == 'n') & (merged['label'] == '+')]\n\n# Count distinct molecules\nresult = filtered['molecule_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.molecule_id) FROM molecule AS T1 INNER JOIN atom AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.element = 'n' AND T1.label = '+'", "difficulty": "simple" }, { "question_id": 326, "question": "Which molecule consisted of Sulphur atom with double bond?", "db_id": "toxicology", "evidence": "sulphur refers to element - 's'; double bond refers to bond_type = ' = ';", "code": "import pandas as pd\n\n# Merge atom and bond tables on molecule_id\nmerged = pd.merge(atom[atom['element'] == 's'], bond[bond['bond_type'] == '='], on='molecule_id')\n\n# Get distinct molecule_ids\nresult = merged[['molecule_id']].drop_duplicates()", "sql": "SELECT DISTINCT m.molecule_id\nFROM molecule m\nWHERE EXISTS (\n SELECT 1 FROM atom a\n INNER JOIN connected c ON a.atom_id IN (c.atom_id, c.atom_id2)\n INNER JOIN bond b ON c.bond_id = b.bond_id\n WHERE a.molecule_id = m.molecule_id\n AND a.element = 's'\n AND b.bond_type = '='\n);", "difficulty": "simple" }, { "question_id": 327, "question": "Which non-carcinogenic molecules consisted more than 5 atoms?", "db_id": "toxicology", "evidence": "label = '-' means molecules are non-carcinogenic; molecules consisted more than 5 atoms refers to COUNT(molecule_id) > 5", "code": "import pandas as pd\\n\\nmolecule = pd.read_csv('../toxicology/molecule.csv')\\natom = pd.read_csv('../toxicology/atom.csv')\\n\\nmerged = pd.merge(molecule[molecule['label'] == '-'], atom, on='molecule_id')\\ngrouped = merged.groupby('molecule_id').size().reset_index(name='atom_count')\\nresult = grouped[grouped['atom_count'] > 5][['molecule_id']]\\n\\nprint(result)", "sql": "SELECT T.molecule_id FROM ( SELECT T1.molecule_id, COUNT(T2.atom_id) FROM molecule AS T1 INNER JOIN atom AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.label = '-' GROUP BY T1.molecule_id HAVING COUNT(T2.atom_id) > 5 ) t", "difficulty": "moderate" }, { "question_id": 328, "question": "List all the elements with double bond, consisted in molecule TR024.", "db_id": "toxicology", "evidence": "double bond refers to bond_type = '='; element = 'cl' means Chlorine; element = 'c' means Carbon; element = 'h' means Hydrogen; element = 'o' means Oxygen, element = 's' means Sulfur; element = 'n' means Nitrogen, element = 'p' means Phosphorus, element = 'na' means Sodium, element = 'br' means Bromine, element = 'f' means Fluorine; element = 'i' means Iodine; element = 'sn' means Tin; element = 'pb' means Lead; element = 'te' means Tellurium; element = 'ca' means Calcium", "code": "import pandas as pd\ndouble_bond_ids = bond[bond['bond_type'] == '=']['bond_id']\nconnected_double = connected[connected['bond_id'].isin(double_bond_ids)]\ndouble_atom_ids = pd.concat([connected_double['atom_id'], connected_double['atom_id2']])\ntr024_mask = (atom['molecule_id'] == 'TR024') & atom['atom_id'].isin(double_atom_ids)\nresult = atom[tr024_mask][['element']].drop_duplicates()", "sql": "SELECT DISTINCT T1.element FROM atom T1 INNER JOIN connected ON T1.atom_id IN (connected.atom_id, connected.atom_id2) INNER JOIN bond T2 ON connected.bond_id = T2.bond_id WHERE T1.molecule_id = 'TR024' AND T2.bond_type = '='", "difficulty": "challenging" }, { "question_id": 329, "question": "Which carcinogenic molecule have the highest number of atoms consisted in it?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; molecule that have the highest number of atoms consisted in in refers to MAX(COUNT(atom.molecule_id))", "code": "import pandas as pd\n\n# Filter carcinogenic molecules\ncarcinogenic = molecule[molecule['label'] == '+']\n\n# Join with atom table to count atoms per molecule\nmerged = pd.merge(atom, carcinogenic, on='molecule_id')\n\n# Count atoms per molecule\natom_counts = merged.groupby('molecule_id').size().reset_index(name='atom_count')\n\n# Find molecule with highest atom count\nmax_atoms = atom_counts.loc[atom_counts['atom_count'].idxmax()]\n\n# Get the molecule_id\nresult = pd.DataFrame({'molecule_id': [max_atoms['molecule_id']]})", "sql": "SELECT T.molecule_id FROM ( SELECT T2.molecule_id, COUNT(T1.atom_id) FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+' GROUP BY T2.molecule_id ORDER BY COUNT(T1.atom_id) DESC LIMIT 1 ) t", "difficulty": "moderate" }, { "question_id": 330, "question": "Calculate the percentage of carcinogenic molecules with triple bonded Hidrogen atoms.", "db_id": "toxicology", "evidence": "hydrogen refers to element = 'h'; label = '+' mean molecules are carcinogenic; triple bond refers to bond_type = '#'; percentage = DIVIDE(SUM(label = '+'), COUNT(molecule_id)) * 100.0 where element = 'h' AND bond_type = '#';", "code": "import pandas as pd\nmol_atom = pd.merge(molecule, atom, on='molecule_id', how='inner')\nmerged1 = pd.merge(mol_atom, connected, left_on='atom_id', right_on='atom_id', how='inner')\nmerged2 = pd.merge(mol_atom, connected, left_on='atom_id', right_on='atom_id2', how='inner')\nconnected_merged = pd.concat([merged1, merged2], ignore_index=True).drop_duplicates()\nbond_merged = pd.merge(connected_merged, bond, on=['bond_id', 'molecule_id'], how='inner')\nfiltered = bond_merged[(bond_merged['bond_type'] == '#') & (bond_merged['element'] == 'h')]\nplus_count = filtered[filtered['label'] == '+']['molecule_id'].nunique()\ntotal_count = filtered['molecule_id'].nunique()\npercentage = (plus_count / total_count) * 100.0 if total_count > 0 else 0.0\nresult = pd.DataFrame([percentage])", "sql": "SELECT CAST(SUM(CASE WHEN T1.label = '+' THEN 1 ELSE 0 END) AS REAL) * 100.0 / COUNT(DISTINCT T1.molecule_id) \nFROM molecule AS T1 \nINNER JOIN atom AS T2 ON T1.molecule_id = T2.molecule_id \nINNER JOIN connected AS T4 ON T2.atom_id = T4.atom_id OR T2.atom_id = T4.atom_id2 \nINNER JOIN bond AS T3 ON T4.bond_id = T3.bond_id AND T1.molecule_id = T3.molecule_id \nWHERE T3.bond_type = '#' AND T2.element = 'h'", "difficulty": "challenging" }, { "question_id": 331, "question": "How many of the molecules are carcinogenic?", "db_id": "toxicology", "evidence": "label equals '+' in the database;", "code": "import pandas as pd\nresult = molecule[molecule['label'] == '+'].shape[0]", "sql": "SELECT COUNT(T.molecule_id) FROM molecule AS T WHERE T.label = '+'", "difficulty": "simple" }, { "question_id": 332, "question": "Among the molecules between TR004 to TR010, how many of them has single bonds?", "db_id": "toxicology", "evidence": "single bond refers to bond_type = '-'; molecules between TR004 to TR010 refers molecule_id BETWEEN 'TR004' and 'TR010';", "code": "import pandas as pd\n\n# Filter bond table for molecules between TR004 and TR010 with single bonds\nfiltered_bonds = bond[(bond['molecule_id'] >= 'TR004') & (bond['molecule_id'] <= 'TR010') & (bond['bond_type'] == '-')]\n\n# Count distinct molecules\nresult = filtered_bonds['molecule_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T.molecule_id) FROM bond AS T WHERE T.molecule_id BETWEEN 'TR004' AND 'TR010' AND T.bond_type = '-'", "difficulty": "simple" }, { "question_id": 333, "question": "In the molecule TR008, how many carbons are present?", "db_id": "toxicology", "evidence": "element equals 'c' in the database;", "code": "import pandas as pd\nresult = len(atom[(atom['molecule_id'] == 'TR008') & (atom['element'] == 'c')])", "sql": "SELECT COUNT(T.atom_id) FROM atom AS T WHERE T.molecule_id = 'TR008' AND T.element = 'c'", "difficulty": "simple" }, { "question_id": 334, "question": "What is the element with the atom ID of TR004_7 in molecule that is not carcinogenic?", "db_id": "toxicology", "evidence": "label equals '-' in the database; element equals 'cl' in the database; element equals 'c' in the database; element equals 'h' in the database; element equals 'o' in the database; element equals 's' in the database; element equals 'n' in the database; element equals 'p' in the database; element equals 'na' in the database; element equals 'br' in the database; element equals 'f' in the database; element equals 'i' in the database; element equals 'sn' in the database; element equals 'pb' in the database; element equals 'te' in the database; element equals 'ca' in the database;", "code": "import pandas as pd\n\n# Merge atom and molecule tables\nmerged = pd.merge(atom, molecule, on='molecule_id')\n\n# Filter for atom_id 'TR004_7' and non-carcinogenic molecules (label = '-')\nfiltered = merged[(merged['atom_id'] == 'TR004_7') & (merged['label'] == '-')]\n\n# Get the element\nresult = filtered[['element']]", "sql": "SELECT T1.element FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.atom_id = 'TR004_7' AND T2.label = '-'", "difficulty": "challenging" }, { "question_id": 335, "question": "What is the total number of molecules with double bonded oxygen?", "db_id": "toxicology", "evidence": "oxygen refers to element = 'o'; double bond refers to bond_type = ' = ';double bond refers to bond_type = '='; oxygen refers to element = 'o'; bond connects atoms via connected table", "code": "import pandas as pd\nbond_connected = pd.merge(bond, connected, on='bond_id')\natom1 = pd.merge(bond_connected, atom, left_on='atom_id', right_on='atom_id', suffixes=('', '_1'))\natom2 = pd.merge(atom1, atom, left_on='atom_id2', right_on='atom_id', suffixes=('', '_2'))\nfiltered = atom2[(atom2['bond_type'] == '=') & ((atom2['element'] == 'o') | (atom2['element_2'] == 'o'))]\nresult = filtered['molecule_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.molecule_id) FROM bond AS T2 INNER JOIN connected AS T3 ON T2.bond_id = T3.bond_id INNER JOIN atom AS T1 ON T3.atom_id = T1.atom_id INNER JOIN atom AS T4 ON T3.atom_id2 = T4.atom_id WHERE T2.bond_type = '=' AND (T1.element = 'o' OR T4.element = 'o')", "difficulty": "simple" }, { "question_id": 336, "question": "in molecules with triple bonds, how many of them are not carcinogenic?", "db_id": "toxicology", "evidence": "triple bond refers to bond_type = '#'; label = '-' means molecules are non-carcinogenic", "code": "import pandas as pd\n\n# Read the CSV files into DataFrames\natom_df = pd.read_csv('atom.csv')\nbond_df = pd.read_csv('bond.csv')\nconnected_df = pd.read_csv('connected.csv')\nmolecule_df = pd.read_csv('molecule.csv')\n\n# Filter molecules with triple bonds\ntriple_bond_molecules = bond_df[bond_df['bond_type'] == '#']['molecule_id'].unique()\n\n# Filter non-carcinogenic molecules\nnon_carcinogenic_molecules = molecule_df[molecule_df['label'] == '-']['molecule_id'].unique()\n\n# Find the intersection of triple bond molecules and non-carcinogenic molecules\nresult = len(set(triple_bond_molecules) & set(non_carcinogenic_molecules))\n\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.molecule_id) FROM molecule AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.bond_type = '#' AND T1.label = '-'", "difficulty": "simple" }, { "question_id": 337, "question": "List the element and bond type included in the molecule with molecule ID of TR002.", "db_id": "toxicology", "evidence": "TR002 is the molecule idelement in atom table refers to atom's element in molecule; bond_type in bond table refers to bond type in molecule", "code": "import pandas as pd\n# Filter TR002 atoms and bonds\ndf_atom_tr = atom[atom['molecule_id'] == 'TR002'][['atom_id', 'element']]\ndf_bond_tr = bond[bond['molecule_id'] == 'TR002'][['bond_id', 'bond_type']]\n# Join connected with bond\nconnected_bond = pd.merge(connected, df_bond_tr, on='bond_id')[['atom_id', 'atom_id2', 'bond_type']]\n# Merge with atoms for both atom positions\nmerge1 = pd.merge(connected_bond, df_atom_tr, left_on='atom_id', right_on='atom_id', how='inner')\nmerge2 = pd.merge(connected_bond, df_atom_tr, left_on='atom_id2', right_on='atom_id', how='inner')\n# Combine and deduplicate\nresult = pd.concat([merge1[['element', 'bond_type']], merge2[['element', 'bond_type']]], ignore_index=True).drop_duplicates()", "sql": "SELECT DISTINCT T1.element, T3.bond_type FROM atom AS T1 JOIN connected AS T2 ON T1.atom_id IN (T2.atom_id, T2.atom_id2) JOIN bond AS T3 ON T2.bond_id = T3.bond_id WHERE T1.molecule_id = 'TR002' AND T3.molecule_id = 'TR002'", "difficulty": "challenging" }, { "question_id": 338, "question": "What is the atom ID of double bonded carbon in TR012 molecule?", "db_id": "toxicology", "evidence": "carbon refers to element = 'c'; double bond refers to bond_type = ' = ';bond connects atoms via connected.atom_id and connected.atom_id2", "code": "import pandas as pd\nfiltered_atom = atom[(atom['molecule_id'] == 'TR012') & (atom['element'] == 'c')]\nbond_filtered = bond[bond['bond_type'] == '=']\nconnected_bond = pd.merge(connected, bond_filtered, on='bond_id')\nmask = filtered_atom['atom_id'].isin(connected_bond['atom_id']) | filtered_atom['atom_id'].isin(connected_bond['atom_id2'])\nresult = filtered_atom[mask][['atom_id']]", "sql": "SELECT T1.atom_id FROM atom T1\nINNER JOIN connected T4 ON T1.atom_id = T4.atom_id OR T1.atom_id = T4.atom_id2\nINNER JOIN bond T3 ON T4.bond_id = T3.bond_id\nWHERE T1.molecule_id = 'TR012'\n AND T3.bond_type = '='\n AND T1.element = 'c'", "difficulty": "moderate" }, { "question_id": 339, "question": "List the atom ID of the carcinogenic molecule that contains oxygen?", "db_id": "toxicology", "evidence": "label = '+' mean molecules are carcinogenic; oxygen refers to element = 'o'", "code": "import pandas as pd\nmerged = pd.merge(atom, molecule, on='molecule_id')\nfiltered = merged[(merged['element'] == 'o') & (merged['label'] == '+')]\nresult = filtered[['atom_id']]", "sql": "SELECT T1.atom_id FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T1.element = 'o' AND T2.label = '+'", "difficulty": "simple" }, { "question_id": 340, "question": "Which are the cards that have incredibly powerful foils.", "db_id": "card_games", "evidence": "incredibly poweful foils refers to cardKingdomFoilId is not null AND cardKingdomId is not null", "code": "import pandas as pd\nresult = cards[(cards['cardKingdomFoilId'].notna()) & (cards['cardKingdomId'].notna())][['id']]", "sql": "SELECT id FROM cards WHERE cardKingdomFoilId IS NOT NULL AND cardKingdomId IS NOT NULL", "difficulty": "simple" }, { "question_id": 341, "question": "What are the borderless cards available without powerful foils?", "db_id": "card_games", "evidence": "borderless' refers to borderColor; poweful foils refers to cardKingdomFoilId paired with cardKingdomId AND cardKingdomId is not null", "code": "import pandas as pd\nfiltered = cards[(cards['borderColor'] == 'borderless') & ((cards['cardKingdomId'].isnull()) | (cards['cardKingdomFoilId'].isnull()))]\nresult = filtered[['id']]", "sql": "SELECT id FROM cards WHERE borderColor = 'borderless' AND (cardKingdomId IS NULL OR cardKingdomFoilId IS NULL)", "difficulty": "simple" }, { "question_id": 342, "question": "List the card names with value that cost more converted mana for the face.", "db_id": "card_games", "evidence": "more converted mana for the face refers to Max(faceConvertedManaCost);", "code": "import pandas as pd\n\n# Read the CSV file strictly as requested\n# low_memory=False is added to handle mixed types warning mentioned in your log\ncards = pd.read_csv('cards.csv', low_memory=False)\n\n# Check if 'faceConvertedManaCost' exists, otherwise use 'convertedManaCost'\ntarget_col = 'faceConvertedManaCost' if 'faceConvertedManaCost' in cards.columns else 'convertedManaCost'\n\n# Calculate the maximum value strictly based on the available column\nmax_val = cards[target_col].max()\n\n# Filter the dataframe and select the name\nresult = cards[cards[target_col] == max_val]['name']\n\n# Print the final result\nprint(result)\n", "sql": "SELECT name FROM cards WHERE faceConvertedManaCost = (SELECT MAX(faceConvertedManaCost) FROM cards)", "difficulty": "simple" }, { "question_id": 343, "question": "Name all cards with 2015 frame style ranking below 100 on EDHRec.", "db_id": "card_games", "evidence": "below 100 on EDHRec refers to EDHRec <100; with 2015 frame style refers to frameVersion = 2015;", "code": "import pandas as pd\n\n\ndef get_2015_frame_cards_with_edhrec_below_100(cards_df):\n # Filter cards with 2015 frame style and EDHRec ranking below 100\n filtered_cards = cards_df[\n (cards_df['edhrecRank'] < 100) &\n (cards_df['edhrecRank'].notna()) &\n ((cards_df['frameVersion'] == '2015') | (cards_df['frameVersion'] == 2015))\n ]\n\n # Return only the id column as per the reference SQL\n result = filtered_cards[['id']].reset_index(drop=True)\n\n return result", "sql": "SELECT id FROM cards WHERE edhrecRank < 100 AND (frameVersion = '2015' OR frameVersion = 2015) AND edhrecRank IS NOT NULL", "difficulty": "simple" }, { "question_id": 344, "question": "List all the mythic rarity print cards banned in gladiator format.", "db_id": "card_games", "evidence": "mythic rarity printing refers to rarity = 'mythic'; card banned refers to status = 'Banned'; in gladiator format refers to format = 'gladiator';", "code": "import pandas as pd\\n\\ncards = pd.read_csv('../card_games/cards.csv')\\nlegalities = pd.read_csv('../card_games/legalities.csv')\\n\\n\\ndef solve_query(cards_df, legalities_df):\\n # Check if required columns exist\\n if 'uuid' not in cards_df.columns or 'uuid' not in legalities_df.columns:\\n return pd.DataFrame({'id': []})\\n\\n if 'rarity' not in cards_df.columns or 'format' not in legalities_df.columns or 'status' not in legalities_df.columns:\\n return pd.DataFrame({'id': []})\\n\\n # Filter legalities for gladiator format and banned status\\n filtered_legalities = legalities_df[\\n (legalities_df['format'] == 'gladiator') & (legalities_df['status'] == 'Banned')]\\n\\n # Merge with cards table,明确指定后缀\\n merged_data = pd.merge(cards_df, filtered_legalities, on='uuid', how='inner', suffixes=('_card', '_legal'))\\n\\n # Filter for mythic rarity\\n mythic_cards = merged_data[merged_data['rarity'] == 'mythic']\\n\\n # 选择cards表的id列(现在是id_card)\\n if 'id_card' in mythic_cards.columns:\\n result = mythic_cards[['id_card']].drop_duplicates()\\n result = result.rename(columns={'id_card': 'id'})\\n else:\\n result = pd.DataFrame({'id': []})\\n\\n return result\\n\\n\\nprint(solve_query(cards, legalities))", "sql": "SELECT DISTINCT T1.id FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.format = 'gladiator' AND T2.status = 'Banned' AND T1.rarity = 'mythic'", "difficulty": "moderate" }, { "question_id": 345, "question": "For artifact type of cards that do not have multiple faces on the same card, state its legalities status for vintage play format.", "db_id": "card_games", "evidence": "Artifact type of cards refers to types = 'Artifact'; card does not have multiple faces on the same card refers to side is NULL'; vintage play format refers to format = 'vintage';", "code": "import pandas as pd\nimport numpy as np\n\n# Filter cards for Artifact type and no multiple faces (side is NULL)\nartifact_cards = cards[(cards['type'] == 'Artifact') & (cards['side'].isna())]\n\n# Merge with legalities table\nmerged = pd.merge(artifact_cards[['uuid']], legalities, on='uuid')\n\n# Filter for vintage format\nvintage_legalities = merged[merged['format'] == 'vintage']\n\n# Get distinct status values\nresult = vintage_legalities['status'].drop_duplicates().reset_index(drop=True)", "sql": "SELECT DISTINCT T2.status FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.type = 'Artifact' AND T2.format = 'vintage' AND T1.side IS NULL", "difficulty": "moderate" }, { "question_id": 346, "question": "List all the card id and artist with unknown power which are legal for commander play format.", "db_id": "card_games", "evidence": "unknown power refers to power = '*' or POWER IS NULL; commander play format refers to format = 'commander'; legal for commander play format refers to format = 'commander' where status = 'Legal'", "code": "import pandas as pd\n\ndef solve_query(cards_df, legalities_df):\n # Merge cards and legalities on uuid with inner join\n merged = pd.merge(cards_df, legalities_df, on='uuid', how='inner')\n \n # Apply filtering conditions for commander legality and unknown power\n filtered = merged[\n (merged['format'] == 'commander') &\n (merged['status'] == 'Legal') &\n (merged['power'].isna() | (merged['power'] == '*'))\n ]\n \n # Select and rename columns to match SQL output\n result = filtered[['id_x', 'artist']].copy()\n result.columns = ['id', 'artist']\n return result\n\n# Execute the query with sample data\nresult = solve_query(cards, legalities)\n", "sql": "SELECT T1.id, T1.artist FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.status = 'Legal' AND T2.format = 'commander' AND (T1.power IS NULL OR T1.power = '*')", "difficulty": "moderate" }, { "question_id": 347, "question": "Find all cards illustrated by Stephen Daniele and describe the text of the ruling of these cards. State if these cards have missing or degraded properties and values.", "db_id": "card_games", "evidence": "cards have missing or degraded properties and value refers to hasContentWarning = 1; 'Stephen Daniele' is artist; Find all cards refers to return card id", "code": "import pandas as pd\n\n# 读取CSV文件\ncards_df = pd.read_csv('cards.csv')\nrulings_df = pd.read_csv('rulings.csv')\n\n# 筛选Stephen Daniele插画的卡牌\nstephen_cards = cards_df[cards_df['artist'] == 'Stephen Daniele']\n\n# LEFT JOIN操作:连接cards和rulings表\nmerged_df = pd.merge(stephen_cards, rulings_df, on='uuid', how='left', suffixes=('', '_ruling'))\n\n# 处理ruling文本,模拟COALESCE函数\nmerged_df['text'] = merged_df['text_ruling'].fillna('No ruling available')\n\n# 处理property_status,模拟CASE WHEN语句\nmerged_df['property_status'] = merged_df['hasContentWarning'].apply(\n lambda x: 'Has missing or degraded properties' if x == 1 else 'No issues'\n)\n\n# 选择最终输出列\nresult = merged_df[['id', 'text', 'property_status']]\n\n# 显示结果\nprint(result)", "sql": "SELECT \n T1.id, \n COALESCE(T2.text, 'No ruling available') AS text,\n CASE \n WHEN T1.hasContentWarning = 1 THEN 'Has missing or degraded properties' \n ELSE 'No issues' \n END AS property_status \nFROM cards AS T1 \nLEFT JOIN rulings AS T2 ON T1.uuid = T2.uuid \nWHERE T1.artist = 'Stephen Daniele'", "difficulty": "moderate" }, { "question_id": 348, "question": "Describe the information about rulings for card named 'Sublime Epiphany' with number 74s.", "db_id": "card_games", "evidence": "Sublime Epiphany' is name of cards; number 74s refers to number = '74s'; information refers to text;", "code": "import pandas as pd\\n\\n# 读取数据表\\ncards = pd.read_csv('cards.csv')\\nrulings = pd.read_csv('rulings.csv')\\n\\n# 筛选条件: name = 'Sublime Epiphany' 且 number = '74s'\\nfiltered_cards = cards[(cards['name'] == 'Sublime Epiphany') & (cards['number'] == '74s')]\\n\\n# 通过 uuid 连接 cards 和 rulings 表,明确指定后缀\\nmerged = pd.merge(filtered_cards, rulings, on='uuid', how='inner', suffixes=('_card', '_ruling'))\\n\\n# 选择 rulings 表的 text 列\\nresult = merged[['text_ruling']].drop_duplicates()\\nresult = result.rename(columns={'text_ruling': 'text'})", "sql": "SELECT T2.text FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Sublime Epiphany' AND T1.number = '74s'", "difficulty": "simple" }, { "question_id": 349, "question": "Name the card and artist with the most ruling information. Also state if the card is a promotional printing.", "db_id": "card_games", "evidence": "with the most ruling information refers to Max(count(rulings.uuid)); the card is the promotional printing refers to isPromo = 1;", "code": "import pandas as pd\n\ndef solve_query(cards_df, rulings_df):\n # Group rulings by uuid and count the number of rulings per uuid\n ruling_counts = rulings_df.groupby('uuid').size().reset_index(name='ruling_count')\n\n # Sort by ruling_count descending and get the top record\n max_ruling = ruling_counts.sort_values(by='ruling_count', ascending=False).iloc[:1]\n\n # Merge with cards to get card details\n result = pd.merge(cards_df, max_ruling, left_on='uuid', right_on='uuid', how='inner')\n\n # Select required columns and rename for clarity\n result = result[['name', 'artist', 'isPromo']]\n\n return result\n", "sql": "SELECT T1.name, T1.artist, T1.isPromo \nFROM cards AS T1 \nINNER JOIN (\n SELECT uuid, COUNT() AS ruling_count \n FROM rulings \n GROUP BY uuid \n HAVING ruling_count = (\n SELECT MAX(ruling_count) \n FROM (SELECT COUNT() AS ruling_count FROM rulings GROUP BY uuid) AS sub\n )\n ORDER BY uuid \n LIMIT 1\n) AS T2 ON T1.uuid = T2.uuid;", "difficulty": "moderate" }, { "question_id": 350, "question": "State the alternative languages available for card named Annul numbered 29.", "db_id": "card_games", "evidence": "annul refers to name = 'annul'; numbered 29 refers to number = '29';", "code": "import pandas as pd\nfiltered_cards = cards[(cards['name'] == 'Annul') & (cards['number'] == '29')]\nmerged = pd.merge(filtered_cards, foreign_data, on='uuid')\nresult = merged[['language']]", "sql": "SELECT T2.language FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Annul' AND T1.number = '29'", "difficulty": "simple" }, { "question_id": 351, "question": "Name all the cards which have alternative language in Japanese.", "db_id": "card_games", "evidence": "Japanese' is the language;", "code": "import pandas as pd\\n\\n\\ndef solve_query(cards_df, foreign_data_df):\\n # 先筛选日语数据(性能优化)\\n japanese_data = foreign_data_df[foreign_data_df['language'] == 'Japanese']\\n\\n # 再进行合并操作\\n merged = pd.merge(cards_df, japanese_data, on='uuid', how='inner', suffixes=('_card', '_foreign'))\\n\\n # 获取卡牌名称并去重\\n result = merged[['name_card']].drop_duplicates()\\n result = result.rename(columns={'name_card': 'name'})\\n\\n return result\\n\\n# 示例用法\\ncards = pd.read_csv('../card_games/cards.csv')\\nforeign_data = pd.read_csv('../card_games/foreign_data.csv')\\njapanese_cards = solve_query(cards, foreign_data)\\nprint(japanese_cards)", "sql": "SELECT T1.name FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T2.language = 'Japanese'", "difficulty": "simple" }, { "question_id": 352, "question": "Calculate the percentage of the cards availabe in Chinese Simplified.", "db_id": "card_games", "evidence": "language equals 'Chinese Simplified' in the database; count of id; sum of id where language = 'Chinese Simplified';", "code": "import pandas as pd\n\n# Merge cards and foreign_data on uuid\nmerged = pd.merge(cards, foreign_data, on='uuid')\n\n# Calculate percentage of cards available in Chinese Simplified\ntotal_cards = len(merged)\nchinese_simplified_cards = len(merged[merged['language'] == 'Chinese Simplified'])\npercentage = (chinese_simplified_cards / total_cards) * 100\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(COUNT(DISTINCT CASE WHEN T2.language = 'Chinese Simplified' THEN T1.uuid END) AS REAL) * 100 / COUNT(*) FROM cards AS T1 LEFT JOIN foreign_data AS T2 ON T1.uuid = T2.uuid", "difficulty": "moderate" }, { "question_id": 353, "question": "List all the sets available in Italian translation. State the total number of cards per set.", "db_id": "card_games", "evidence": "Italian translation refers to language = 'Italian'; total number of card per set refers to totalSetSize;", "code": "import pandas as pd\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\nfiltered = merged[merged['language'] == 'Italian']\nresult = filtered[['name', 'totalSetSize']]", "sql": "SELECT T1.name, T1.totalSetSize FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T2.language = 'Italian'", "difficulty": "simple" }, { "question_id": 354, "question": "How many types of cards does the artist Aaron Boyd illustrated about card art?", "db_id": "card_games", "evidence": "Aaron Boyd' is artist;type refers to card category", "code": "import pandas as pd\naaron_cards = cards[cards['artist'] == 'Aaron Boyd']\nresult = aaron_cards['type'].nunique()", "sql": "SELECT COUNT(DISTINCT type) FROM cards WHERE artist = 'Aaron Boyd'", "difficulty": "simple" }, { "question_id": 355, "question": "What is the keyword found on card 'Angel of Mercy'?", "db_id": "card_games", "evidence": "Angel of Mercy' is the name of card;", "code": "import pandas as pd\nresult = cards[cards['name'] == 'Angel of Mercy']['keywords'].drop_duplicates()", "sql": "SELECT DISTINCT keywords FROM cards WHERE name = 'Angel of Mercy'", "difficulty": "simple" }, { "question_id": 356, "question": "How many cards have infinite power?", "db_id": "card_games", "evidence": "infinite power refers to power = '*';", "code": "import pandas as pd\nresult = len(cards[cards['power'] == '*'])", "sql": "SELECT COUNT(*) FROM cards WHERE power = '*'", "difficulty": "simple" }, { "question_id": 357, "question": "What type of promotion is of card 'Duress'?", "db_id": "card_games", "evidence": "card Duress refers to name = 'Duress'; type of promotion refers to promoTypes;", "code": "import pandas as pd\nresult = cards[(cards['name'] == 'Duress') & (cards['promoTypes'].notna())][['promoTypes']]", "sql": "SELECT promoTypes FROM cards WHERE name = 'Duress' AND promoTypes IS NOT NULL;", "difficulty": "simple" }, { "question_id": 358, "question": "What is the border color of card \"Ancestor's Chosen\"?", "db_id": "card_games", "evidence": "card equals 'Ancestor' in the database;", "code": "import pandas as pd\nresult = cards[cards['name'] == \"Ancestor's Chosen\"]['borderColor'].drop_duplicates()", "sql": "SELECT DISTINCT borderColor FROM cards WHERE name = 'Ancestor''s Chosen'", "difficulty": "simple" }, { "question_id": 359, "question": "What is the type of the card \"Ancestor's Chosen\" as originally printed?", "db_id": "card_games", "evidence": "Ancestor's Chosen' is the name of card; type of the card as originally printed refers to originaltype;", "code": "import pandas as pd\nresult = cards[(cards['name'] == \"Ancestor's Chosen\") & (cards['originalType'].notna())]['originalType']", "sql": "SELECT originalType FROM cards WHERE name = 'Ancestor''s Chosen' AND originalType IS NOT NULL", "difficulty": "simple" }, { "question_id": 360, "question": "cards are not directly linked to language but through table 'set'. you need to add set in covered table & rephrase your question\nWhat are the languages available for the set that card 'Angel of Mercy' is in?", "db_id": "card_games", "evidence": "Angel of Mercy' is the name of card;'setCode' in 'cards' refers to 'code' in 'sets'; 'setCode' in 'set_translations' refers to 'code' in 'sets'", "code": "import pandas as pd\nset_code = cards[cards['name'] == 'Angel of Mercy']['setCode'].iloc[0]\nresult = set_translations[set_translations['setCode'] == set_code]['language']", "sql": "SELECT st.language FROM cards c JOIN sets s ON c.setCode = s.code JOIN set_translations st ON s.code = st.setCode WHERE c.name = 'Angel of Mercy';", "difficulty": "moderate" }, { "question_id": 361, "question": "How many cards of legalities whose status is restricted have text boxes?", "db_id": "card_games", "evidence": "restricted refers to status = 'restricted'; have text boxes refers to is Textless = 0;", "code": "import pandas as pd\n\n# Merge cards and legalities tables on uuid\nmerged = pd.merge(cards, legalities, on='uuid')\n\n# Filter for restricted status and cards with text boxes (isTextless = 0)\nfiltered = merged[(merged['status'] == 'Restricted') & (merged['isTextless'] == 0)]\n\n# Count distinct card ids\nresult = filtered['id_x'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.status = 'Restricted' AND T1.isTextless = 0", "difficulty": "simple" }, { "question_id": 362, "question": "What is the description about the ruling of card \"Condemn\"?", "db_id": "card_games", "evidence": "Ancestor's Chosen' is the name of card; description about the ruling refers to text;", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['name'] == 'Condemn'][['uuid']], rulings, on='uuid')\nresult = merged[['text']]", "sql": "SELECT T2.text FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Condemn'", "difficulty": "simple" }, { "question_id": 363, "question": "How many cards of legalities whose status is restricted are found in a starter deck?", "db_id": "card_games", "evidence": "restricted refers to status = 'restricted'; found in the starter deck refers to isStarter = 1;", "code": "def solve_query(cards_df, legalities_df):\n # Filter cards that are in starter decks\n starter_cards = cards_df[cards_df['isStarter'] == 1]\n\n # Filter legalities where status is 'Restricted'\n restricted_legalities = legalities_df[legalities_df['status'] == 'Restricted']\n\n # Merge the two DataFrames on uuid\n merged_data = pd.merge(starter_cards, restricted_legalities, left_on='uuid', right_on='uuid', how='inner')\n\n # Count distinct card ids\n result = merged_data['id_x'].nunique()\n\n return result", "sql": "SELECT COUNT(DISTINCT T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.status = 'Restricted' AND T1.isStarter = 1", "difficulty": "simple" }, { "question_id": 364, "question": "What is the status of card \"Cloudchaser Eagle\"?", "db_id": "card_games", "evidence": "Cloudchaser Eagle is the name of card;", "code": "import pandas as pd\nresult = pd.merge(cards[cards['name'] == 'Cloudchaser Eagle'], legalities, on='uuid')[['format', 'status']]", "sql": "SELECT T2.format, T2.status FROM cards AS T1 JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Cloudchaser Eagle'", "difficulty": "simple" }, { "question_id": 365, "question": "What is the type of card \"Benalish Knight\"?", "db_id": "card_games", "evidence": "Benalish Knight' is the name of card;", "code": "import pandas as pd\n\n# 读取数据表\ncards = pd.read_csv('../card_games/cards.csv')\n\n# 筛选名为 'Benalish Knight' 的卡牌\nfiltered_cards = cards[cards['name'] == 'Benalish Knight']\n\n# 获取卡牌类型并去重\nresult = filtered_cards[['type']].drop_duplicates()\n\nprint(result)", "sql": "SELECT DISTINCT type FROM cards WHERE name = 'Benalish Knight'", "difficulty": "simple" }, { "question_id": 366, "question": "What is the rule of playing card \"Benalish Knight\"?", "db_id": "card_games", "evidence": "Benalish Knight' is the name of card; rule of playing card refers to format;", "code": "import pandas as pd\nfiltered_cards = cards[cards['name'] == 'Benalish Knight']\nmerged = pd.merge(filtered_cards[['uuid']], legalities, on='uuid')\nresult = merged[['format']]", "sql": "SELECT T2.format FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Benalish Knight'", "difficulty": "simple" }, { "question_id": 367, "question": "Please provide the names of the artists who illustrated the card art in Phyrexian.", "db_id": "card_games", "evidence": "Phyrexian' is the language; name of artists refers to artist;", "code": "import pandas as pd\nmerged = pd.merge(cards, foreign_data, on='uuid')\nfiltered = merged[merged['language'] == 'Phyrexian']\nresult = filtered[['artist']]", "sql": "SELECT T1.artist FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T2.language = 'Phyrexian'", "difficulty": "simple" }, { "question_id": 368, "question": "What is the percentage of borderless cards?", "db_id": "card_games", "evidence": "borderless card refers to borderColor = 'borderless'; percentage = Divide(Count (id) where borderColor = 'borderless', Count(id)) *100", "code": "import pandas as pd\nimport numpy as np\n\nresult = (cards['borderColor'] == 'borderless').sum() * 100 / len(cards)", "sql": "SELECT CAST(SUM(CASE WHEN borderColor = 'borderless' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(id) FROM cards", "difficulty": "simple" }, { "question_id": 369, "question": "How many cards that illusrtated in German have been reprinted?", "db_id": "card_games", "evidence": "German' is the language; reprinted refers to isReprint = 1;", "code": "import pandas as pd\n\n# Merge cards and foreign_data tables on uuid\nmerged = pd.merge(cards, foreign_data, on='uuid')\n\n# Filter for German language and reprinted cards\nfiltered = merged[(merged['language'] == 'German') & (merged['isReprint'] == 1)]\n\n# Count the number of cards\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T2.language = 'German' AND T1.isReprint = 1", "difficulty": "simple" }, { "question_id": 370, "question": "How many borderless cards are illustrated in Russian?", "db_id": "card_games", "evidence": "borderless card refers to borderColor = 'borderless'; 'Russian' is the language;", "code": "import pandas as pd\n\n# Merge cards and foreign_data tables\nmerged = pd.merge(cards, foreign_data, on='uuid')\n\n# Filter for borderless cards in Russian\nfiltered = merged[(merged['borderColor'] == 'borderless') & (merged['language'] == 'Russian')]\n\n# Count the number of cards\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.borderColor = 'borderless' AND T2.language = 'Russian'", "difficulty": "simple" }, { "question_id": 371, "question": "What is the percentage of cards whose language is French among the Story Spotlight cards?", "db_id": "card_games", "evidence": "Story Spotlight card refers to isStorySpotlight = 1; French is the language; Percentage = Divide(Count(id) where language = 'French' and isStorySpotlight = 1, Count(id) where isStorySpotlight = 1)*100foreign_data contains language information for cards; Percentage = Divide(Count(T2.id) where T2.language = 'French' and T1.isStorySpotlight = 1, Count(T1.id) where T1.isStorySpotlight = 1)*100", "code": "import pandas as pd\nstory = cards[cards['isStorySpotlight'] == 1]\nfrench = foreign_data[foreign_data['language'] == 'French']\nmatch_count = pd.merge(story, french, on='uuid')['uuid'].nunique()\nresult = (match_count / len(story)) * 100", "sql": "SELECT (CAST(COUNT(DISTINCT CASE WHEN T2.language = 'French' THEN T1.uuid END) AS REAL) * 100) / COUNT(DISTINCT T1.uuid) FROM cards AS T1 LEFT JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.isStorySpotlight = 1", "difficulty": "challenging" }, { "question_id": 372, "question": "How many cards are there with toughness of 99?", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\nresult = len(cards[cards['toughness'] == '99'])", "sql": "SELECT COUNT(id) FROM cards WHERE toughness = '99'", "difficulty": "simple" }, { "question_id": 373, "question": "Name the cards that were illustrated by Aaron Boyd.", "db_id": "card_games", "evidence": "Aaron Boyd' is artist;", "code": "import pandas as pd\nresult = cards[cards['artist'] == 'Aaron Boyd']['name'].drop_duplicates()", "sql": "SELECT DISTINCT name FROM cards WHERE artist = 'Aaron Boyd'", "difficulty": "simple" }, { "question_id": 374, "question": "How many black border cards are only available on mtgo?", "db_id": "card_games", "evidence": "black border card refers to borderColor = black; available on mtgo refers to availability = mtgo;\n\nadd quotes for string = 'black' and = 'mtgo'", "code": "import pandas as pd\nresult = len(cards[(cards['availability'] == 'mtgo') & (cards['borderColor'] == 'black')])", "sql": "SELECT COUNT(id) FROM cards WHERE availability = 'mtgo' AND borderColor = 'black'", "difficulty": "simple" }, { "question_id": 375, "question": "List down all the card IDs with converted mana cost of 0.", "db_id": "card_games", "evidence": "converted mana cost of 0 refers to covertedManaCost = 0;", "code": "import pandas as pd\nresult = cards[cards['convertedManaCost'] == 0]['id']", "sql": "SELECT id FROM cards WHERE convertedManaCost = 0", "difficulty": "simple" }, { "question_id": 376, "question": "What are the card layout of cards with keyword of flying?", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\n\nresult = cards[cards['keywords'] == 'Flying'][['layout']]", "sql": "SELECT layout FROM cards WHERE ',' || keywords || ',' LIKE '%,Flying,%'", "difficulty": "simple" }, { "question_id": 377, "question": "How many cards with original type of \"Summon - Angel\" have subtype other than \"Angel\"?", "db_id": "card_games", "evidence": "subtype other than Angel refers to subtypes is not 'Angel';", "code": "import pandas as pd\nresult = cards[(cards['originalType'] == 'Summon - Angel') & (cards['subtypes'] != 'Angel')]['id'].count()", "sql": "SELECT COUNT(id) FROM cards WHERE originalType = 'Summon - Angel' AND subtypes != 'Angel'", "difficulty": "simple" }, { "question_id": 378, "question": "What are the foiled cards that are incredibly powerful when paired with non foiled cards? List the IDs.", "db_id": "card_games", "evidence": "Incredibly powerful refers to both cardKingdomFoilId and cardKingdomId IS NOT Null;", "code": "import pandas as pd\nresult = cards[(cards['cardKingdomId'].notna()) & (cards['cardKingdomFoilId'].notna())]['id']", "sql": "SELECT id FROM cards WHERE cardKingdomId IS NOT NULL AND cardKingdomFoilId IS NOT NULL", "difficulty": "simple" }, { "question_id": 379, "question": "What are the cards belong to duel deck a? List the ID.", "db_id": "card_games", "evidence": "duel deck a refers to duelDeck = a;", "code": "import pandas as pd\nresult = cards[cards['duelDeck'] == 'a'][['id']]", "sql": "SELECT id FROM cards WHERE duelDeck = 'a'", "difficulty": "simple" }, { "question_id": 380, "question": "List the edhrecRank for cards with frame version 2015.", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\nresult = cards[cards['frameVersion'] == '2015'][['edhrecRank']]", "sql": "SELECT edhrecRank FROM cards WHERE frameVersion = '2015'", "difficulty": "simple" }, { "question_id": 381, "question": "List down the name of artists for cards in Chinese Simplified.", "db_id": "card_games", "evidence": "Chinese Simplified' is the language;", "code": "import pandas as pd\nresult = pd.merge(cards, foreign_data, on='uuid')[foreign_data['language'] == 'Chinese Simplified'][['artist']]", "sql": "SELECT T1.artist FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T2.language = 'Chinese Simplified'", "difficulty": "simple" }, { "question_id": 382, "question": "What are the cards that only available in paper and Japanese language?", "db_id": "card_games", "evidence": "available in paper refers to availability = 'paper'; 'Japanese is the language;", "code": "import pandas as pd\n\ndef solve_query(cards, foreign_data):\n merged = pd.merge(cards, foreign_data, on='uuid')\n filtered = merged[(merged['availability'] == 'paper') & (merged['language'] == 'Japanese')]\n if not filtered.empty:\n return filtered[['name_x']].rename(columns={'name_x': 'name'})\n return pd.DataFrame(columns=['name'])\n\n# Example function call (replace with actual data loading)\n# cards_df = pd.read_csv('cards.csv')\n# foreign_df = pd.read_csv('foreign_data.csv')\n# result = solve_query(cards_df, foreign_df)", "sql": "SELECT T1.name FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.availability = 'paper' AND T2.language = 'Japanese'", "difficulty": "simple" }, { "question_id": 383, "question": "How many of the banned cards are white border?", "db_id": "card_games", "evidence": "banned card refers to status = 'Banned'; white border refers to borderColor = 'white';", "code": "import pandas as pd\n\ndf_cards = pd.read_csv('cards.csv')\ndf_legalities = pd.read_csv('legalities.csv')\n\nmerged_df = pd.merge(df_cards, df_legalities, on='uuid', suffixes=('_card', '_legality'))\n\nbanned_white_border_cards = merged_df[\n (merged_df['status'] == 'Banned') & \n (merged_df['borderColor'] == 'white')\n]\n\nresult_count = banned_white_border_cards['id_card'].nunique()\nresult = pd.DataFrame({'count': [result_count]})", "sql": "SELECT COUNT(DISTINCT T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.status = 'Banned' AND T1.borderColor = 'white'", "difficulty": "simple" }, { "question_id": 384, "question": "List down the uuid for legacy cards and the foreign language of these cards.", "db_id": "card_games", "evidence": "legacy card refers to format = 'legacy'; foreign language refers to language in foreign_data", "code": "import pandas as pd\n\n# Filter legalities for legacy format\nlegacy_cards = legalities[legalities['format'] == 'legacy']\n\n# Merge with cards table\nmerged = pd.merge(legacy_cards[['uuid']], cards[['uuid']], on='uuid')\n\n# Merge with foreign_data to get languages\nresult = pd.merge(merged, foreign_data[['uuid', 'language']], on='uuid')\n\n# Select only uuid and language columns\nresult = result[['uuid', 'language']]", "sql": "SELECT T1.uuid, T3.language FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid INNER JOIN foreign_data AS T3 ON T1.uuid = T3.uuid WHERE T2.format = 'legacy'", "difficulty": "simple" }, { "question_id": 385, "question": "Write down the ruling of Beacon of Immortality.", "db_id": "card_games", "evidence": "Beacon of Immortality' is the name of card;", "code": "import pandas as pd\nfiltered_cards = cards[cards['name'] == 'Beacon of Immortality']\nmerged = pd.merge(filtered_cards[['uuid']], rulings, on='uuid')\nresult = merged[['text']]", "sql": "SELECT T2.text FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Beacon of Immortality'", "difficulty": "simple" }, { "question_id": 386, "question": "How many cards are having future frame version and what are the legality status of these cards?", "db_id": "card_games", "evidence": "future frame version refers to frameVersion = 'future'; legility status refers to status = 'legal';", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['frameVersion'] == 'future'], legalities, on='uuid')\nresult = merged.groupby('status', as_index=False).size().rename(columns={'size': 'card_count'})", "sql": "SELECT T2.status, COUNT(T1.id) AS card_count FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.frameVersion = 'future' GROUP BY T2.status", "difficulty": "simple" }, { "question_id": 387, "question": "What are the cards for set OGW? State the colour for these cards.", "db_id": "card_games", "evidence": "set OGW refers to setCode = 'OGW';", "code": "import pandas as pd\nresult = cards[cards['setCode'] == 'OGW'][['id', 'colors']]", "sql": "SELECT id, colors FROM cards WHERE setCode = 'OGW'", "difficulty": "simple" }, { "question_id": 388, "question": "What are the cards in set 10E with converted mana of 5 have translation and what are the languages?", "db_id": "card_games", "evidence": "set 10E refers to setCode = '10E'; converted mana of 5 refers to convertedManaCost = 5;", "code": "import pandas as pd\\n\\n# 读取数据\\ncards = pd.read_csv('../card_games/cards.csv')\\nforeign_data = pd.read_csv('../card_games/foreign_data.csv')\\n\\n# 筛选10E系列中法术力值为5的卡牌\\ntarget_cards = cards[\\n (cards['setCode'] == '10E') &\\n (cards['convertedManaCost'] == 5.0)\\n]\\n\\n# 使用INNER JOIN匹配SQL逻辑\\ncombined_data = pd.merge(\\n target_cards,\\n foreign_data,\\n on='uuid',\\n how='inner', # 改为inner join\\n suffixes=('_card', '_foreign')\\n)\\n\\n# 选择需要的列\\nresult = combined_data[['name_card', 'language']].copy()\\nresult = result.rename(columns={'name_card': 'name'})", "sql": "SELECT c.name, f.language FROM cards c JOIN foreign_data f ON c.uuid = f.uuid WHERE c.setCode = '10E' AND c.convertedManaCost = 5", "difficulty": "simple" }, { "question_id": 389, "question": "List down the name of cards with original types of Creature - Elf and the date of rulings for these cards.", "db_id": "card_games", "evidence": "Creature - Elf is the originalType;", "code": "import pandas as pd\nresult = pd.merge(cards, rulings, on='uuid').query(\"originalType == 'Creature - Elf'\")[['name', 'date']]", "sql": "SELECT T1.name, T2.date FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE T1.originalType = 'Creature - Elf'", "difficulty": "simple" }, { "question_id": 390, "question": "What are the colors of cards from ID 1-20? What are the format of these cards?", "db_id": "card_games", "evidence": "ID 1-20 refers to id BETWEEN 1 and 20;", "code": "import pandas as pd\n\n# Filter cards with ID between 1 and 20\nfiltered_cards = cards[(cards['id'] >= 1) & (cards['id'] <= 20)]\n\n# Left join with legalities table\nresult = pd.merge(filtered_cards[['id', 'uuid', 'colors']], legalities[['uuid', 'format']], on='uuid', how='left')\n\n# Select only colors and format columns\nresult = result[['colors', 'format']]", "sql": "SELECT T1.colors, T2.format FROM cards AS T1 LEFT JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.id BETWEEN 1 AND 20", "difficulty": "simple" }, { "question_id": 391, "question": "Among the Artifact cards, which are black color and comes with foreign languague translation?", "db_id": "card_games", "evidence": "Artifact card refers to originalType = 'Artifact'; black color refers to colors = 'B'; foreign language refers to language in foreign_data", "code": "import pandas as pd\n\ndef solve_query(cards_df, foreign_data_df):\n # Check if necessary columns exist\n if 'originalType' not in cards_df.columns or 'colors' not in cards_df.columns or 'uuid' not in cards_df.columns:\n return pd.DataFrame({'name': []})\n\n if 'uuid' not in foreign_data_df.columns or 'language' not in foreign_data_df.columns:\n return pd.DataFrame({'name': []})\n\n # Filter cards with originalType = 'Artifact' and colors = 'B'\n artifact_black_cards = cards_df[(cards_df['originalType'] == 'Artifact') & (cards_df['colors'] == 'B')]\n\n # Merge with foreign_data on uuid\n merged_data = pd.merge(artifact_black_cards, foreign_data_df, on='uuid', how='inner')\n\n # Select distinct names\n result = merged_data['name'].drop_duplicates().reset_index(drop=True)\n\n return pd.DataFrame({'name': result})\n\n# Example function call\ncards_data = pd.DataFrame({\n 'uuid': ['1', '2', '3'],\n 'name': ['Card1', 'Card2', 'Card3'],\n 'originalType': ['Artifact', 'Creature', 'Artifact'],\n 'colors': ['B', 'W', 'B']\n})\n\nforeign_data_data = pd.DataFrame({\n 'uuid': ['1', '3'],\n 'language': ['French', 'Spanish']\n})\n\nresult = solve_query(cards_data, foreign_data_data)\nprint(result)", "sql": "SELECT DISTINCT T1.name FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.originalType = 'Artifact' AND T1.colors = 'B'", "difficulty": "moderate" }, { "question_id": 392, "question": "Pick 3 cards with rarity of uncommon, list down name these cards according to ascending order of it's ruling date.", "db_id": "card_games", "evidence": "uncommon refers to rarity = 'uncommon';", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nrulings_df = pd.read_csv('rulings.csv')\n\n# Join the cards and rulings DataFrames on 'uuid'\nmerged_df = pd.merge(cards_df, rulings_df, on='uuid', how='inner')\n\n# Filter for cards with rarity 'uncommon'\nfiltered_df = merged_df[merged_df['rarity'] == 'uncommon']\n\n# Group by card name and get the minimum ruling date for each card\nresult_df = filtered_df.groupby('name')['date'].min().reset_index()\n\n# Sort the DataFrame by the ruling date in ascending order\nsorted_df = result_df.sort_values(by='date', ascending=True)\n\n# Select the top 3 cards\nfinal_result = sorted_df.head(3)['name']\n\nprint(final_result)", "sql": "SELECT c.name FROM cards c JOIN rulings r ON c.uuid = r.uuid WHERE c.rarity = 'uncommon' GROUP BY c.name ORDER BY MIN(r.date) ASC LIMIT 3", "difficulty": "simple" }, { "question_id": 393, "question": "On how many cards designed by John Avon is its foil non-powerful?", "db_id": "card_games", "evidence": "John Avon refer to artist; foil poweful foils refers to cardKingdomId and cardKingdomFoildId is NOT NULL \n", "code": "import pandas as pd\nresult = cards[(cards['artist'] == 'John Avon') & (cards['cardKingdomId'].isnull() | cards['cardKingdomFoilId'].isnull())].shape[0]", "sql": "SELECT COUNT(id) FROM cards WHERE (cardKingdomId IS NULL OR cardKingdomFoilId IS NULL) AND artist = 'John Avon'", "difficulty": "simple" }, { "question_id": 394, "question": "How many white bordered cards are powerful?", "db_id": "card_games", "evidence": "white bordered cards refer to borderColor = 'white'; powerful cards refers to cardKingdomFoilId is not null AND cardKingdomId is not null (replace)", "code": "import pandas as pd\nresult = len(cards[(cards['borderColor'] == 'white') & (cards['cardKingdomId'].notna()) & (cards['cardKingdomFoilId'].notna())])", "sql": "SELECT COUNT(id) FROM cards WHERE borderColor = 'white' AND cardKingdomId IS NOT NULL AND cardKingdomFoilId IS NOT NULL", "difficulty": "simple" }, { "question_id": 395, "question": "How many cards designed by UDON and available in mtgo print type has a starting maximum hand size of -1?", "db_id": "card_games", "evidence": "UDON refer to artist; availabe in mtgo refers to availability = 'mtgo'; starting maximum hand size of -1 refers to hand = -1", "code": "import pandas as pd\nresult = len(cards[(cards['hand'] == '-1') & (cards['artist'] == 'UDON') & (cards['availability'] == 'mtgo')])", "sql": "SELECT COUNT(id) FROM cards WHERE hAND = '-1' AND artist = 'UDON' AND Availability = 'mtgo' ", "difficulty": "simple" }, { "question_id": 396, "question": "How many cards with a 1993 frame version and available on paper have a sensitive content warning?", "db_id": "card_games", "evidence": "hasContentWarning equals 1 in the database; availability equals 'paper' in the database;", "code": "import pandas as pd\nresult = len(cards[(cards['frameVersion'] == '1993') & (cards['availability'] == 'paper') & (cards['hasContentWarning'] == 1)])", "sql": "SELECT COUNT(id) FROM cards WHERE frameVersion = '1993' AND availability = 'paper' AND hasContentWarning = 1", "difficulty": "simple" }, { "question_id": 397, "question": "What is the mana cost of cards with a normal layout, a 2003 frame version, with a black border color, and available in paper and mtgo?", "db_id": "card_games", "evidence": "available in paper and mtgo refers to availability = 'mtgo,paper'; frameVersion = 2003;borderColor = 'black'", "code": "import pandas as pd\nresult = cards[(cards['availability'] == 'mtgo,paper') & (cards['borderColor'] == 'black') & (cards['frameVersion'] == 2003) & (cards['layout'] == 'normal')]['manaCost']", "sql": "SELECT manaCost FROM cards WHERE availability = 'mtgo,paper' AND borderColor = 'black' AND frameVersion = 2003 AND layout = 'normal'", "difficulty": "moderate" }, { "question_id": 398, "question": "What is the unconverted mana do all the cards created by Rob Alexander cost in total?", "db_id": "card_games", "evidence": "unconverted mana refer to manaCost; Rob Alexander refer to artist", "code": "import pandas as pd\nimport numpy as np\n\n# Filter cards created by Rob Alexander\nrob_alexander_cards = cards[cards['artist'] == 'Rob Alexander']\n\n# Calculate the sum of convertedManaCost\nresult = rob_alexander_cards['convertedManaCost'].sum()", "sql": "SELECT SUM(CAST(REPLACE(manaCost, '{', '') AS REAL)) FROM cards WHERE artist = 'Rob Alexander' AND manaCost IS NOT NULL", "difficulty": "simple" }, { "question_id": 399, "question": "Lists all types of cards available in arena.", "db_id": "card_games", "evidence": "availability equals 'arena' in the database;availability is a comma-separated string indicating platforms; to check if 'arena' is present, use availability LIKE '%arena%'", "code": "import pandas as pd\nfiltered = cards[cards['availability'].str.contains('arena', na=False)]\nresult = filtered[filtered['types'].notnull()]['types'].drop_duplicates()", "sql": "SELECT DISTINCT types FROM cards WHERE availability = 'arena' AND types IS NOT NULL", "difficulty": "simple" }, { "question_id": 400, "question": "Lists the set code of all cards translated into Spanish.", "db_id": "card_games", "evidence": "Spanish refer to language; set code refers to setCode", "code": "import pandas as pd\nresult = set_translations[set_translations['language'] == 'Spanish']['setCode']", "sql": "SELECT setCode FROM set_translations WHERE language = 'Spanish'", "difficulty": "simple" }, { "question_id": 401, "question": "What percentage of legendary frame effect cards that are only available in online game variations?", "db_id": "card_games", "evidence": "isOnlineOnly equals 1 in the database; frameEffects equals 'legendary' in the database; count of isOnlineOnly=1; count of id;", "code": "import pandas as pd\n\n# Filter cards with legendary frame effect\nlegendary_cards = cards[cards['frameEffects'] == 'legendary']\n\n# Calculate percentage of online-only cards\ntotal_legendary = len(legendary_cards)\nonline_only_count = legendary_cards['isOnlineOnly'].sum()\npercentage = (online_only_count / total_legendary) * 100 if total_legendary > 0 else 0\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT SUM(CASE WHEN isOnlineOnly = 1 THEN 1.0 ELSE 0 END) / COUNT(id) * 100 FROM cards WHERE frameEffects = 'legendary'", "difficulty": "moderate" }, { "question_id": 402, "question": "What is the percentage of Story Spotlight cards that do not have a text box? List them by their ID.", "db_id": "card_games", "evidence": "Story Spotlight cards that do not have a text box refers to isStorylight = 1 and isTextless = 0; Percentage = DIVIDE(SUM(count(id) where isStorylight = 1 AND isTextless = 0 ), SUM(count(id))) * 100", "code": "import pandas as pd\nstoryspotlight_cards = cards[cards['isStorySpotlight'] == 1]\ntarget_cards = storyspotlight_cards[storyspotlight_cards['isTextless'] == 0]\npercentage = (len(target_cards) / len(storyspotlight_cards) * 100)\ncard_ids = ','.join(target_cards['id'].astype(int).astype(str))\nresult = pd.DataFrame({'percentage': [percentage], 'card_ids': [card_ids]})", "sql": "WITH target_cards AS (\n SELECT id \n FROM cards \n WHERE isStorySpotlight = 1 AND isTextless = 0\n)\nSELECT \n (CAST((SELECT COUNT(*) FROM target_cards) AS REAL) * 100 / COUNT(id)) AS percentage,\n GROUP_CONCAT(id) AS card_ids\nFROM cards\nWHERE isStorySpotlight = 1;", "difficulty": "moderate" }, { "question_id": 403, "question": "Calculate the percentage of cards in Spanish. List them by name.", "db_id": "card_games", "evidence": "language equals 'Spanish' in the database; count of id; sum of ID where language = 'Spanish';", "code": "import pandas as pd\n\n# Calculate percentage of Spanish cards\ntotal_count = len(foreign_data)\nspanish_count = len(foreign_data[foreign_data['language'] == 'Spanish'])\npercentage = (spanish_count / total_count) * 100\n\n# Get Spanish card names\nspanish_cards = foreign_data[foreign_data['language'] == 'Spanish'][['name']].copy()\nspanish_cards['percentage'] = percentage\n\nresult = spanish_cards", "sql": "SELECT \n (SELECT CAST(COUNT(DISTINCT f.uuid) AS REAL) * 100 / (SELECT COUNT(*) FROM cards) \n FROM foreign_data f WHERE f.language = 'Spanish'\n) AS percentage,\n c.name \nFROM foreign_data f\nJOIN cards c ON f.uuid = c.uuid\nWHERE f.language = 'Spanish'\nGROUP BY c.name", "difficulty": "simple" }, { "question_id": 404, "question": "Indicates the name of all the languages into which the set whose number of cards is 309 is translated.", "db_id": "card_games", "evidence": "set refer to setCode; number of cards refers to baseSetSize; baseSetsize = 309\n\n", "code": "import pandas as pd\nfiltered_sets = sets[sets['baseSetSize'] == 309]\nmerged = pd.merge(filtered_sets, set_translations, left_on='code', right_on='setCode')\nresult = merged[['language']]", "sql": "SELECT T2.language FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T1.baseSetSize = 309", "difficulty": "simple" }, { "question_id": 405, "question": "How many Brazilian Portuguese translated sets are inside the Commander block?", "db_id": "card_games", "evidence": "block equals 'Commander' in the database; language equals 'Portuguese (Brasil)' in the database;", "code": "import pandas as pd\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\nfiltered = merged[(merged['language'] == 'Portuguese (Brazil)') & (merged['block'] == 'Commander')]\nresult = filtered.shape[0]", "sql": "SELECT COUNT(T1.id) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T2.language = 'Portuguese (Brazil)' AND T1.block = 'Commander'", "difficulty": "moderate" }, { "question_id": 406, "question": "Lists by ID all Creature-type cards with legal status.", "db_id": "card_games", "evidence": "status equals 'legal' in the database; types equals 'Creature' in the database;", "code": "import pandas as pd\n\ndf_cards = pd.read_csv('cards.csv')\ndf_legalities = pd.read_csv('legalities.csv')\n\ncreature_cards = df_cards[df_cards['types'] == 'Creature']\nlegal_cards = df_legalities[df_legalities['status'] == 'Legal']\n\nmerged_df = pd.merge(creature_cards, legal_cards, on='uuid', suffixes=('_card', '_legality'))\n\nresult = merged_df[['id_card']].drop_duplicates().rename(columns={'id_card': 'id'}).sort_values(by='id')", "sql": "SELECT DISTINCT c.id FROM cards c JOIN legalities l ON c.uuid = l.uuid WHERE c.types = 'Creature' AND l.status = 'legal'", "difficulty": "simple" }, { "question_id": 407, "question": "Lists all types of cards in German.", "db_id": "card_games", "evidence": "German refer to language; all types refer to the subtypes, supertypes; subtypes is not null AND supertypes is not null", "code": "import pandas as pd\nmerged = pd.merge(cards, foreign_data, on='uuid')\nfiltered = merged[(merged['language'] == 'German') & (merged['subtypes'].notna()) & (merged['supertypes'].notna())]\nresult = filtered[['subtypes', 'supertypes']]", "sql": "SELECT T1.subtypes, T1.supertypes FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T2.language = 'German' AND T1.subtypes IS NOT NULL AND T1.supertypes IS NOT NULL", "difficulty": "moderate" }, { "question_id": 408, "question": "How many unknown power cards contain info about the triggered ability", "db_id": "card_games", "evidence": "unknown power cards refers to power is null or power = '*';contain info about the triggered ability refers to text contains 'triggered ability'", "code": "import pandas as pd\nresult = cards[(cards['power'].isnull() | (cards['power'] == '*')) & cards['text'].str.contains('triggered ability')].shape[0]", "sql": "SELECT COUNT(*) FROM cards AS T1 WHERE (T1.power IS NULL OR T1.power = '*') AND T1.text LIKE '%triggered ability%'", "difficulty": "moderate" }, { "question_id": 409, "question": "Indicates the number of cards with pre-modern format, ruling text \"This is a triggered mana ability.\" that do not have multiple faces.", "db_id": "card_games", "evidence": "pre-modern format refers to format = 'premodern' ;do not have multiple faces refers to side IS NULL", "code": "import pandas as pd\n\ndef solve_query(cards_df, legalities_df, rulings_df):\n # Ensure the necessary columns exist\n if not all(col in cards_df.columns for col in ['uuid', 'side']):\n return pd.DataFrame({'count': [0]})\n if not all(col in legalities_df.columns for col in ['uuid', 'format']):\n return pd.DataFrame({'count': [0]})\n if not all(col in rulings_df.columns for col in ['uuid', 'text']):\n return pd.DataFrame({'count': [0]})\n\n # Filter legalities for 'premodern' format\n premodern_legalities = legalities_df[legalities_df['format'] == 'premodern']\n\n # Filter rulings for the specified text\n triggered_rulings = rulings_df[rulings_df['text'] == 'This is a triggered mana ability.']\n\n # Merge dataframes to align on uuid\n merged_data = pd.merge(cards_df, premodern_legalities, on='uuid', how='inner')\n merged_data = pd.merge(merged_data, triggered_rulings, on='uuid', how='inner')\n\n # Filter for cards that do not have multiple faces (side IS NULL)\n filtered_data = merged_data[merged_data['side'].isnull()]\n\n # Count the number of matching cards\n result_count = filtered_data['id'].nunique()\n\n return pd.DataFrame({'count': [result_count]})\n\n# Example function call with placeholder DataFrames\ncards = pd.DataFrame(columns=['id', 'uuid', 'side'])\nlegalities = pd.DataFrame(columns=['uuid', 'format'])\nrulings = pd.DataFrame(columns=['uuid', 'text'])\n\nresult = solve_query(cards, legalities, rulings)\nprint(result)", "sql": "SELECT COUNT(T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid INNER JOIN rulings AS T3 ON T1.uuid = T3.uuid WHERE T2.format = 'premodern' AND T3.text = 'This is a triggered mana ability.' AND T1.Side IS NULL", "difficulty": "moderate" }, { "question_id": 410, "question": "Is there any card from Erica Yang artist in pauper format and available in paper? If so, indicate its ID.", "db_id": "card_games", "evidence": "availability equals 'paper' in the database;", "code": "import pandas as pd\n\ncards = pd.read_csv('cards.csv')\nlegalities = pd.read_csv('legalities.csv')\n\nmerged_df = pd.merge(cards, legalities, on='uuid')\nfiltered_df = merged_df[(merged_df['artist'] == 'Erica Yang') & (merged_df['format'] == 'pauper') & (merged_df['availability'] == 'paper')]\nresult = filtered_df[['id_x']]\nprint(result)", "sql": "SELECT T1.id FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.artist = 'Erica Yang' AND T2.format = 'pauper' AND T1.availability = 'paper'", "difficulty": "simple" }, { "question_id": 411, "question": "To which artist does the card with the text \"Das perfekte Gegenmittel zu einer dichten Formation\" belong?", "db_id": "card_games", "evidence": "flavorText in foreign_data refers to flavorText in cards; language in foreign_data refers to the language of flavorText", "code": "import pandas as pd\nmerged = pd.merge(cards, foreign_data, on='uuid')\nfiltered = merged[merged['flavorText_y'].str.contains(\"Das perfekte Gegenmittel zu einer dichten Formation\") & (merged['language'] == 'German')]\nresult = filtered[['artist']].drop_duplicates()", "sql": "SELECT DISTINCT T1.artist FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T2.flavorText LIKE '%Das perfekte Gegenmittel zu einer dichten Formation%' AND T2.language = 'German'", "difficulty": "simple" }, { "question_id": 412, "question": "What is the foreign name of the card in French of type Creature, normal layout and black border color, by artist Matthew D. Wilson?", "db_id": "card_games", "evidence": "in French refers to language = 'French'; black border color refers to borderColor = 'black'", "code": "import pandas as pd\n\n# Filter cards based on criteria\nfiltered_cards = cards[(cards['types'] == 'Creature') & \n (cards['layout'] == 'normal') & \n (cards['borderColor'] == 'black') & \n (cards['artist'] == 'Matthew D. Wilson')]\n\n# Get the uuids of filtered cards\nfiltered_uuids = filtered_cards['uuid'].tolist()\n\n# Filter foreign_data for French translations of these cards\nresult = foreign_data[(foreign_data['language'] == 'French') & \n (foreign_data['uuid'].isin(filtered_uuids))][['name']]", "sql": "SELECT fd.name FROM foreign_data fd WHERE fd.language = 'French' AND fd.uuid IN (SELECT c.uuid FROM cards c WHERE c.types = 'Creature' AND c.layout = 'normal' AND c.borderColor = 'black' AND c.artist = 'Matthew D. Wilson')", "difficulty": "moderate" }, { "question_id": 413, "question": "How many cards with print rarity have ruling text printed on 01/02/2007?", "db_id": "card_games", "evidence": "with print rarity refers to rarity = 'rare'; on 01/02/2007 refers to date = '2007-02-01'", "code": "import pandas as pd\n\ncards = pd.read_csv('cards.csv')\nrulings = pd.read_csv('rulings.csv')\n\nmerged_df = pd.merge(cards, rulings, on='uuid')\nfiltered_df = merged_df[(merged_df['rarity'] == 'rare') & (merged_df['date'] == '2007-02-01')]\nresult = len(filtered_df['id_x'].unique())\n\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.id) FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE T1.rarity = 'rare' AND T2.date = '2007-02-01'", "difficulty": "simple" }, { "question_id": 414, "question": "What language is the set of 180 cards that belongs to the Ravnica block translated into?", "db_id": "card_games", "evidence": "baseSetSize equals 180 in the database;", "code": "import pandas as pd\nfiltered_sets = sets[(sets['block'] == 'Ravnica') & (sets['baseSetSize'] == 180)]\nmerged = pd.merge(filtered_sets, set_translations, left_on='code', right_on='setCode')\nresult = merged[['language']]", "sql": "SELECT T2.language FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T1.block = 'Ravnica' AND T1.baseSetSize = 180", "difficulty": "simple" }, { "question_id": 415, "question": "What percentage of cards with format commander and legal status do not have a content warning?", "db_id": "card_games", "evidence": "do not have a content warning refers to hasContentWarning = 0; percentage refers to DIVIDE(COUNT(hasContentWarning = 0),COUNT(ID))*100 where format = 'commander' AND Status = 'legal';", "code": "import pandas as pd\nmerged = pd.merge(cards, legalities, on='uuid')\nfiltered = merged[(merged['format'] == 'commander') & (merged['status'] == 'Legal')]\nno_warning_count = (filtered['hasContentWarning'] == 0).sum()\ntotal_count = len(filtered)\nresult = (no_warning_count / total_count) * 100", "sql": "SELECT CAST(SUM(CASE WHEN T1.hasContentWarning = 0 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.format = 'commander' AND T2.status = 'Legal'", "difficulty": "challenging" }, { "question_id": 416, "question": "What percentage of cards without power are in French?", "db_id": "card_games", "evidence": "in French refers to language = 'French'; cards without power refers to power IS NULL OR power = '*'; percentage = DIVIDE(COUNT(language = 'French' and power is NULL or power = '*'), COUNT( power is NULL or power = '*'))*100", "code": "import pandas as pd\n\ncards = pd.read_csv('cards.csv')\nforeign_data = pd.read_csv('foreign_data.csv')\nmerged_data = pd.merge(cards, foreign_data, on='uuid', how='inner')\nfiltered_data = merged_data[(merged_data['power'].isnull()) | (merged_data['power'] == '*')]\ntotal_count = len(filtered_data)\nfrench_count = len(filtered_data[filtered_data['language'] == 'French'])\npercentage = (french_count / total_count) * 100 if total_count > 0 else 0\nresult = pd.DataFrame({'percentage': [percentage]})\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN T2.language = 'French' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.id) FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.power IS NULL OR T1.power = '*'", "difficulty": "challenging" }, { "question_id": 417, "question": "What percentage of Japanese translated sets are expansion sets?", "db_id": "card_games", "evidence": "Japanese translated refers to language = 'Japanese'; expansion sets refers to type = 'expansion'; percentage = DIVIDE(COUNT(language = 'Japanese'),COUNT(language))*100percentage = DIVIDE(COUNT(language = 'Japanese' AND type = 'expansion'), COUNT(language = 'Japanese')) * 100", "code": "import pandas as pd\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode', how='left')\nfiltered = merged[merged['type'] == 'expansion']\njapanese_count = filtered[filtered['language'] == 'Japanese']['code'].nunique()\ntotal_count = filtered['code'].nunique()\nresult = (japanese_count / total_count) * 100", "sql": "SELECT (COUNT(DISTINCT CASE WHEN T2.language = 'Japanese' THEN T1.code END) * 100.0) / COUNT(DISTINCT T1.code) FROM sets AS T1 LEFT JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T1.type = 'expansion'", "difficulty": "moderate" }, { "question_id": 418, "question": "What kind of printing is on the card that Daren Bader created?", "db_id": "card_games", "evidence": "kind of printing refers to availability; Daren Bader created refers to artist = 'Daren Bader'", "code": "import pandas as pd\nresult = cards[cards['artist'] == 'Daren Bader']['availability'].drop_duplicates()", "sql": "SELECT DISTINCT availability FROM cards WHERE artist = 'Daren Bader'", "difficulty": "simple" }, { "question_id": 419, "question": "How many color cards with no borders have been ranked higher than 12000 on EDHRec?", "db_id": "card_games", "evidence": "color cards with no borders refers to borderColor = 'borderless'; ranked higher than 12000 on EDHRec refers to edhrecRank > 12000", "code": "import pandas as pd\nimport numpy as np\n\n# Filter cards with borderColor = 'borderless' and edhrecRank > 12000\nfiltered_cards = cards[(cards['borderColor'] == 'borderless') & (cards['edhrecRank'] > 12000)]\n\n# Count the number of cards\nresult = len(filtered_cards)", "sql": "SELECT COUNT(id) FROM cards WHERE edhrecRank > 12000 AND borderColor = 'borderless'", "difficulty": "simple" }, { "question_id": 420, "question": "How many cards are oversized, reprinted, and printed for promotions?", "db_id": "card_games", "evidence": "are oversized refers to isOversized = 1; reprinted refers to isReprint = 1; printed for promotions refers to isPromo = 1", "code": "import pandas as pd\nresult = len(cards[(cards['isOversized'] == 1) & (cards['isReprint'] == 1) & (cards['isPromo'] == 1)])", "sql": "SELECT COUNT(id) FROM cards WHERE isOversized = 1 AND isReprint = 1 AND isPromo = 1", "difficulty": "simple" }, { "question_id": 421, "question": "Please list top three unknown power cards that have promotional types for arena league in alphabetical order.", "db_id": "card_games", "evidence": "unknown power cards refers to power is null or power = '*'; promotional types for arena league refers to promoTypes = 'arenaleague'", "code": "import pandas as pd\nfiltered = cards[(cards['power'].isna() | (cards['power'] == '*')) & (cards['promoTypes'] == 'arenaleague')]\nresult = filtered[['name']].sort_values('name').head(3)", "sql": "SELECT name FROM cards WHERE (power IS NULL OR power = '*') AND promoTypes = 'arenaleague' ORDER BY name LIMIT 3", "difficulty": "simple" }, { "question_id": 422, "question": "What is the language of the card with the multiverse number 149934?", "db_id": "card_games", "evidence": "multiverse number 149934 refers to multiverseid = 149934;", "code": "import pandas as pd\nresult = foreign_data[foreign_data['multiverseid'] == 149934]['language']", "sql": "SELECT language FROM foreign_data WHERE multiverseid = 149934", "difficulty": "simple" }, { "question_id": 423, "question": "Please provide the ids of top three powerful pairs of Kingdom Foil and Kingdom Cards sorted by Kingdom Foil id in alphabetical order.", "db_id": "card_games", "evidence": "poweful refers to cardKingdomFoilId is not null AND cardKingdomId is not null", "code": "import pandas as pd\nfiltered = cards[(cards['cardKingdomFoilId'].notna()) & (cards['cardKingdomId'].notna())]\nsorted_cards = filtered.sort_values('cardKingdomFoilId')\nresult = sorted_cards[['cardKingdomFoilId', 'cardKingdomId']].head(3)", "sql": "SELECT cardKingdomFoilId, cardKingdomId FROM cards WHERE cardKingdomFoilId IS NOT NULL AND cardKingdomId IS NOT NULL ORDER BY cardKingdomFoilId LIMIT 3", "difficulty": "simple" }, { "question_id": 424, "question": "What proportion of cards do not have a text box with a normal layout?", "db_id": "card_games", "evidence": "do not have a text box refers to isTextless = 1; proportion refers to DIVIDE(COUNT(Textless = 1 and layout = 'normal'),COUNT(Textless))*100proportion refers to DIVIDE(SUM(CASE WHEN isTextless = 1 AND layout = 'normal' THEN 1 ELSE 0 END), COUNT(*)) * 100", "code": "import pandas as pd\nmask = cards['layout'] == 'normal'\nresult = (cards.loc[mask, 'isTextless'].sum() / mask.sum()) * 100", "sql": "SELECT (CAST(SUM(CASE WHEN isTextless = 1 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*)) FROM cards WHERE layout = 'normal'", "difficulty": "simple" }, { "question_id": 425, "question": "What are the card numbers that don't have multiple faces on a single card and have the subtypes Angel and Wizard?", "db_id": "card_games", "evidence": "don't have multiple faces on a single card side is null", "code": "import pandas as pd\nresult = cards[(cards['subtypes'].str.contains('Angel', na=False)) & (cards['subtypes'].str.contains('Wizard', na=False)) & (cards['side'].isna())]['number']", "sql": "SELECT number FROM cards WHERE subtypes LIKE '%Angel%' AND subtypes LIKE '%Wizard%' AND side IS NULL", "difficulty": "simple" }, { "question_id": 426, "question": "Please provide top three sets that don't appear in Magic: The Gathering Online, along with their names in in alphabetical order.", "db_id": "card_games", "evidence": "mtgoCode is NULL in the database;", "code": "import pandas as pd\n\n# Read the CSV file\ndf_sets = pd.read_csv('sets.csv')\n\n# Filter for sets where mtgoCode is missing (NULL/NaN)\n# SQL: WHERE mtgoCode IS NULL\n# Note: In Pandas, SQL NULLs are loaded as NaN. checking == '' will fail.\nfiltered_sets = df_sets[df_sets['mtgoCode'].isna()]\n\n# Sort by name in alphabetical order\n# SQL: ORDER BY name\nsorted_sets = filtered_sets.sort_values(by='name', ascending=True)\n\n# Select the top 3 and extract the 'name' column\n# SQL: LIMIT 3\nresult = sorted_sets.head(3)['name'].values.tolist()\n\nprint(result)", "sql": "SELECT name FROM sets WHERE mtgoCode IS NULL ORDER BY name LIMIT 3", "difficulty": "simple" }, { "question_id": 427, "question": "What languages are available in the set known as Archenemy on the magic card market and having the code ARC?", "db_id": "card_games", "evidence": "known as Archenemy refers to mcmName = 'Archenemy'; having the code ARC refers to setCode = 'ARC'", "code": "import pandas as pd\nmerged = pd.merge(sets[sets['mcmName'] == 'Archenemy'], set_translations[set_translations['setCode'] == 'ARC'], left_on='code', right_on='setCode')\nresult = merged[['language']]", "sql": "SELECT T2.language FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T1.mcmName = 'Archenemy' AND T2.setCode = 'ARC'", "difficulty": "moderate" }, { "question_id": 428, "question": "What is the name of set number 5 and its translation?", "db_id": "card_games", "evidence": "id equals 5 in the database;", "code": "import pandas as pd\nsets_df = pd.read_csv('sets.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\nfiltered_set_translations_df = set_translations_df[set_translations_df['id'] == 5]\nif not filtered_set_translations_df.empty:\n merged_df = pd.merge(filtered_set_translations_df, sets_df, left_on='setCode', right_on='code', how='left')\n result = merged_df[['name', 'translation']]\nelse:\n result = pd.DataFrame(columns=['name', 'translation'])\nresult = result.reset_index(drop=True)", "sql": "SELECT T1.name, T2.translation FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T2.id = 5 GROUP BY T1.name, T2.translation", "difficulty": "simple" }, { "question_id": 429, "question": "What is the language and expansion type of set number 206?", "db_id": "card_games", "evidence": "id equals 206 in the database;", "code": "import pandas as pd\n\n# Merge sets and set_translations tables\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\n\n# Filter for id = 206\nfiltered = merged[merged['id_y'] == 206]\n\n# Select language and type columns\nresult = filtered[['language', 'type']]", "sql": "SELECT T2.language, T1.type FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode WHERE T1.id = 206", "difficulty": "simple" }, { "question_id": 430, "question": "Please list top two sets of cards with their IDs that have Italian-language cards and are located in the Shadowmoor block in alphabetical order.", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\nmerged_sets_cards = pd.merge(sets, cards, left_on='code', right_on='setCode')\nmerged_all = pd.merge(merged_sets_cards, foreign_data, on='uuid')\nfiltered = merged_all[(merged_all['block'] == 'Shadowmoor') & (merged_all['language'] == 'Italian')]\nunique_sets = filtered[['id_x', 'name_x']].drop_duplicates().rename(columns={'id_x': 'id', 'name_x': 'name'})\nsorted_sets = unique_sets.sort_values('name')\nresult = sorted_sets.head(2)", "sql": "SELECT T1.name, T1.id FROM sets AS T1 INNER JOIN cards AS T2 ON T1.code = T2.setCode INNER JOIN foreign_data AS T3 ON T2.uuid = T3.uuid WHERE T1.block = 'Shadowmoor' AND T3.language = 'Italian' GROUP BY T1.id ORDER BY T1.name LIMIT 2", "difficulty": "simple" }, { "question_id": 431, "question": "Which set is not available outside of the United States and has foil cards with Japanese writing on them? Please include the set ID in your response.", "db_id": "card_games", "evidence": "available outside of the United States refers to isForeignOnly = 1; has foil cards refers to isFoilOnly = 1; with Japanese writing on them refers to language = 'Japanese'", "code": "import pandas as pd\nmerged_sets_cards = pd.merge(sets, cards, left_on='code', right_on='setCode')\nmerged_all = pd.merge(merged_sets_cards, foreign_data, on='uuid')\nfiltered = merged_all[(merged_all['isForeignOnly'] == 0) & (merged_all['isFoilOnly'] == 1) & (merged_all['language'] == 'Japanese')]\nresult = filtered[['name', 'code']].drop_duplicates()", "sql": "SELECT DISTINCT sets.name, sets.code AS id FROM sets JOIN cards ON sets.code = cards.setCode JOIN foreign_data ON cards.uuid = foreign_data.uuid WHERE sets.isForeignOnly = 0 AND sets.isFoilOnly = 1 AND foreign_data.language = 'Japanese'", "difficulty": "challenging" }, { "question_id": 432, "question": "Which Russian set of cards contains the most cards overall?", "db_id": "card_games", "evidence": "Russian refers to language = 'Russian'; contains the most cards overall refers to MAX(baseSetSize)", "code": "import pandas as pd\nmerged_sc = pd.merge(sets, cards, left_on='code', right_on='setCode')\nmerged_all = pd.merge(merged_sc, foreign_data, on='uuid')\nrussian = merged_all[merged_all['language'] == 'Russian']\ngrouped = russian.groupby('code')['id_y'].nunique().reset_index(name='count')\nresult = grouped.loc[grouped['count'].idxmax()]['code']", "sql": "SELECT sets.code FROM sets JOIN cards ON sets.code = cards.setCode JOIN foreign_data ON cards.uuid = foreign_data.uuid WHERE foreign_data.language = 'Russian' GROUP BY sets.code ORDER BY COUNT(DISTINCT cards.id) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 433, "question": "What is the percentage of the set of cards that have Chinese Simplified as the language and are only available for online games?", "db_id": "card_games", "evidence": "are only available for online games refers to isOnlineOnly = 1; percentage = DIVIDE(COUNT(isOnlineOnly = 1),COUNT(isOnlineOnly))*100language refers to T2.language in set_translations; isOnlineOnly refers to T1.isOnlineOnly in sets; percentage = DIVIDE(SUM(CASE WHEN T2.language = 'Chinese Simplified' AND T1.isOnlineOnly = 1 THEN 1 ELSE 0 END), COUNT(*)) * 100", "code": "import pandas as pd\n\n# Read the necessary CSV files\nsets_df = pd.read_csv('sets.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\n\n# Merge the sets and set_translations DataFrames on the setCode column\nmerged_df = pd.merge(sets_df, set_translations_df, left_on='code', right_on='setCode')\n\n# Filter the DataFrame to include only rows where the language is 'Chinese Simplified'\nchinese_simplified_df = merged_df[merged_df['language'] == 'Chinese Simplified']\n\n# Calculate the percentage of sets that are only available for online games\npercentage_online_only = (chinese_simplified_df['isOnlineOnly'].sum() / len(chinese_simplified_df)) * 100\n\n# Record the final result\nresult = percentage_online_only\n\n# Print the final result\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN T2.language = 'Chinese Simplified' AND T1.isOnlineOnly = 1 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.code = T2.setCode", "difficulty": "moderate" }, { "question_id": 434, "question": "How many sets are available just in Japanese and not in Magic: The Gathering Online?", "db_id": "card_games", "evidence": "Japanese refers to language = 'Japanese'; not in Magic: The Gathering Online refers to mtgoCode is null or mtgoCode = ''", "code": "import pandas as pd\n\nsets = pd.read_csv('sets.csv')\nset_translations = pd.read_csv('set_translations.csv')\n\nmerged_df = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\nfiltered_df = merged_df[(merged_df['language'] == 'Japanese') & (merged_df['mtgoCode'].isnull() | (merged_df['mtgoCode'] == ''))]\nresult = len(filtered_df)\n\nprint(result)", "sql": "SELECT COUNT(T1.id) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T2.language = 'Japanese' AND (T1.mtgoCode IS NULL OR T1.mtgoCode = '')", "difficulty": "moderate" }, { "question_id": 435, "question": "How many card border with black color ? List out the card id.", "db_id": "card_games", "evidence": "borderColor equals 'black' in the database;", "code": "import pandas as pd\n# 假设cards DataFrame已存在\nresult = cards[cards['borderColor'] == 'black']['id']", "sql": "SELECT id FROM cards WHERE borderColor = 'black'", "difficulty": "simple" }, { "question_id": 436, "question": "How many cards have frame effect as extendedart? List out the id of those cards.", "db_id": "card_games", "evidence": "frameEffects equals 'extendedart' in the database;", "code": "import pandas as pd\nfiltered_cards = cards[cards['frameEffects'] == 'extendedart']\ncount = len(filtered_cards)\nids = filtered_cards[['id']]\nresult = ids", "sql": "SELECT id FROM cards WHERE frameEffects = 'extendedart' GROUP BY id", "difficulty": "simple" }, { "question_id": 437, "question": "Among black card borders, which card has full artwork?", "db_id": "card_games", "evidence": "white card borders refers to borderColor = 'white'; has full artwork refers to isFullArt = 1", "code": "import pandas as pd\nresult = cards[(cards['borderColor'] == 'black') & (cards['isFullArt'] == 1)][['id']]", "sql": "SELECT id FROM cards WHERE borderColor = 'black' AND isFullArt = 1", "difficulty": "simple" }, { "question_id": 438, "question": "Point out the language of set translation id \"174\"?", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV file\ndf_set_translations = pd.read_csv('set_translations.csv')\n\n# Filter set_translations table directly by its primary key ID\n# Logic matches Gold SQL: SELECT language FROM set_translations WHERE id = 174\n# The question \"set id 174\" refers to the record ID in the translation table\ntarget_translation = df_set_translations[df_set_translations['id'] == 174]\n\n# Extract the language\nif not target_translation.empty:\n result = target_translation.iloc[0]['language']\nelse:\n result = None\n\nprint(result)", "sql": "SELECT language FROM set_translations WHERE id = 174", "difficulty": "simple" }, { "question_id": 439, "question": "List out the set name of the set code \"ALL\".", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\nresult = sets[sets['code'] == 'ALL'][['name']]", "sql": "SELECT name FROM sets WHERE code = 'ALL'", "difficulty": "simple" }, { "question_id": 440, "question": "Which foreign language used by \"A Pedra Fellwar\"?", "db_id": "card_games", "evidence": "name equals 'A Pedra Fellwar' in the database;name in foreign_data refers to localized card name", "code": "import pandas as pd\nresult = foreign_data[foreign_data['name'] == 'A Pedra Fellwar']['language'].drop_duplicates()", "sql": "SELECT DISTINCT language FROM foreign_data WHERE name = 'A Pedra Fellwar';", "difficulty": "simple" }, { "question_id": 441, "question": "State the set code of the set with release date of 07/13/2007?", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\nfiltered = sets[sets['releaseDate'] == '2007-07-13']\nresult = filtered['code']", "sql": "SELECT code FROM sets WHERE releaseDate = '2007-07-13'", "difficulty": "simple" }, { "question_id": 442, "question": "Mention the base set size and set code of the set that was in block named \"Masques\" and \"Mirage\".", "db_id": "card_games", "evidence": "block refers to the name of the block the set is part of", "code": "import pandas as pd\nresult = sets[sets['block'].isin(['Masques', 'Mirage'])][['baseSetSize', 'code']]", "sql": "SELECT baseSetSize, code FROM sets WHERE block IN ('Masques','Mirage')", "difficulty": "simple" }, { "question_id": 443, "question": "Give the code of sets have expansion type of 'expansion'?", "db_id": "card_games", "evidence": "code of sets refers to setCode", "code": "import pandas as pd\nresult = sets[sets['type'] == 'expansion']['code']", "sql": "SELECT code FROM sets WHERE type = 'expansion'", "difficulty": "simple" }, { "question_id": 444, "question": "Name the foreign name of the card that has boros watermark? List out the type of this card.", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(cards, foreign_data, on='uuid')\nfiltered = merged[merged['watermark'] == 'boros']\nresult = filtered[['name_y', 'type_x']].drop_duplicates()", "sql": "SELECT DISTINCT T2.name AS foreign_name, T1.type FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.watermark = 'boros';", "difficulty": "simple" }, { "question_id": 445, "question": "What is the language and flavor text of the card that has colorpie watermark? List out the type of this card.", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\n\ncards = pd.read_csv('cards.csv')\nforeign_data = pd.read_csv('foreign_data.csv')\n\nmerged_df = pd.merge(cards, foreign_data, on='uuid')\nfiltered_df = merged_df[merged_df['watermark'] == 'colorpie']\nresult = filtered_df[['language', 'flavorText_y', 'type_x']].drop_duplicates()\n\nprint(result)", "sql": "SELECT DISTINCT T2.language, T2.flavorText, T1.type FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.watermark = 'colorpie'", "difficulty": "simple" }, { "question_id": 446, "question": "What is percentage of the cards with a converted Mana Cost of 10 in set of Abyssal Horror?", "db_id": "card_games", "evidence": "set of Abyssal Horror refers to name = 'Abyssal Horror'; percentage refers to DIVIDE(COUNT(convertedManaCost = 16),COUNT(convertedManaCost))*100", "code": "import pandas as pd\n\n# Filter cards for 'Abyssal Horror'\nabyssal_cards = cards[cards['name'] == 'Abyssal Horror']\n\n# Get the setCode for Abyssal Horror\nif len(abyssal_cards) > 0:\n set_code = abyssal_cards['setCode'].iloc[0]\n \n # Get all cards from the same set\n set_cards = cards[cards['setCode'] == set_code]\n \n # Calculate percentage of cards with convertedManaCost = 10\n cards_with_cmc_10 = set_cards[set_cards['convertedManaCost'] == 10]\n percentage = (len(cards_with_cmc_10) / len(set_cards)) * 100 if len(set_cards) > 0 else 0\n \n result = pd.DataFrame({'percentage': [percentage], 'name': ['Abyssal Horror']})\nelse:\n result = pd.DataFrame({'percentage': [0], 'name': ['Abyssal Horror']})", "sql": "SELECT (CAST(SUM(CASE WHEN T1.convertedManaCost = 10 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.id)) AS percentage FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Abyssal Horror'", "difficulty": "moderate" }, { "question_id": 447, "question": "Give the code of sets have expansion commander type?", "db_id": "card_games", "evidence": "code of sets refers to setCode[\"expansion_commander_type corresponds_to type = 'commander'\"]", "code": "import pandas as pd\nresult = sets[sets['type'] == 'commander']['code']", "sql": "SELECT T1.code FROM sets AS T1 WHERE T1.type = 'commander'", "difficulty": "simple" }, { "question_id": 448, "question": "Name the foreign name of the card that has abzan watermark? List out the type of this card.", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\ncards = pd.read_csv('cards.csv', low_memory=False)\nforeign_data = pd.read_csv('foreign_data.csv', low_memory=False)\ndef solve_query(cards, foreign_data):\n merged_df = pd.merge(cards, foreign_data, on='uuid', how='inner')\n filtered_df = merged_df[merged_df['watermark'] == 'abzan']\n result_df = filtered_df[['name_x', 'type_x']].drop_duplicates()\n return result_df\n\n# 假设cards和foreign_data已加载为DataFrame\nresult = solve_query(cards, foreign_data)\nprint(result)", "sql": "SELECT DISTINCT T1.name, T1.type FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.watermark = 'abzan'", "difficulty": "simple" }, { "question_id": 449, "question": "What is the language of the card that has azorius watermark? List out the type of this card.", "db_id": "card_games", "evidence": "", "code": "import pandas as pd\n\n# Filter cards with azorius watermark\nazorius_cards = cards[cards['watermark'] == 'azorius']\n\n# Inner join with foreign_data\nmerged = pd.merge(azorius_cards, foreign_data, on='uuid', how='inner')\n\n# Select distinct language and type columns\nresult = merged[['language', 'type_x']].drop_duplicates()\nresult.columns = ['language', 'type']\nprint(result)", "sql": "SELECT DISTINCT T2.language, T1.type FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.watermark = 'azorius'", "difficulty": "simple" }, { "question_id": 450, "question": "Of all the cards that are designed by Aaron Miller, how many of them are incredibly powerful?", "db_id": "card_games", "evidence": "designed by Aaron Miller refers to artist = 'Aaron Miller'; are icredibily powerful refers to cardKingdomFoilId is not null AND cardKingdomId is not null", "code": "import pandas as pd\nresult = cards[(cards['artist'] == 'Aaron Miller') & (cards['cardKingdomFoilId'].notna()) & (cards['cardKingdomId'].notna())].shape[0]", "sql": "SELECT SUM(CASE WHEN artist = 'Aaron Miller' AND cardKingdomFoilId IS NOT NULL AND cardKingdomId IS NOT NULL THEN 1 ELSE 0 END) FROM cards", "difficulty": "moderate" }, { "question_id": 451, "question": "How many cards available in paper have a positive starting maximum hand size?", "db_id": "card_games", "evidence": "available in paper refers to availability like '%paper%'; have a positive starting maximum hand size refers to hand = '3'", "code": "import pandas as pd\nresult = len(cards[(cards['availability'].str.contains('paper', na=False)) & (cards['hand'] == '3')])", "sql": "SELECT SUM(CASE WHEN availability = 'paper' AND hAND = '3' THEN 1 ELSE 0 END) FROM cards", "difficulty": "simple" }, { "question_id": 452, "question": "Please list the names of the cards that have a text box.", "db_id": "card_games", "evidence": "isTextless equals 0 in the database;", "code": "import pandas as pd\nresult = cards[cards['isTextless'] == 0][['name']].drop_duplicates()", "sql": "SELECT DISTINCT name FROM cards WHERE isTextless = 0;", "difficulty": "simple" }, { "question_id": 453, "question": "What's the unconverted mana cost of the card \"Ancestor's Chosen\"?", "db_id": "card_games", "evidence": "name equals 'Ancestor`s Chosen' in the database;", "code": "import pandas as pd\n\n# Load the cards table\ncards_df = pd.read_csv('cards.csv')\n\n# Filter the row where the name is 'Ancestor's Chosen'\nancestor_chosen = cards_df[cards_df['name'] == \"Ancestor's Chosen\"]\n\n# Get the unconverted mana cost\nunconverted_mana_cost = ancestor_chosen['manaCost'].values[0]\n\n# Store the result\nresult = unconverted_mana_cost\n\n# Print the result\nprint(result)", "sql": "SELECT DISTINCT manaCost FROM cards WHERE name = 'Ancestor''s Chosen'", "difficulty": "simple" }, { "question_id": 454, "question": "Among the cards with a white border color, how many of them have unknown power?", "db_id": "card_games", "evidence": "power equals '*' in the database;", "code": "import pandas as pd\nresult = cards[(cards['borderColor'] == 'white') & (cards['power'] == '*')].shape[0]", "sql": "SELECT COUNT(*) FROM cards WHERE borderColor = 'white' AND power = '*'", "difficulty": "simple" }, { "question_id": 455, "question": "Which of the cards that are a promotional painting have multiple faces on the same card? Please list their names.", "db_id": "card_games", "evidence": "are a promotional painting refers to isPromo = 1; have multiple faces on the same card refers to side is not Null", "code": "import pandas as pd\nimport numpy as np\n\n# Filter cards that are promotional and have multiple faces\npromo_multiface = cards[(cards['isPromo'] == 1) & (cards['side'].notna())]\n\n# Get distinct names\nresult = promo_multiface[['name']].drop_duplicates()", "sql": "SELECT DISTINCT name FROM cards WHERE isPromo = 1 AND side IS NOT NULL", "difficulty": "simple" }, { "question_id": 456, "question": "What's the list of all types for the card \"Molimo, Maro-Sorcerer\"?", "db_id": "card_games", "evidence": "card \"Molimo, Maro-Sorcerer\" refers to name = 'Molimo, Maro-Sorcerer'; list of all types refers to subtypes,supertypes", "code": "import pandas as pd\nresult = cards[cards['name'] == 'Molimo, Maro-Sorcerer'][['subtypes', 'supertypes']].drop_duplicates()", "sql": "SELECT DISTINCT subtypes, supertypes FROM cards WHERE name = 'Molimo, Maro-Sorcerer'", "difficulty": "simple" }, { "question_id": 457, "question": "Please list the websites where I can purchase the cards that have the promotional type of \"bundle\".", "db_id": "card_games", "evidence": "promotional type of \"bundle\" refers to promoTypes = 'bundle'; websites refers to purchaseUrls", "code": "import pandas as pd\nresult = cards[cards['promoTypes'] == 'bundle']['purchaseUrls'].dropna().unique()", "sql": "SELECT DISTINCT purchaseUrls FROM cards WHERE promoTypes = 'bundle'", "difficulty": "simple" }, { "question_id": 458, "question": "How many artists have designed a card with a black border color and is available in both \"arena\" and \"mtgo\" printing type?", "db_id": "card_games", "evidence": "available in both \"arena\" and \"mtgo\" refers to availability like '%arena,mtgo%'count of distinct artists; availability like '%arena,mtgo%' and borderColor = 'black'", "code": "import pandas as pd\n# Filter cards with black border and dual availability\nfiltered = cards[(cards['borderColor'] == 'black') & \n (cards['availability'].str.contains('arena') & \n cards['availability'].str.contains('mtgo'))]\n# Calculate distinct artist count and format result\nresult = pd.DataFrame({'count': [filtered['artist'].nunique()]})", "sql": "SELECT COUNT(DISTINCT artist) FROM cards WHERE availability LIKE '%arena,mtgo%' AND borderColor = 'black'", "difficulty": "simple" }, { "question_id": 459, "question": "Which card costs more converted mana, \"Serra Angel\" or \"Shrine Keeper\"?", "db_id": "card_games", "evidence": "\"Serra Angel\" refers to name = 'Serra Angel'; \"Shrine Keeper\" refers to name = 'Shrine Keeper'; card costs more converted mana when the value of convertedManaCost is greater", "code": "import pandas as pd\nfiltered_cards = cards[cards['name'].isin(['Serra Angel', 'Shrine Keeper'])]\nresult = filtered_cards.sort_values('convertedManaCost', ascending=False).head(1)[['name']]", "sql": "SELECT name FROM cards WHERE name IN ('Serra Angel', 'Shrine Keeper') ORDER BY convertedManaCost DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 460, "question": "Which artist designed the card whose promotional name is \"Battra, Dark Destroyer\"?", "db_id": "card_games", "evidence": "flavorName equals 'Battra, Dark Destroyer' in the database;", "code": "import pandas as pd\n\ndf = pd.read_csv('cards.csv')\nresult = df[df['flavorName'] == 'Battra, Dark Destroyer'][['artist']]\nprint(result)", "sql": "SELECT artist FROM cards WHERE flavorName = 'Battra, Dark Destroyer';", "difficulty": "simple" }, { "question_id": 461, "question": "Please list the names of the top 3 cards with the highest converted mana cost and have a 2003 card frame style.", "db_id": "card_games", "evidence": "name of cards refers to name; 2003 card frame style refers to frameVersion = '2003'", "code": "import pandas as pd\nfiltered_cards = cards[cards['frameVersion'] == '2003']\nsorted_cards = filtered_cards.sort_values('convertedManaCost', ascending=False)\nresult = sorted_cards[['name']].head(3)", "sql": "SELECT name FROM cards WHERE frameVersion = '2003' ORDER BY convertedManaCost DESC LIMIT 3", "difficulty": "simple" }, { "question_id": 462, "question": "What's the Italian name of the set of cards with \"Ancestor's Chosen\" is in?", "db_id": "card_games", "evidence": "Italian is a language which refers to language = 'Italian'; with \"Ancestor's Chosen\" in the card set refers to name = 'Ancestor''s Chosen'", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\n\nfiltered_cards_df = cards_df[cards_df['name'] == \"Ancestor's Chosen\"]\nset_codes = filtered_cards_df['setCode'].drop_duplicates()\n\nresult = set_translations_df[\n (set_translations_df['setCode'].isin(set_codes)) &\n (set_translations_df['language'] == 'Italian')\n][['translation']]\n\nresult = result.drop_duplicates().reset_index(drop=True)", "sql": "SELECT translation FROM set_translations WHERE setCode IN (SELECT setCode FROM cards WHERE name = 'Ancestor''s Chosen') AND language = 'Italian'", "difficulty": "moderate" }, { "question_id": 463, "question": "How many translations are there for the set of cards with \"Angel of Mercy\" in it?", "db_id": "card_games", "evidence": "name equals 'Angel of Mercy' in the database;", "code": "import pandas as pd\ncards_df = pd.read_csv('cards.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\nfiltered_cards = cards_df[cards_df['name'] == 'Angel of Mercy']\nset_codes = set()\nfor printing in filtered_cards['printings']:\n if pd.notna(printing):\n codes = [code.strip('\"') for code in printing.split(',')]\n set_codes.update(codes)\nresult = set_translations_df[(set_translations_df['setCode'].isin(set_codes)) & (set_translations_df['translation'].notna())]['translation'].nunique()\nprint(result)", "sql": "SELECT COUNT(DISTINCT translation) FROM set_translations WHERE setCode IN ( SELECT DISTINCT TRIM(value) FROM cards, json_each('[\"' || REPLACE(printings, ',', '\",\"') || '\"]') WHERE name = 'Angel of Mercy' ) AND translation IS NOT NULL", "difficulty": "simple" }, { "question_id": 464, "question": "Please list the names of the cards in the set \"Hauptset Zehnte Edition\".", "db_id": "card_games", "evidence": "translation equals 'Hauptset Zehnte Edition' in the database;", "code": "import pandas as pd\nmerged = pd.merge(cards, set_translations, left_on='setCode', right_on='setCode')\nfiltered = merged[merged['translation'] == 'Hauptset Zehnte Edition']\nresult = filtered[['name']].drop_duplicates()", "sql": "SELECT DISTINCT T1.name FROM cards AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.setCode WHERE T2.translation = 'Hauptset Zehnte Edition'", "difficulty": "simple" }, { "question_id": 465, "question": "For the set of cards with \"Ancestor's Chosen\" in it, is there a Korean version of it?", "db_id": "card_games", "evidence": "set of cards with \"Ancestor''s Chosen\" in it refers to name = 'Ancestor''s Chosen'; Korean version refers to language = 'Korean'Korean version refers to language = 'Korean' and translation IS NOT NULL", "code": "import pandas as pd\nmerged = pd.merge(cards, foreign_data, on='uuid')\nmask = (merged['name_x'] == \"Ancestor's Chosen\") & (merged['language'] == 'Korean') & merged['text_y'].notnull()\nresult = 'YES' if mask.any() else 'NO'", "sql": "SELECT IIF(SUM(CASE WHEN T2.language = 'Korean' THEN 1 ELSE 0 END) > 0, 'YES', 'NO') AS has_korean_version FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Ancestor''s Chosen';", "difficulty": "moderate" }, { "question_id": 466, "question": "Among the cards in the set \"Hauptset Zehnte Edition\", how many of them are designed by Adam Rex?", "db_id": "card_games", "evidence": "card set \"Hauptset Zehnte Edition\" refers to translation = 'Hauptset Zehnte Edition'; designed by Adam refers to artist = 'Adam Rex'", "code": "import pandas as pd\nmerged = pd.merge(cards, set_translations, left_on='setCode', right_on='setCode')\nfiltered = merged[(merged['translation'] == 'Hauptset Zehnte Edition') & (merged['artist'] == 'Adam Rex')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM cards AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.setCode WHERE T2.translation = 'Hauptset Zehnte Edition' AND T1.artist = 'Adam Rex'", "difficulty": "moderate" }, { "question_id": 467, "question": "How many cards are there in the base set of \"Hauptset Zehnte Edition\"?", "db_id": "card_games", "evidence": "\"Hauptset Zehnte Edition\" refers to translation = 'Hauptset Zehnte Edition'; number of cards refers to baseSetSize", "code": "import pandas as pd\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\nfiltered = merged[merged['translation'] == 'Hauptset Zehnte Edition']\nresult = filtered[['baseSetSize']]", "sql": "SELECT T1.baseSetSize FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T2.translation = 'Hauptset Zehnte Edition'", "difficulty": "simple" }, { "question_id": 468, "question": "What is the Simplified Chinese translation of the name of the set \"Eighth Edition\"?", "db_id": "card_games", "evidence": "Eighth Edition is the name of card set which refers to name = 'Eighth Edition'; Simplified Chinese refers to language = 'Chinese Simplified'; translation of the name refers to translation", "code": "import pandas as pd\n\n# Merge sets and set_translations tables\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\n\n# Filter for Eighth Edition and Chinese Simplified\nfiltered = merged[(merged['name'] == 'Eighth Edition') & (merged['language'] == 'Chinese Simplified')]\n\n# Select translation column\nresult = filtered[['translation']]", "sql": "SELECT T2.translation FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T1.name = 'Eighth Edition' AND T2.language = 'Chinese Simplified'", "difficulty": "moderate" }, { "question_id": 469, "question": "Did the set of cards with \"Angel of Mercy\" appear on Magic: The Gathering Online?", "db_id": "card_games", "evidence": "card set \"Angel of Mercy\" refers to name = 'Angel of Mercy'; appear on Magic: The Gathering Online refers to mtgoCode is NOT NULL and vice versaappear on Magic: The Gathering Online refers to T2.mtgoCode IS NOT NULL and vice versa", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['name'] == 'Angel of Mercy'], sets[sets['mtgoCode'].notnull()], left_on='setCode', right_on='code')\nresult = 'YES' if not merged.empty else 'NO'", "sql": "SELECT CASE WHEN EXISTS (SELECT 1 FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T1.name = 'Angel of Mercy' AND T2.mtgoCode IS NOT NULL) THEN 'YES' ELSE 'NO' END", "difficulty": "moderate" }, { "question_id": 470, "question": "When was the set of cards with \"Ancestor's Chosen\" released?", "db_id": "card_games", "evidence": "card set \"Ancestor's Chosen\" refers to name = 'Ancestor''s Chosen'; when released refers to releaseDate", "code": "import pandas as pd\nfiltered_cards = cards[cards['name'] == \"Ancestor's Chosen\"]\nmerged = pd.merge(filtered_cards, sets, left_on='setCode', right_on='code')\nresult = merged[['releaseDate']].drop_duplicates()", "sql": "SELECT DISTINCT T2.releaseDate FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T1.name = 'Ancestor''s Chosen'", "difficulty": "simple" }, { "question_id": 471, "question": "What is the expansion type of the set \"Hauptset Zehnte Edition\"?", "db_id": "card_games", "evidence": "card set \"Hauptset Zehnte Edition\" refers to translation = ' Hauptset Zehnte Edition'; expansion type refers to type", "code": "import pandas as pd\nresult = pd.merge(sets, set_translations, left_on='code', right_on='setCode')[set_translations['translation'] == 'Hauptset Zehnte Edition'][['type']].iloc[0]['type']", "sql": "SELECT T1.type FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T2.translation = 'Hauptset Zehnte Edition'", "difficulty": "simple" }, { "question_id": 472, "question": "Among the sets in the block \"Ice Age\", how many of them have an Italian translation?", "db_id": "card_games", "evidence": "sets in the block \"Ice Age\" refers to block = 'Ice Age'; Italian translation refers to language = 'Italian' and translation is not null", "code": "import pandas as pd\n\nsets_df = pd.read_csv('sets.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\nmerged_df = pd.merge(sets_df, set_translations_df, left_on='code', right_on='setCode')\nresult = merged_df[(merged_df['block'] == 'Ice Age') & (merged_df['language'] == 'Italian') & (merged_df['translation'].notna())]['id_x'].nunique()\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.id) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T1.block = 'Ice Age' AND T2.language = 'Italian' AND T2.translation IS NOT NULL", "difficulty": "moderate" }, { "question_id": 473, "question": "Is the set of cards with Adarkar Valkyrie only available outside the United States?", "db_id": "card_games", "evidence": "card set Adarkar Valkyrie refers to name = 'Adarkar Valkyrie'; isForeignOnly = 1 means only available outside the United States;", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['name'] == 'Adarkar Valkyrie'], sets, left_on='setCode', right_on='code')\nresult = 'YES' if merged[merged['isForeignOnly'] != 1].empty else 'NO'", "sql": "SELECT IIF(COUNT(CASE WHEN T2.isForeignOnly != 1 THEN 1 END) = 0, 'YES', 'NO') FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T1.name = 'Adarkar Valkyrie'", "difficulty": "moderate" }, { "question_id": 474, "question": "Among the sets of cards that have an Italian translation, how many of them have a base set number of under 100?", "db_id": "card_games", "evidence": "Italian translation refers to language = 'Italian'; have a translation means translation is not null; base set number of under 100 refers to baseSetSize < 10", "code": "import pandas as pd\n\n# Merge sets with set_translations\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\n\n# Filter for Italian translations that are not null and baseSetSize < 100\nfiltered = merged[(merged['language'] == 'Italian') & (merged['translation'].notna()) & (merged['baseSetSize'] < 100)]\n\n# Count the number of sets\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T2.translation IS NOT NULL AND T1.baseSetSize < 100 AND T2.language = 'Italian'", "difficulty": "moderate" }, { "question_id": 475, "question": "How many cards in the set Coldsnap have a black border color?", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; black border color refers to borderColor = 'black'", "code": "import pandas as pd\n\ndef solve_query(cards_df, sets_df):\n # Check if required columns exist\n if 'setCode' not in cards_df.columns or 'code' not in sets_df.columns or 'name' not in sets_df.columns or 'borderColor' not in cards_df.columns:\n return 0\n\n # Filter the sets dataframe for name = 'Coldsnap'\n coldsnap_sets = sets_df[sets_df['name'] == 'Coldsnap']\n\n # Merge with cards dataframe on setCode and code\n merged_data = pd.merge(cards_df, coldsnap_sets, left_on='setCode', right_on='code', how='inner')\n\n # Filter for borderColor = 'black'\n black_border_cards = merged_data[merged_data['borderColor'] == 'black']\n\n # Return the count of matching cards\n return len(black_border_cards)\n\n# Example usage:\n# Assuming `cards` and `sets` are pandas DataFrames loaded from the database\ncards_data = pd.DataFrame({\n 'id': [1, 2, 3],\n 'setCode': ['CS1', 'CS2', 'CS1'],\n 'borderColor': ['black', 'white', 'black']\n})\nsets_data = pd.DataFrame({\n 'code': ['CS1', 'CS2'],\n 'name': ['Coldsnap', 'OtherSet']\n})\nresult = solve_query(cards_data, sets_data)\nprint(result)", "sql": "SELECT COUNT(*) FROM cards AS T1 INNER JOIN sets AS T2 ON T1.setCode = T2.code WHERE T2.name = 'Coldsnap' AND T1.borderColor = 'black'", "difficulty": "simple" }, { "question_id": 476, "question": "Please list the name of the cards in the set Coldsnap with the highest converted mana cost.", "db_id": "card_games", "evidence": "name equals 'Coldsnap' in the database;", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nsets_df = pd.read_csv('sets.csv')\nmerged_df = pd.merge(cards_df, sets_df, left_on='setCode', right_on='code')\nfiltered_df = merged_df[merged_df['name_y'] == 'Coldsnap']\nresult = filtered_df.nlargest(1, 'convertedManaCost')[['name_x']]\nprint(result)", "sql": "SELECT T1.name FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Coldsnap' ORDER BY T1.convertedManaCost DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 477, "question": "Which of these artists have designed a card in the set Coldsnap, Jeremy Jarvis, Aaron Miller or Chippy?", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; Jeremy Jarvis, Aaron Miller or Chippy are the name of artists which refers to artist IN ('Jeremy Jarvis', 'Aaron Miller','Chippy');", "code": "import pandas as pd\n\ndef solve_query(cards_df, sets_df):\n # Ensure the required columns exist\n if 'artist' not in cards_df.columns or 'setCode' not in cards_df.columns or 'code' not in sets_df.columns or 'name' not in sets_df.columns:\n return pd.DataFrame(columns=['artist'])\n\n # Filter the sets DataFrame for 'Coldsnap'\n coldsnap_set = sets_df[sets_df['name'] == 'Coldsnap']\n\n # Merge cards with the filtered sets data\n merged_data = pd.merge(cards_df, coldsnap_set, left_on='setCode', right_on='code', how='inner')\n\n # Filter for the specified artists\n target_artists = ['Jeremy Jarvis', 'Aaron Miller', 'Chippy']\n filtered_data = merged_data[merged_data['artist'].isin(target_artists)]\n\n # Group by artist and select distinct artists\n result = filtered_data.groupby('artist').first().reset_index()[['artist']]\n\n return result\n\n# Example function call (replace example DataFrames with actual data)\ncards_df = pd.DataFrame({\n 'artist': ['Jeremy Jarvis', 'Aaron Miller', 'Chippy', 'Other'],\n 'setCode': ['CSP', 'CSP', 'CSP', 'XXX']\n})\nsets_df = pd.DataFrame({\n 'code': ['CSP'],\n 'name': ['Coldsnap']\n})\nresult = solve_query(cards_df, sets_df)\nprint(result)", "sql": "SELECT T1.artist FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE (T2.name = 'Coldsnap' AND T1.artist = 'Chippy') OR (T2.name = 'Coldsnap' AND T1.artist = 'Aaron Miller') OR (T2.name = 'Coldsnap' AND T1.artist = 'Jeremy Jarvis') GROUP BY T1.artist", "difficulty": "challenging" }, { "question_id": 478, "question": "What is card number 4 in the set Coldsnap?", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; card number 4 refers to number = 4", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['number'] == '4'], sets[sets['name'] == 'Coldsnap'], left_on='setCode', right_on='code')\nresult = merged[['name_x']].rename(columns={'name_x': 'name'})", "sql": "SELECT T1.name FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Coldsnap' AND T1.number = '4'", "difficulty": "simple" }, { "question_id": 479, "question": "Among the cards with converted mana cost higher than 5 in the set Coldsnap, how many of them have unknown power?", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; converted mana cost higher than 5 refers to convertedManaCost > 5; unknown power refers to power = '*' or T1.power is null", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nsets_df = pd.read_csv('sets.csv')\nmerged_df = pd.merge(cards_df, sets_df, left_on='setCode', right_on='code')\nfiltered_df = merged_df[(merged_df['name_y'] == 'Coldsnap') & (merged_df['convertedManaCost'] > 5)]\nresult = filtered_df[(filtered_df['power'] == '*') | (filtered_df['power'].isna())].shape[0]\nprint(result)", "sql": "SELECT SUM(CASE WHEN T1.power = '*' OR T1.power IS NULL THEN 1 ELSE 0 END) FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Coldsnap' AND T1.convertedManaCost > 5", "difficulty": "moderate" }, { "question_id": 480, "question": "What is the Italian flavor text of the card \"Ancestor's Chosen\"?", "db_id": "card_games", "evidence": "Italian refers to language = 'Italian'; flavor text refers to flavorText; \"Ancestor''s Chosen\" refers to name = 'Ancestor''s Chosen'", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv', low_memory=False)\nforeign_df = pd.read_csv('foreign_data.csv', low_memory=False)\nmerged_df = pd.merge(cards_df, foreign_df, on='uuid', how='inner')\nfiltered_df = merged_df[(merged_df['name_x'] == \"Ancestor's Chosen\") & (merged_df['language'] == 'Italian')]\nresult = filtered_df[['flavorText_y']]\nprint(result)", "sql": "SELECT T2.flavorText FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.name = 'Ancestor''s Chosen' AND T2.language = 'Italian'", "difficulty": "moderate" }, { "question_id": 481, "question": "Please list all the foreign languages in which the card \"Ancestor's Chosen\" has a flavor text.", "db_id": "card_games", "evidence": "\"Ancestor''s Chosen\" refers to name = 'Ancestor''s Chosen'; has a flavor text refers to flavorText is not null", "code": "import pandas as pd\nresult = foreign_data[foreign_data['uuid'].isin(cards[cards['name'] == \"Ancestor's Chosen\"]['uuid']) & foreign_data['flavorText'].notnull()]['language']\nprint(result)", "sql": "SELECT T2.language FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.name = 'Ancestor''s Chosen' AND T2.flavorText IS NOT NULL;", "difficulty": "simple" }, { "question_id": 482, "question": "What's the German type of the card \"Ancestor's Chosen\"?", "db_id": "card_games", "evidence": "German refers to language = 'German'; \"Ancestor's Chosen\" refers to name = 'Ancestor''s Chosen'", "code": "import pandas as pd\n\ncards = pd.read_csv('cards.csv')\nforeign_data = pd.read_csv('foreign_data.csv')\n\nfiltered_cards = cards[cards['name'] == \"Ancestor's Chosen\"]\nmerged_data = pd.merge(filtered_cards, foreign_data, on='uuid', how='inner')\nresult = merged_data[merged_data['language'] == 'German'][['type_y']].drop_duplicates()\nprint(result)", "sql": "SELECT DISTINCT T2.type FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.name = 'Ancestor''s Chosen' AND T2.language = 'German'", "difficulty": "simple" }, { "question_id": 483, "question": "Please list the Italian text ruling of all the cards in the set Coldsnap.", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; Italian refers to language = 'Italian'", "code": "import pandas as pd\n\n# Merge foreign_data with cards on uuid\nmerged1 = pd.merge(foreign_data[foreign_data['language'] == 'Italian'], cards[['uuid', 'setCode']], on='uuid')\n\n# Merge with sets to filter by Coldsnap\nmerged2 = pd.merge(merged1, sets[sets['name'] == 'Coldsnap'][['code']], left_on='setCode', right_on='code')\n\n# Get distinct Italian text rulings\nresult = merged2[['text']].drop_duplicates()", "sql": "SELECT DISTINCT R.text FROM rulings AS R INNER JOIN cards AS C ON C.uuid = R.uuid INNER JOIN sets AS S ON S.code = C.setCode LEFT JOIN foreign_data AS F ON F.uuid = C.uuid AND F.language = 'Italian' WHERE S.name = 'Coldsnap'", "difficulty": "moderate" }, { "question_id": 484, "question": "Please list the Italian names of the cards in the set Coldsnap with the highest converted mana cost.", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; Italian refers to language = 'Italian'; highest converted mana cost refers to MAX(convertedManaCost)", "code": "import pandas as pd\n\n# Read the CSV files\ndf_cards = pd.read_csv('cards.csv')\ndf_foreign = pd.read_csv('foreign_data.csv')\ndf_sets = pd.read_csv('sets.csv')\n\n# Step 1: Find the cards in the 'Coldsnap' set and determine the max convertedManaCost\n# Merge cards and sets to link cards to set names\n# cards has 'name', sets has 'name'. Suffixes will help distinguish them.\ncards_sets = pd.merge(df_cards, df_sets, left_on='setCode', right_on='code', suffixes=('_card', '_set'))\n\n# Filter for the set 'Coldsnap'\n# SQL: WHERE T3.name = 'Coldsnap'\ncoldsnap_cards = cards_sets[cards_sets['name_set'] == 'Coldsnap']\n\n# Calculate the maximum mana cost within this set\n# SQL: SELECT MAX(convertedManaCost) ...\nmax_cmc = coldsnap_cards['convertedManaCost'].max()\n\n# Filter for cards that match this maximum mana cost\ntarget_cards = coldsnap_cards[coldsnap_cards['convertedManaCost'] == max_cmc]\n\n# Step 2: Get the Italian names for these cards\n# SQL: INNER JOIN foreign_data ... AND T1.language = 'Italian'\nmerged_final = pd.merge(target_cards, df_foreign, on='uuid')\n\n# Filter for Italian language\nitalian_cards = merged_final[merged_final['language'] == 'Italian']\n\n# Extract the foreign name.\n# In merged_final: \n# 'name_card' is from cards table.\n# 'name_set' is from sets table.\n# 'name' comes from foreign_data table (since it didn't conflict with _card/_set suffixes).\nresult = italian_cards['name'].values.tolist()\n\nprint(result)", "sql": "SELECT T1.name FROM foreign_data AS T1 INNER JOIN cards AS T2 ON T2.uuid = T1.uuid INNER JOIN sets AS T3 ON T3.code = T2.setCode WHERE T3.name = 'Coldsnap' AND T1.language = 'Italian' AND T2.convertedManaCost = (SELECT MAX(convertedManaCost) FROM cards INNER JOIN sets ON cards.setCode = sets.code WHERE sets.name = 'Coldsnap')", "difficulty": "moderate" }, { "question_id": 485, "question": "When was the ruling for the card 'Reminisce' created?", "db_id": "card_games", "evidence": "Reminisce refers to name = 'Reminisce'; when created is the date", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['name'] == 'Reminisce'][['uuid']], rulings, on='uuid')\nresult = merged[['date']]", "sql": "SELECT T2.date FROM cards AS T1 INNER JOIN rulings AS T2 ON T2.uuid = T1.uuid WHERE T1.name = 'Reminisce'", "difficulty": "simple" }, { "question_id": 486, "question": "What is the percentage of the cards with a converted mana cost of 7 in the set Coldsnap?", "db_id": "card_games", "evidence": "converted mana cost of 7 refers to convertedManaCost = 7; card set Coldsnap refers to name = 'Coldsnap'; percentage = DIVIDE(SUM(convertedManaCost = 7), SUM(convertedManaCost))*100", "code": "import pandas as pd\n\ndef solve_query(cards_df, sets_df):\n try:\n # Check if required columns exist\n if 'convertedManaCost' not in cards_df.columns or 'setCode' not in cards_df.columns:\n return None\n if 'code' not in sets_df.columns or 'name' not in sets_df.columns:\n return None\n\n # Filter the sets DataFrame for the set named 'Coldsnap'\n coldsnap_set = sets_df[sets_df['name'] == 'Coldsnap']\n\n # Ensure the set exists\n if coldsnap_set.empty:\n return None\n\n # Get the set code for 'Coldsnap'\n coldsnap_code = coldsnap_set.iloc[0]['code']\n\n # Filter cards that belong to the 'Coldsnap' set\n coldsnap_cards = cards_df[cards_df['setCode'] == coldsnap_code]\n\n # Ensure there are cards in the set\n if coldsnap_cards.empty:\n return 0.0\n\n # Calculate the percentage of cards with convertedManaCost = 7\n total_cards = len(coldsnap_cards)\n cards_with_cmc_7 = len(coldsnap_cards[coldsnap_cards['convertedManaCost'] == 7])\n\n if total_cards == 0:\n return 0.0\n\n percentage = (cards_with_cmc_7 / total_cards) * 100\n return percentage\n\n except Exception as e:\n return None\n\n# Example usage\n# Assuming `cards` and `sets` are DataFrames loaded from the database\ncards_data = pd.DataFrame({\n 'id': [1, 2, 3, 4],\n 'convertedManaCost': [7, 5, 7, 3],\n 'setCode': ['CSP', 'CSP', 'CSP', 'OTHER']\n})\nsets_data = pd.DataFrame({\n 'code': ['CSP'],\n 'name': ['Coldsnap']\n})\nresult = solve_query(cards_data, sets_data)\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN T1.convertedManaCost = 7 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.id) FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Coldsnap'", "difficulty": "moderate" }, { "question_id": 487, "question": "What is the percentage of incredibly powerful cards in the set Coldsnap?", "db_id": "card_games", "evidence": "card set Coldsnap refers to name = 'Coldsnap'; foil is incredibly powerful refers to cardKingdomFoilId is not null AND cardKingdomId is not null; the percentage of incredibly powerful cards in the set refers to DIVIDE(SUM(incredibly powerful), SUM(name = 'Coldsnap'))*100", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nsets_df = pd.read_csv('sets.csv')\nmerged_df = pd.merge(cards_df, sets_df, left_on='setCode', right_on='code')\nfiltered_df = merged_df[merged_df['name_y'] == 'Coldsnap']\nincredibly_powerful_count = filtered_df[(filtered_df['cardKingdomFoilId'].notna()) & (filtered_df['cardKingdomId'].notna())].shape[0]\ntotal_count = filtered_df.shape[0]\nresult = (incredibly_powerful_count / total_count) * 100\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN T1.cardKingdomFoilId IS NOT NULL AND T1.cardKingdomId IS NOT NULL THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.id) FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Coldsnap'", "difficulty": "challenging" }, { "question_id": 488, "question": "What's the code for the set which was released on 2017/7/14?", "db_id": "card_games", "evidence": "releaseDate equals '2017-07-14' in the database; ratio calculated by dividing 2017 by 7;", "code": "import pandas as pd\nresult = sets[sets['releaseDate'] == '2017-07-14']['code']", "sql": "SELECT code FROM sets WHERE releaseDate = '2017-07-14'", "difficulty": "simple" }, { "question_id": 489, "question": "List the keyrune code for the set whose code is 'PKHC'.", "db_id": "card_games", "evidence": "keyrune code refers to keyruneCode", "code": "import pandas as pd\nresult = sets[sets['code'] == 'PKHC']['keyruneCode']", "sql": "SELECT keyruneCode FROM sets WHERE code = 'PKHC'", "difficulty": "simple" }, { "question_id": 490, "question": "For the set which had 'SS2' as the code, what is its magic card market id?", "db_id": "card_games", "evidence": "magic card market id refers to mcmId", "code": "import pandas as pd\nresult = sets[sets['code'] == 'SS2']['mcmId'].iloc[0]", "sql": "SELECT mcmId FROM sets WHERE code = 'SS2'", "difficulty": "simple" }, { "question_id": 491, "question": "What's the magic card market name for the set which was released on 2017/6/9?", "db_id": "card_games", "evidence": "magic card market name refers to mcmName", "code": "import pandas as pd\nresult = sets[sets['releaseDate'] == '2017-06-09']['mcmName']", "sql": "SELECT mcmName FROM sets WHERE releaseDate = '2017-06-09'", "difficulty": "simple" }, { "question_id": 492, "question": "For the set \"From the Vault: Lore\", what is its expansion type?", "db_id": "card_games", "evidence": "set \"From the Vault refers to name which contains 'From the Vault: Lore'; expansion type refers to type", "code": "import pandas as pd\nresult = sets[sets['name'].str.contains('From the Vault: Lore', case=False, na=False)][['type']]", "sql": "SELECT type FROM sets WHERE name LIKE '%FROM the Vault: Lore%'", "difficulty": "simple" }, { "question_id": 493, "question": "For the set \"Commander 2014 Oversized\" , give its parent code.", "db_id": "card_games", "evidence": "the set \"Commander 2014 Oversized\" refers to name = 'Commander 2014 Oversized';", "code": "import pandas as pd\nresult = sets[sets['name'] == 'Commander 2014 Oversized'][['parentCode']]", "sql": "SELECT parentCode FROM sets WHERE name = 'Commander 2014 Oversized'", "difficulty": "simple" }, { "question_id": 494, "question": "For all cards illustrated by Jim Pavelec. and describe the text of the ruling of these cards. Do these cards have missing or degraded properties and values.", "db_id": "card_games", "evidence": "all cards illustrated by Jim Pavelec refers to artist = 'Jim Pavelec'; the text of the ruling refers to text; cards have missing or degraded properties and values if hasContentWarning = 1 else it doesn't have;", "code": "import pandas as pd\ncards = pd.read_csv('cards.csv', low_memory=False)\nrulings = pd.read_csv('rulings.csv')\nmerged_df = pd.merge(cards, rulings, on='uuid', how='left')\nfiltered_df = merged_df[merged_df['artist'].str.contains('Jim Pavelec', na=False, case=False)].copy()\nfiltered_df.loc[:, 'contentWarning'] = filtered_df['hasContentWarning'].apply(lambda x: 'YES' if x == 1 else 'NO')\nresult = filtered_df[['text_x', 'contentWarning']]\nprint(result)", "sql": "SELECT T2.text, CASE WHEN T1.hasContentWarning = 1 THEN 'YES' ELSE 'NO' END FROM cards AS T1 LEFT JOIN rulings AS T2 ON T2.uuid = T1.uuid WHERE T1.artist = 'Jim Pavelec'", "difficulty": "challenging" }, { "question_id": 495, "question": "What was the release date for the set which card \"Evacuation\" in it?", "db_id": "card_games", "evidence": "\"Evacuation\" refers to name = 'Evacuation'; release date refers to releaseDate", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nsets_df = pd.read_csv('sets.csv')\nmerged_df = pd.merge(cards_df, sets_df, left_on='setCode', right_on='code')\nresult = merged_df[merged_df['name_x'] == 'Evacuation'][['releaseDate']]\nprint(result)", "sql": "SELECT T2.releaseDate FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T1.name = 'Evacuation'", "difficulty": "simple" }, { "question_id": 496, "question": "What is the number of cards are there in the set of \"Rinascita di Alara\"?", "db_id": "card_games", "evidence": "number of cards refers to baseSetSize; set of \"Rinascita di Alara\" refers to translation = 'Rinascita di Alara'", "code": "import pandas as pd\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\nfiltered = merged[merged['translation'] == 'Rinascita di Alara']\nresult = filtered['baseSetSize'].iloc[0]", "sql": "SELECT T1.baseSetSize FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T2.translation = 'Rinascita di Alara'", "difficulty": "simple" }, { "question_id": 497, "question": "List the expansion type of the set \"Huitième édition\".", "db_id": "card_games", "evidence": "the set \"Huitième édition\" refers to translation = 'Huitième édition'; expansion type refers to type", "code": "import pandas as pd\n\ndef solve_query(sets_df, set_translations_df):\n try:\n # Check if necessary columns exist\n if 'translation' not in set_translations_df.columns or 'setCode' not in set_translations_df.columns:\n return pd.DataFrame({'type': []})\n\n if 'code' not in sets_df.columns or 'type' not in sets_df.columns:\n return pd.DataFrame({'type': []})\n\n # Filter set_translations for the target translation\n filtered_translation = set_translations_df[set_translations_df['translation'] == 'Huitième édition']\n\n # Get the corresponding set codes\n set_codes = filtered_translation['setCode']\n\n # Use the set codes to filter the sets DataFrame\n result = sets_df[sets_df['code'].isin(set_codes)][['type']]\n\n return result\n\n except Exception as e:\n # Return an empty DataFrame in case of error\n return pd.DataFrame({'type': []})\n\n# Example usage\nsets_data = {'code': ['SET1', 'SET2'], 'type': ['Expansion', 'Core']}\nset_translations_data = {'setCode': ['SET1'], 'translation': ['Huitième édition']}\n\nsets_df = pd.DataFrame(sets_data)\nset_translations_df = pd.DataFrame(set_translations_data)\n\nresult = solve_query(sets_df, set_translations_df)\nprint(result)", "sql": "SELECT type FROM sets WHERE code IN ( SELECT setCode FROM set_translations WHERE translation = 'Huitième édition' )", "difficulty": "simple" }, { "question_id": 498, "question": "What's the French name of the set of cards with \"Tendo Ice Bridge\" is in?", "db_id": "card_games", "evidence": "French refers to language = 'French'; \"Tendo Ice Bridge\" is a translated name of a card; translated name refers to translation", "code": "import pandas as pd\nmerged = pd.merge(cards[cards['name'] == 'Tendo Ice Bridge'], set_translations[(set_translations['language'] == 'French') & (set_translations['translation'].notna())], left_on='setCode', right_on='setCode')\nresult = merged[['translation']]", "sql": "SELECT T2.translation FROM cards AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.setCode WHERE T1.name = 'Tendo Ice Bridge' AND T2.language = 'French' AND T2.translation IS NOT NULL", "difficulty": "moderate" }, { "question_id": 499, "question": "How many translations of the name of the set \"Tenth Edition\"?", "db_id": "card_games", "evidence": "translations of the name refers to translation; translation is not NULL; set \"Salvat 2011\" refers to name = 'Tenth Edition'", "code": "import pandas as pd\n\n# Merge sets and set_translations tables\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\n\n# Filter for 'Tenth Edition' and non-null translations\nfiltered = merged[(merged['name'] == 'Tenth Edition') & (merged['translation'].notna())]\n\n# Count distinct translations\nresult = filtered['translation'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.translation) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T1.name = 'Tenth Edition' AND T2.translation IS NOT NULL", "difficulty": "moderate" }, { "question_id": 500, "question": "Tell the Japanese name of the set which card \"Fellwar Stone\" is in it.", "db_id": "card_games", "evidence": "Japanese name refers to language = 'Japanese'; card \"Fellwar Stone\" refers to name = 'Fellwar Stone'", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nsets_df = pd.read_csv('sets.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\nmerged_df = pd.merge(cards_df, sets_df, left_on='setCode', right_on='code')\nmerged_df = pd.merge(merged_df, set_translations_df, left_on='code', right_on='setCode')\nresult = merged_df[(merged_df['name_x'] == 'Fellwar Stone') & (merged_df['language'] == 'Japanese') & (merged_df['translation'].notna())][['translation']]\nprint(result)", "sql": "SELECT T3.translation FROM cards AS T1 INNER JOIN sets AS T2 ON T1.setCode = T2.code INNER JOIN set_translations AS T3 ON T2.code = T3.setCode WHERE T1.name = 'Fellwar Stone' AND T3.language = 'Japanese' AND T3.translation IS NOT NULL", "difficulty": "moderate" }, { "question_id": 501, "question": "Which card name in the set 'Journey into Nyx Hero's Path' has the highest converted mana cost.", "db_id": "card_games", "evidence": "name equals 'Journey into Nyx Hero' in the database;", "code": "import pandas as pd\n# 找出目标集合对应的所有set code\nfiltered_sets = sets[sets['name'] == \"Journey into Nyx Hero's Path\"]\ntarget_set_codes = filtered_sets['code']\n# 过滤出这些set code对应的卡牌\nfiltered_cards = cards[cards['setCode'].isin(target_set_codes)]\n# 找到convertedManaCost最高的卡牌\nresult = filtered_cards.sort_values('convertedManaCost', ascending=False).iloc[0]['name']", "sql": "SELECT T1.name FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Journey into Nyx Hero''s Path' ORDER BY T1.convertedManaCost DESC LIMIT 1;", "difficulty": "moderate" }, { "question_id": 502, "question": "What is the release date for the set \"Ola de frío\"?", "db_id": "card_games", "evidence": "release date is the date of card set being released; set \"Ola de frío\" refers to translation = 'Ola de frío'", "code": "import pandas as pd\nmerged = pd.merge(sets, set_translations, left_on='code', right_on='setCode')\nfiltered = merged[merged['translation'] == 'Ola de frío']\nresult = filtered[['releaseDate']]", "sql": "SELECT T1.releaseDate FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T2.translation = 'Ola de frío'", "difficulty": "simple" }, { "question_id": 503, "question": "What was the expansion type for the set which card \"Samite Pilgrim\" in it?", "db_id": "card_games", "evidence": "expansion type refers to type; card \"Samite Pilgrim\" refers to name = 'Samite Pilgrim'", "code": "import pandas as pd\n\n# Filter cards for 'Samite Pilgrim'\nsamite_cards = cards[cards['name'] == 'Samite Pilgrim']\n\n# Get the setCode(s) for this card\nset_codes = samite_cards['setCode'].unique()\n\n# Filter sets by these codes and get the type\nresult = sets[sets['code'].isin(set_codes)][['type']]", "sql": "SELECT type FROM sets WHERE code IN ( SELECT setCode FROM cards WHERE name = 'Samite Pilgrim' )", "difficulty": "simple" }, { "question_id": 504, "question": "How many cards are there in the set 'World Championship Decks 2004' with the converted mana cost as '3'.", "db_id": "card_games", "evidence": "name equals 'World Championship Decks 2004' in the database;", "code": "import pandas as pd\n\n# Get the set code for 'World Championship Decks 2004'\nset_code = sets[sets['name'] == 'World Championship Decks 2004']['code'].iloc[0]\n\n# Count cards with that setCode and convertedManaCost = 3\nresult = cards[(cards['setCode'] == set_code) & (cards['convertedManaCost'] == 3)]['id'].count()", "sql": "SELECT COUNT(id) FROM cards WHERE setCode IN (SELECT code FROM sets WHERE name = 'World Championship Decks 2004') AND convertedManaCost = 3", "difficulty": "simple" }, { "question_id": 505, "question": "Show the Simplified Chinese translation of the name of the set \"Mirrodin\"?", "db_id": "card_games", "evidence": "Simplified Chinese translation refers to language = 'Chinese Simplified'; name of the set \"Mirrodin\" refers to name = 'Mirrodin'", "code": "import pandas as pd\n\n# Get the code for the set named 'Mirrodin'\nmirrodin_code = sets[sets['name'] == 'Mirrodin']['code'].iloc[0]\n\n# Filter set_translations for the Mirrodin code and Chinese Simplified language\nresult = set_translations[(set_translations['setCode'] == mirrodin_code) & (set_translations['language'] == 'Chinese Simplified')]['translation']", "sql": "SELECT translation FROM set_translations WHERE setCode IN ( SELECT code FROM sets WHERE name = 'Mirrodin' ) AND language = 'Chinese Simplified'", "difficulty": "moderate" }, { "question_id": 506, "question": "For all the set of cards that has Japanese translation, what is the percentage of them are only available in non-foil?", "db_id": "card_games", "evidence": "Japanese translation refers to language = 'Japanese'; in non-foil refers to isNonFoilOnly = 1; percentage of Japanese non foil in Japanese cards refers to DIVIDE(SUM(isNonFoilOnly = 1), SUM(language = 'Japanese'))*100percentage of Japanese non foil in Japanese sets refers to DIVIDE(SUM(isNonFoilOnly = 1), COUNT(id))*100", "code": "import pandas as pd\nmerged = pd.merge(cards, set_translations, on='setCode')\njapanese = merged[merged['language'] == 'Japanese']\nnon_foil_count = ((japanese['hasNonFoil'] == 1) & (japanese['hasFoil'] == 0)).sum()\ntotal_japanese = japanese['id_x'].nunique()\npercentage_non_foil_only = (non_foil_count / total_japanese) * 100\nresult = pd.DataFrame({'percentage_non_foil_only': [percentage_non_foil_only]})", "sql": "SELECT CAST(SUM(CASE WHEN c.hasNonFoil = 1 AND c.hasFoil = 0 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(DISTINCT c.id) AS percentage_non_foil_only FROM cards c JOIN set_translations st ON c.setCode = st.setCode WHERE st.language = 'Japanese'", "difficulty": "challenging" }, { "question_id": 507, "question": "For all the set of cards that has Brazil Portuguese translation, what is the percentage of them are only available online?", "db_id": "card_games", "evidence": "Brazil Portuguese translation refers to language = 'Portuguese (Brazil)'; only available online refers to isOnlineOnly = 1; percentage of online only Brazil Portuguese in all Brazil Portuguese cards refers to DIVIDE(SUM(isOnlineOnly = 1), SUM(language = 'Portuguese (Brazil)))*100", "code": "import pandas as pd\nbrazil_sets = set_translations[set_translations['language'] == 'Portuguese (Brazil)']['setCode']\nfiltered_sets = sets[sets['code'].isin(brazil_sets)]\nonline_only_ratio = (filtered_sets['isOnlineOnly'].sum() / len(filtered_sets)) * 100\nresult = online_only_ratio", "sql": "SELECT CAST(SUM(CASE WHEN isOnlineOnly = 1 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(id) FROM sets WHERE code IN ( SELECT setCode FROM set_translations WHERE language = 'Portuguese (Brazil)' )", "difficulty": "challenging" }, { "question_id": 508, "question": "What are the available printing types of the cards that doesn't have a text box created by Aleksi Briclot?", "db_id": "card_games", "evidence": "created by Aleksi Briclot refers to artist = 'Aleksi Briclot'; doesn't have a text box refers to isTextless = 1; available printing types refers to availability", "code": "import pandas as pd\nfiltered_cards = cards[(cards['artist'] == 'Aleksi Briclot') & (cards['isTextless'] == 1)]\nresult = filtered_cards['availability'].dropna().unique()", "sql": "SELECT DISTINCT availability FROM cards WHERE artist = 'Aleksi Briclot' AND isTextless = 1", "difficulty": "moderate" }, { "question_id": 509, "question": "What is the unique id of the set that has the highest number of cards?", "db_id": "card_games", "evidence": "the highest number of cards refers to MAX(baseSetSize); unique id refers to id", "code": "import pandas as pd\nresult = sets.nlargest(1, 'baseSetSize')[['id']]", "sql": "SELECT id FROM sets ORDER BY baseSetSize DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 510, "question": "Among the cards that doesn't have multiple faces on the same card, who is the illustrator of the card art that has the highest cost of converted mana?", "db_id": "card_games", "evidence": "doesn't have multiple faces refers to side IS NULL; illustrator refers to artist", "code": "import pandas as pd\nfiltered_cards = cards[cards['side'].isna()]\nresult = filtered_cards.nlargest(1, 'convertedManaCost')[['artist']]", "sql": "SELECT artist FROM cards WHERE side IS NULL ORDER BY convertedManaCost DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 511, "question": "What is the most common visual frame effects among the incredibly powerful foils?", "db_id": "card_games", "evidence": "when both cardKingdomFoilId and cardKingdomId are not null, this foil is incredibly powerful; most common visual frame effects refers to MAX(frameEffects)", "code": "import pandas as pd\n\ncards_df = pd.read_csv('cards.csv')\nfiltered_df = cards_df[(cards_df['cardKingdomFoilId'].notna()) & (cards_df['cardKingdomId'].notna())]\nresult = filtered_df.groupby('frameEffects').size().reset_index(name='count').nlargest(1, 'count')[['frameEffects']]\nprint(result)", "sql": "SELECT frameEffects FROM cards WHERE cardKingdomFoilId IS NOT NULL AND cardKingdomId IS NOT NULL GROUP BY frameEffects ORDER BY COUNT(frameEffects) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 512, "question": "How many cards with unknown power that can't be found in foil is in duel deck A?", "db_id": "card_games", "evidence": "unknown power refers to power IS NULL or power = '*'; can't be found in foil refers to hasFoil = 0; duel deck A refers to duelDeck = 'a'", "code": "import pandas as pd\nfiltered_cards = cards[(cards['hasFoil'] == 0) & (cards['duelDeck'] == 'a')]\nresult = ((filtered_cards['power'] == '*') | (filtered_cards['power'].isna())).sum()", "sql": "SELECT SUM(CASE WHEN power = '*' OR power IS NULL THEN 1 ELSE 0 END) FROM cards WHERE hasFoil = 0 AND duelDeck = 'a'", "difficulty": "simple" }, { "question_id": 513, "question": "Among the sets whose expansion type is Commander, which set has the highest total number of cards including promotional and related supplemental products but excluding Alchemy modifications? Indicate the id of the set.", "db_id": "card_games", "evidence": "expansion type refers to type where type = 'commander'; totalSetSize: The total number of cards in the set, including promotional and related supplemental products but excluding Alchemy modifications; highest total number of cards refers to MAX(totalSetSize)", "code": "import pandas as pd\ncommander_sets = sets[sets['type'] == 'commander']\nresult = commander_sets.sort_values('totalSetSize', ascending=False).head(1)['id'].values[0]", "sql": "SELECT id FROM sets WHERE type = 'commander' ORDER BY totalSetSize DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 514, "question": "In duels, what are the top 10 cards with the highest uncoverted mana cost?", "db_id": "card_games", "evidence": "duels refer to format = 'duel'; the highest uncoverted mana cost refers to MAX(manaCost)", "code": "import pandas as pd\nlegal_duels = legalities[legalities['format'] == 'duel']['uuid']\nfiltered = cards[cards['uuid'].isin(legal_duels)]\nsorted_cards = filtered.sort_values('convertedManaCost', ascending=False)\nunique_cards = sorted_cards.drop_duplicates('name')\nresult = unique_cards.head(10)[['name']]", "sql": "SELECT DISTINCT name FROM cards WHERE uuid IN ( SELECT uuid FROM legalities WHERE format = 'duel' ) ORDER BY convertedManaCost DESC LIMIT 0, 10", "difficulty": "simple" }, { "question_id": 515, "question": "When was the oldest mythic card released and what are its legal play formats?", "db_id": "card_games", "evidence": "the oldest card refers to MIN(originalReleaseDate); mythic card refers to rarity = 'mythic'; legal play refers to status = 'legal'; play format refers to format", "code": "import pandas as pd\n\n# Filter mythic cards with non-null originalReleaseDate\nmythic_cards = cards[(cards['rarity'] == 'mythic') & (cards['originalReleaseDate'].notna())]\n\n# Join with legalities table\nmerged = pd.merge(mythic_cards, legalities[legalities['status'] == 'Legal'], on='uuid')\n\n# Sort by originalReleaseDate and get the oldest\noldest = merged.sort_values('originalReleaseDate').head(1)\n\n# Select only the required columns\nresult = oldest[['originalReleaseDate', 'format']]", "sql": "SELECT T1.originalReleaseDate, T2.format FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.rarity = 'mythic' AND T1.originalReleaseDate IS NOT NULL AND T2.status = 'Legal' ORDER BY T1.originalReleaseDate LIMIT 1", "difficulty": "moderate" }, { "question_id": 516, "question": "How many cards did Volkan Baǵa illustrated whose foreign language is in French?", "db_id": "card_games", "evidence": "Volkan Baǵa refers to artist = 'Volkan Baǵa'; foreign language is in French refers to language = 'French'", "code": "import pandas as pd\n\ndef solve_query(cards_df, foreign_data_df):\n merged = pd.merge(cards_df, foreign_data_df, on='uuid', how='inner')\n filtered = merged[(merged['artist'] == 'Volkan Baǵa') & (merged['language'] == 'French')]\n return filtered['id_x'].nunique()\n\n# 假设cards和foreign_data已加载为DataFrame\nresult = solve_query(cards, foreign_data)", "sql": "SELECT COUNT(T3.id) FROM ( SELECT T1.id FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T2.uuid = T1.uuid WHERE T1.artist = 'Volkan Baǵa' AND T2.language = 'French' GROUP BY T1.id ) AS T3", "difficulty": "moderate" }, { "question_id": 517, "question": "How many rare enchantment Abundance cards are there whose play format status are all legal?", "db_id": "card_games", "evidence": "rare refers to rarity = 'rare'; enchantment card refers to types = 'Enchantment'; Abundance cards refers to name = 'Abundance'; format status are all legal refers to status = 'Legal'", "code": "import pandas as pd\n\n# 筛选符合条件的卡牌\nfiltered_cards = cards[(cards['rarity'] == 'rare') & (cards['types'] == 'Enchantment') & (cards['name'] == 'Abundance')]\n\n# 找出状态不为'legal'的uuid(注意是小写'legal')\nbad_uuids = legalities[legalities['status'] != 'legal']['uuid']\n\n# 找出所有在legalities表中存在的uuid\nall_uuids = legalities['uuid'].unique()\n\n# 找出在legalities表中存在但状态不为'legal'的卡牌uuid\nvalid_cards = filtered_cards[\n (filtered_cards['uuid'].isin(all_uuids)) & # 确保在legalities表中存在\n (~filtered_cards['uuid'].isin(bad_uuids)) # 确保所有状态都是'legal'\n]\n\nresult = len(valid_cards)", "sql": "SELECT COUNT(T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T2.uuid = T1.uuid WHERE T1.rarity = 'rare' AND T1.types = 'Enchantment' AND T1.name = 'Abundance' AND T2.status = 'legal'", "difficulty": "moderate" }, { "question_id": 518, "question": "Which of the play format has the highest number of banned status? Indicate the play format and the names of all the card meet the condition.", "db_id": "card_games", "evidence": "play format refers to format; banned status refers to status = 'Banned'; the highest number of banned status refers to MAX(COUNT(status = 'Banned'))legalities table refers to legalities; cards table refers to cards; uuid in legalities refers to uuid in cards; format in legalities refers to play format; status = 'Banned' refers to banned status; MaxBanned CTE refers to subquery selecting format with highest COUNT(*) of banned status; final query joins legalities and cards on uuid to retrieve card names", "code": "import pandas as pd\nbanned = legalities[legalities['status'] == 'Banned']\nformat_counts = banned.groupby('format').size().reset_index(name='cnt')\nmax_format = format_counts.loc[format_counts['cnt'].idxmax(), 'format']\nmerged = cards.merge(legalities, on='uuid')\nfiltered = merged[(merged['format'] == max_format) & (merged['status'] == 'Banned')]\nresult = filtered[['format', 'name']]", "sql": "WITH MaxBanned AS (SELECT format, COUNT(*) AS count_banned FROM legalities WHERE status = 'Banned' GROUP BY format ORDER BY COUNT(*) DESC LIMIT 1) SELECT T2.format, T1.name FROM cards AS T1 INNER JOIN legalities AS T2 ON T2.uuid = T1.uuid INNER JOIN MaxBanned MB ON MB.format = T2.format WHERE T2.status = 'Banned'", "difficulty": "moderate" }, { "question_id": 519, "question": "What is the language of the \"Battlebond\" set?", "db_id": "card_games", "evidence": "name equals 'Battlebond' in the database;", "code": "import pandas as pd\nresult = set_translations[set_translations['setCode'].isin(sets[sets['name'] == 'Battlebond']['code'])]['language']", "sql": "SELECT language FROM set_translations WHERE setCode IN (SELECT code FROM sets WHERE name = 'Battlebond')", "difficulty": "simple" }, { "question_id": 520, "question": "Who is the illustrator that illustrated the least amount of cards? List the format of play of the cards that he/she illustrated.", "db_id": "card_games", "evidence": "format of the cards refers to format; illustrator refers to artist; the least amount of cards refers to MIN(artist)the least amount of cards refers to COUNT(T1.id) ordered in ascending order", "code": "import pandas as pd\nartist_counts = cards.groupby('artist', as_index=False)['id'].count().rename(columns={'id': 'card_count'})\nmin_count = artist_counts['card_count'].min()\nmin_artists = artist_counts[artist_counts['card_count'] == min_count]['artist']\nmerged_df = pd.merge(cards[['uuid', 'artist']], legalities[['uuid', 'format']], on='uuid')\nresult = merged_df[merged_df['artist'].isin(min_artists)][['artist', 'format']]", "sql": "WITH ArtistCardCount AS (SELECT T1.artist, COUNT(T1.id) AS card_count FROM cards AS T1 GROUP BY T1.artist), MinCardCount AS (SELECT MIN(card_count) AS min_count FROM ArtistCardCount) SELECT T1.artist, T2.format FROM cards AS T1 INNER JOIN legalities AS T2 ON T2.uuid = T1.uuid WHERE T1.artist IN (SELECT artist FROM ArtistCardCount WHERE card_count = (SELECT min_count FROM MinCardCount))", "difficulty": "moderate" }, { "question_id": 521, "question": "Among the cards whose version of frame style is 1997, what is the status of the card illustrated by D. Alexander Gregory in legacy play format that has sensitive content or Wizards of the Coast?", "db_id": "card_games", "evidence": "version of frame style is 1997 refers to frameVersion = '1997'; illustrated by D. Alexander Gregory refers to artist = 'D. Alexander Gregory'; sensitive content refers to hasContentWarning = 1; legacy play format refers to format = 'legacy'; status of the card refers to status", "code": "import pandas as pd\n\n# Read the CSV files\ndf_cards = pd.read_csv('cards.csv')\ndf_legalities = pd.read_csv('legalities.csv')\n\n# Ensure frameVersion is treated as string to match the query '1997'\n# SQL: WHERE frameVersion = 1997 (SQLite handles implicit casting, Pandas does not)\ndf_cards['frameVersion'] = df_cards['frameVersion'].astype(str)\n\n# Filter cards based on conditions\n# Conditions: frameVersion='1997', hasContentWarning=1, artist='D. Alexander Gregory'\nfiltered_cards = df_cards[\n (df_cards['frameVersion'] == '1997') & \n (df_cards['hasContentWarning'] == 1) & \n (df_cards['artist'] == 'D. Alexander Gregory')\n]\n\n# Join with legalities table on uuid\n# SQL: INNER JOIN legalities AS T2 ON T2.uuid = T1.uuid\nmerged_df = pd.merge(filtered_cards, df_legalities, on='uuid')\n\n# Filter for legacy format\n# SQL: AND T2.format = 'legacy'\nlegacy_cards = merged_df[merged_df['format'] == 'legacy']\n\n# Get distinct status values\n# SQL: SELECT DISTINCT T2.status\nresult = legacy_cards['status'].unique().tolist()\n\nprint(result)", "sql": "SELECT DISTINCT T2.status FROM cards AS T1 INNER JOIN legalities AS T2 ON T2.uuid = T1.uuid WHERE T1.frameVersion = 1997 AND T1.hasContentWarning = 1 AND T1.artist = 'D. Alexander Gregory' AND T2.format = 'legacy'", "difficulty": "challenging" }, { "question_id": 522, "question": "Which cards are ranked 1st on EDHRec? List all of the cards name and its banned play format.", "db_id": "card_games", "evidence": "ranked 1st on EDHRec refers to edhrecRank = 1; banned refers to status = 'Banned'; play format refers to format; cards name refers to name", "code": "import pandas as pd\nfiltered_cards = cards[cards['edhrecRank'] == 1]\nfiltered_legalities = legalities[legalities['status'] == 'Banned']\nmerged = pd.merge(filtered_cards, filtered_legalities, on='uuid')\nresult = merged[['name', 'format']].drop_duplicates()", "sql": "SELECT T1.name, T2.format FROM cards AS T1 INNER JOIN legalities AS T2 ON T2.uuid = T1.uuid WHERE T1.edhrecRank = 1 AND T2.status = 'Banned' GROUP BY T1.name, T2.format", "difficulty": "moderate" }, { "question_id": 523, "question": "What is the annual average number of sets that were released between 1/1/2012 to 12/31/2015? Indicate the common langugage of the card.", "db_id": "card_games", "evidence": "AVG(id); releaseDate BETWEEN 1/1/2012 AND 12/31/2015; the common language refers to MAX(COUNT(language))", "code": "import pandas as pd\n\n# Filter sets between 2012-2015\nsets['releaseDate'] = pd.to_datetime(sets['releaseDate'])\nfiltered_sets = sets[(sets['releaseDate'] >= '2012-01-01') & (sets['releaseDate'] <= '2015-12-31')]\n\n# Join with set_translations\nmerged = pd.merge(filtered_sets, set_translations, left_on='code', right_on='setCode')\n\n# Calculate annual average number of sets (total sets / 4 years)\ntotal_sets = len(filtered_sets)\nannual_average = total_sets / 4\n\n# Find most common language\nlanguage_counts = merged['language'].value_counts()\nmost_common_language = language_counts.index[0]\n\n# Create result\nresult = pd.DataFrame({'annual_average_sets': [annual_average], 'common_language': [most_common_language]})", "sql": "SELECT (CAST(SUM(T1.id) AS REAL) / COUNT(T1.id)) / 4, T2.language FROM sets AS T1 INNER JOIN set_translations AS T2 ON T1.id = T2.id WHERE T1.releaseDate BETWEEN '2012-01-01' AND '2015-12-31' GROUP BY T1.releaseDate ORDER BY COUNT(T2.language) DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 524, "question": "List the artists who illustrated cards with black borders which are available only in arena.", "db_id": "card_games", "evidence": "black borders refers to BorderColor = 'black'; available only in arena refers to availability = 'arena'", "code": "import pandas as pd\nresult = cards[(cards['availability'] == 'arena') & (cards['borderColor'] == 'black')]['artist'].drop_duplicates()", "sql": "SELECT DISTINCT artist FROM cards WHERE availability = 'arena' AND BorderColor = 'black'", "difficulty": "simple" }, { "question_id": 525, "question": "Find the uuid of cards in which the old school format is restricted or banned.", "db_id": "card_games", "evidence": "old school format refers to format = 'oldschool'; restricted or banned refers to status = 'banned' or 'restricted'restricted or banned refers to status = 'Banned' or 'Restricted'", "code": "import pandas as pd\nresult = legalities[(legalities['format'] == 'oldschool') & ((legalities['status'] == 'Banned') | (legalities['status'] == 'Restricted'))][['uuid']]", "sql": "SELECT uuid FROM legalities WHERE format = 'oldschool' AND (status = 'Banned' OR status = 'Restricted')", "difficulty": "simple" }, { "question_id": 526, "question": "Among the card designed by Matthew D. Wilson, how many are available only in the paper?", "db_id": "card_games", "evidence": "card designed by Matthew D. Wilson refers to artist = 'Matthew D. Wilson'; available only in the paper refers to availability = 'paper'", "code": "import pandas as pd\nresult = len(cards[(cards['artist'] == 'Matthew D. Wilson') & (cards['availability'] == 'paper')])", "sql": "SELECT COUNT(id) FROM cards WHERE artist = 'Matthew D. Wilson' AND availability = 'paper'", "difficulty": "simple" }, { "question_id": 527, "question": "What are the rulings for the card named and designed by Kev Walker? List them in descending order of dates.", "db_id": "card_games", "evidence": "rulings refers to text; card named and designed by Kev Walker refers to artist = 'Kev Walker'; descending order of dates refers to MAX(date);", "code": "import pandas as pd\n\ncards = pd.read_csv('cards.csv')\nrulings = pd.read_csv('rulings.csv')\n\n# 合并 cards 和 rulings 表\n# 注意:两个表都有 'text' 列,合并后会自动变成 'text_x' (cards) 和 'text_y' (rulings)\nmerged_data = pd.merge(cards, rulings, on='uuid')\n\n# 筛选艺术家为 Kev Walker 的卡牌\nfiltered_data = merged_data[merged_data['artist'] == 'Kev Walker']\n\n# 按日期降序排列\nsorted_data = filtered_data.sort_values('date', ascending=False)\n\n# 选取 rulings 表中的 text 列 (即 text_y),并重命名回 text\nresult = sorted_data[['text_y']].rename(columns={'text_y': 'text'})\n\nprint(result)", "sql": "SELECT T2.text FROM cards AS T1 INNER JOIN rulings AS T2 ON T2.uuid = T1.uuid WHERE T1.artist = 'Kev Walker' ORDER BY T2.date DESC", "difficulty": "moderate" }, { "question_id": 528, "question": "List the names of all the cards in the set Hour of Devastation and find the formats in which these cards are legal.", "db_id": "card_games", "evidence": "the set Hour of Devastation refers to set.name = 'Hour of Devastation'; names of all the cards in the set refers to cards.name; legal cards refers to status = 'Legal'; the formats refers to formatcards.setCode refers to sets.code", "code": "import pandas as pd\nhour_code = sets[sets['name'] == 'Hour of Devastation']['code'].iloc[0]\nfiltered_cards = cards[cards['setCode'] == hour_code][['uuid', 'name']]\nlegal_legals = legalities[legalities['status'] == 'Legal'][['uuid', 'format']]\nmerged = pd.merge(filtered_cards, legal_legals, on='uuid')\nresult = merged[['name', 'format']].drop_duplicates()", "sql": "SELECT DISTINCT T2.name, T1.format FROM legalities AS T1 INNER JOIN cards AS T2 ON T2.uuid = T1.uuid WHERE T2.setCode IN (SELECT code FROM sets WHERE name = 'Hour of Devastation') AND T1.status = 'Legal'", "difficulty": "challenging" }, { "question_id": 529, "question": "Find and list the names of sets which doesn't have Japanese translation but have Korean translation.", "db_id": "card_games", "evidence": "names of sets refers to name; doesn't have Japanese translation refers to language not like '%Japanese%'; have Korean translation refers to language = 'Korean'", "code": "import pandas as pd\n\n# Read the necessary tables\nsets_df = pd.read_csv('sets.csv')\nset_translations_df = pd.read_csv('set_translations.csv')\n\n# Filter sets with Korean translation\nkorean_translated_sets = set_translations_df[set_translations_df['language'] == 'Korean']['setCode'].unique()\n\n# Filter sets without Japanese translation\nnon_japanese_translated_sets = set_translations_df[~set_translations_df['language'].str.contains('Japanese')]['setCode'].unique()\n\n# Find sets that have Korean translation but no Japanese translation\nresult_sets = set(korean_translated_sets) & set(non_japanese_translated_sets)\n\n# Get the names of these sets\nresult = sets_df[sets_df['code'].isin(result_sets)]['name']\n\n# Print the final result\nprint(result)", "sql": "SELECT name FROM sets WHERE code IN ( SELECT setCode FROM set_translations WHERE language = 'Korean' AND language NOT LIKE '%Japanese%' )", "difficulty": "moderate" }, { "question_id": 530, "question": "List all the frame styles and cards Allen Williams worked on and find any banned cards if there are any.", "db_id": "card_games", "evidence": "frame styles refers to frameVersion; cards Allen Williams worked on refers to artist = 'Allen Williams'; banned cards refers to status = 'Banned'", "code": "import pandas as pd\nimport numpy as np\n# 假设cards和legalities已作为DataFrame存在\nresult = (cards[cards['artist'] == 'Allen Williams']\n .merge(legalities, on='uuid')\n .assign(banned=lambda x: np.where(x['status'] == 'Banned', x['name'], 'NO'))\n [['frameVersion', 'name', 'banned']]\n .drop_duplicates())", "sql": "SELECT DISTINCT T1.frameVersion, T1.name, IIF(T2.status = 'Banned', T1.name, 'NO') FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.artist = 'Allen Williams'", "difficulty": "moderate" }, { "question_id": 531, "question": "Which user has a higher reputation, Harlan or Jarrod Dixon?", "db_id": "codebase_community", "evidence": "\"Harlan\" and \"Jarrod Dixon\" are both DisplayName; highest reputation refers to Max(Reputation)", "code": "import pandas as pd\nfiltered_users = users[users['DisplayName'].isin(['Harlan', 'Jarrod Dixon'])]\nmax_reputation = filtered_users['Reputation'].max()\nresult = filtered_users[filtered_users['Reputation'] == max_reputation][['DisplayName']]", "sql": "SELECT DisplayName FROM users WHERE DisplayName IN ('Harlan', 'Jarrod Dixon') AND Reputation = ( SELECT MAX(Reputation) FROM users WHERE DisplayName IN ('Harlan', 'Jarrod Dixon') )", "difficulty": "simple" }, { "question_id": 532, "question": "Please list the display names of all the users whose accounts were created in the year 2011.", "db_id": "codebase_community", "evidence": "account created in the year 2011 refers to year(CreationDate) = 2011", "code": "import pandas as pd\n\n# 筛选2011年创建的用户账户\nusers_2011 = users[pd.to_datetime(users['CreationDate']).dt.year == 2011]\n\n# 返回显示名称\nresult = users_2011[['DisplayName']].drop_duplicates()", "sql": "SELECT DisplayName FROM users WHERE STRFTIME('%Y', CreationDate) = '2011'", "difficulty": "simple" }, { "question_id": 533, "question": "How many users last accessed the website after 2014/9/1?", "db_id": "codebase_community", "evidence": "LastAccessDate is greater than '2014-09-01' in the database; ratio calculated by dividing 2014 by 9;", "code": "import pandas as pd\n\n# 筛选最后访问日期在2014年9月1日之后的用户\nfiltered_users = users[pd.to_datetime(users['LastAccessDate']) > '2014-09-01']\n\n# 计算用户数量\nresult = len(filtered_users)", "sql": "SELECT COUNT(Id) FROM users WHERE date(LastAccessDate) > '2014-09-01'", "difficulty": "simple" }, { "question_id": 534, "question": "What is the display name of the user who has the most number of views?", "db_id": "codebase_community", "evidence": "user who has the most number of view refers to Max(Views)", "code": "import pandas as pd\nmax_views = users['Views'].max()\nresult = users[users['Views'] == max_views]['DisplayName']", "sql": "SELECT DisplayName FROM users WHERE Views = ( SELECT MAX(Views) FROM users )", "difficulty": "simple" }, { "question_id": 535, "question": "Among the users who have more than 100 upvotes, how many of them have more then 1 downvotes?", "db_id": "codebase_community", "evidence": "more than 100 upvotes refers to Upvotes > 100; more than 1 downvotes refers to Downvotes > 1", "code": "import pandas as pd\nresult = len(users[(users['UpVotes'] > 100) & (users['DownVotes'] > 1)])", "sql": "SELECT COUNT(Id) FROM users WHERE UpVotes > 100 AND DownVotes > 1;", "difficulty": "simple" }, { "question_id": 536, "question": "How many users with more than 10 views created their account after the year 2013?", "db_id": "codebase_community", "evidence": "more than 10 views refers to Views > 10; created after the year 2013 refers to year (CreationDate) > 2013", "code": "import pandas as pd\n\n# Filter users created after 2013 with more than 10 views\nfiltered_users = users[(pd.to_datetime(users['CreationDate']).dt.year > 2013) & (users['Views'] > 10)]\n\n# Count the number of users\nresult = len(filtered_users)", "sql": "SELECT COUNT(id) FROM users WHERE STRFTIME('%Y', CreationDate) > '2013' AND Views > 10", "difficulty": "simple" }, { "question_id": 537, "question": "How many posts does the user csgillespie own?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nresult = len(filtered)", "sql": "SELECT COUNT(T1.Id) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 538, "question": "Please list the titles of the posts owned by the user csgillespie?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user", "code": "import pandas as pd\nresult = posts[posts['OwnerUserId'].isin(users[users['DisplayName'] == 'csgillespie']['Id'])][['Title']]", "sql": "SELECT T1.Title FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 539, "question": "Who is the owner of the post \"Eliciting priors from experts\"?", "db_id": "codebase_community", "evidence": "\"Eliciting priors from experts\" is the Title of post; owner refers to DisplayName", "code": "import pandas as pd\nmerged = pd.merge(posts[posts['Title'] == 'Eliciting priors from experts'], users, left_on='OwnerUserId', right_on='Id')\nresult = merged[['DisplayName']]", "sql": "SELECT T2.DisplayName FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.Title = 'Eliciting priors from experts'", "difficulty": "simple" }, { "question_id": 540, "question": "What is the title of the post that is owned by csgillespie and has the highest popularity?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user; highest popularity refers to Max(ViewCount)", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nsorted_posts = filtered.sort_values('ViewCount', ascending=False)\nresult = sorted_posts.iloc[0]['Title']", "sql": "SELECT T1.Title FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie' ORDER BY T1.ViewCount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 541, "question": "What is the display name of the user who is the owner of the most valuable post?", "db_id": "codebase_community", "evidence": "most valuable post refers to Max(FavoriteCount)", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nmerged_sorted = merged.sort_values('FavoriteCount', ascending=False)\nresult = merged_sorted.iloc[0]['DisplayName']", "sql": "SELECT T2.DisplayName FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id ORDER BY T1.FavoriteCount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 542, "question": "What is the total number of comments of all the posts owned by csgillespie?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user; total number of comments refers to Sum(CommentCount)", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nresult = filtered['CommentCount'].sum()", "sql": "SELECT SUM(T1.CommentCount) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 543, "question": "For the post that got the most number of answers owned by csgillespie, how many answers did it get?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user; the most number of answer refers to Max(AnswerCount)", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nresult = filtered['AnswerCount'].max()", "sql": "SELECT MAX(T1.AnswerCount) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 544, "question": "What is the display name of the user who last edited the post \"Examples for teaching: Correlation does not mean causation\"?", "db_id": "codebase_community", "evidence": "\"Examples for teaching: Correlation does not mean causation\" is the Title of post; user who last edited refers to LastEditorUserId", "code": "import pandas as pd\nfiltered_posts = posts[posts['Title'] == 'Examples for teaching: Correlation does not mean causation']\nmerged = pd.merge(filtered_posts, users, left_on='LastEditorUserId', right_on='Id')\nresult = merged[['DisplayName']]", "sql": "SELECT T2.DisplayName FROM posts AS T1 INNER JOIN users AS T2 ON T1.LastEditorUserId = T2.Id WHERE T1.Title = 'Examples for teaching: Correlation does not mean causation'", "difficulty": "moderate" }, { "question_id": 545, "question": "Among the posts owned by csgillespie, how many of them are root posts?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user; root post refers to ParentId IS Null", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[(merged['DisplayName'] == 'csgillespie') & (merged['ParentId'].isna())]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.Id) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie' AND T1.ParentId IS NULL", "difficulty": "simple" }, { "question_id": 546, "question": "Please list the display names of all the users who owns a post that is well-finished.", "db_id": "codebase_community", "evidence": "the post that is well-finished refers to ClosedDate IS NOT Null", "code": "import pandas as pd\n\n# Assuming the DataFrames 'posts' and 'users' are already loaded\ndef get_well_finished_post_owners(posts_df, users_df):\n # Filter posts with non-null ClosedDate\n well_finished_posts = posts_df[posts_df['ClosedDate'].notnull()]\n\n # Merge with users DataFrame to get DisplayName\n result = pd.merge(well_finished_posts, users_df, left_on='OwnerUserId', right_on='Id', how='inner')\n\n # Select only the 'DisplayName' column and drop duplicates\n display_names = result[['DisplayName']].drop_duplicates()\n\n return display_names\n\n# Example usage:\n# display_names = get_well_finished_post_owners(posts, users)\n# print(display_names)", "sql": "SELECT T2.DisplayName FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.ClosedDate IS NOT NULL", "difficulty": "simple" }, { "question_id": 547, "question": "Among the posts owned by an elder user, how many of them have a score of over 19?", "db_id": "codebase_community", "evidence": "elder users refers to Age > 65; Score of over 19 refers to Score > = 20", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[(merged['Score'] >= 20) & (merged['Age'] > 65)]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.Id) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.Score >= 20 AND T2.Age > 65", "difficulty": "simple" }, { "question_id": 548, "question": "What is the location of the owner of the post \"Eliciting priors from experts\"?", "db_id": "codebase_community", "evidence": "Owner refers to OwnerUserId; 'Eliciting priors from experts' is the Title of post", "code": "import pandas as pd\nfiltered_posts = posts[posts['Title'] == 'Eliciting priors from experts']\nmerged = pd.merge(filtered_posts, users, left_on='OwnerUserId', right_on='Id')\nresult = merged[['Location']]", "sql": "SELECT T2.Location FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.Title = 'Eliciting priors from experts'", "difficulty": "simple" }, { "question_id": 549, "question": "From which post is the tag \"bayesian\" excerpted from? Please give the body of the post.", "db_id": "codebase_community", "evidence": "\"bayesian\" is the TagName; excerpt from refers to ExcerptPostId", "code": "import pandas as pd\nimport numpy as np\n\n# Filter tags for 'bayesian'\nbayesian_tag = tags[tags['TagName'] == 'bayesian']\n\n# Join with posts on ExcerptPostId\nresult = pd.merge(bayesian_tag, posts, left_on='ExcerptPostId', right_on='Id', how='inner')[['Body']]", "sql": "SELECT T2.Body FROM tags AS T1 INNER JOIN posts AS T2 ON T2.Id = T1.ExcerptPostId WHERE T1.TagName = 'bayesian'", "difficulty": "simple" }, { "question_id": 550, "question": "From which post is the most popular tag excerpted from? Please give the body of the post.", "db_id": "codebase_community", "evidence": "most popular tag refers to Max(Count); excerpt from refer to ExcerptPostId", "code": "import pandas as pd\n\n# Find the most popular tag (highest Count)\nmost_popular_tag = tags.nlargest(1, 'Count').iloc[0]\nexcerpt_post_id = most_popular_tag['ExcerptPostId']\n\n# Get the body of the post\nresult = posts[posts['Id'] == excerpt_post_id][['Body']]", "sql": "SELECT Body FROM posts WHERE id = ( SELECT ExcerptPostId FROM tags ORDER BY Count DESC LIMIT 1 )", "difficulty": "simple" }, { "question_id": 551, "question": "How many badges has the user csgillespie obtained?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user", "code": "import pandas as pd\nmerged = pd.merge(badges, users, left_on='UserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nresult = len(filtered)", "sql": "SELECT COUNT(T1.Id) FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 552, "question": "Please list the names of the badges obtained by csgillespie.", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user", "code": "import pandas as pd\nmerged = pd.merge(badges, users, left_on='UserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nresult = filtered[['Name']]", "sql": "SELECT T1.`Name` FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 553, "question": "Among the badges obtained by csgillespie, how many of them were obtained in the year 2011?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user; obtained in 2011 refers to YEAR (Date) = 2011", "code": "import pandas as pd\nbadges['Date'] = pd.to_datetime(badges['Date'])\nfiltered_badges = badges[badges['Date'].dt.year == 2011]\nmerged = pd.merge(filtered_badges, users, left_on='UserId', right_on='Id')\nresult = len(merged[merged['DisplayName'] == 'csgillespie'])", "sql": "SELECT COUNT(T1.Id) FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE STRFTIME('%Y', T1.Date) = '2011' AND T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 554, "question": "What is the display name of the user who has obtained the most number of badges?", "db_id": "codebase_community", "evidence": "count of Id;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge badges with users\nmerged = pd.merge(badges, users, left_on='UserId', right_on='Id', how='inner')\n\n# Group by DisplayName and count badges\nbadge_counts = merged.groupby('DisplayName').size().reset_index(name='badge_count')\n\n# Sort by badge count descending and get the top user\nresult = badge_counts.sort_values('badge_count', ascending=False).head(1)['DisplayName'].iloc[0]", "sql": "SELECT T2.DisplayName FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id GROUP BY T2.DisplayName ORDER BY COUNT(T1.Id) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 555, "question": "What is the average score of the posts owned by the user csgillespie?", "db_id": "codebase_community", "evidence": "\"csgillespie\" is the DisplayName of user; average score refers to AVG(Score)", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'csgillespie']\nresult = filtered['Score'].mean()", "sql": "SELECT AVG(T1.Score) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'csgillespie'", "difficulty": "simple" }, { "question_id": 556, "question": "What is the average number of badges obtained by a user with over 200 views?", "db_id": "codebase_community", "evidence": "user with over 200 views refers to Views > 200; average number of badges = Divide (Count(Id), Count(DisplayName))", "code": "import pandas as pd\nmerged = pd.merge(badges, users, left_on='UserId', right_on='Id', how='inner')\nfiltered = merged[merged['Views'] > 200]\nresult = len(filtered) / filtered['DisplayName'].nunique()", "sql": "SELECT CAST(COUNT(T1.Id) AS REAL) / COUNT(DISTINCT T2.DisplayName) FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.Views > 200", "difficulty": "simple" }, { "question_id": 557, "question": "Among the posts with a score of over 5, what is the percentage of them being owned by an elder user?", "db_id": "codebase_community", "evidence": "score of over 5 refers to Score > 5; elder user refers to Age > 65; percentage = Divide (Count(Id where Age>65), Count(Id)) * 100", "code": "import pandas as pd\nfiltered_posts = posts[posts['Score'] > 5]\nmerged = pd.merge(filtered_posts, users, left_on='OwnerUserId', right_on='Id')\npercentage = (merged[merged['Age'] > 65].shape[0] / merged.shape[0]) * 100\nresult = percentage", "sql": "SELECT CAST(SUM(IIF(T2.Age > 65, 1, 0)) AS REAL) * 100 / COUNT(T1.Id) FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.Score > 5", "difficulty": "moderate" }, { "question_id": 558, "question": "How many votes did the user No.58 take on 2010/7/19?", "db_id": "codebase_community", "evidence": "user no. 58 refers to UserId = 58; on 2010/7/19 refers to CreationDate = '2010-07-19'", "code": "import pandas as pd\nvotes['CreationDate'] = pd.to_datetime(votes['CreationDate'])\nfiltered_votes = votes[(votes['UserId'] == 58) & (votes['CreationDate'] == '2010-07-19')]\nresult = len(filtered_votes)", "sql": "SELECT COUNT(Id) FROM votes WHERE UserId = 58 AND CreationDate = '2010-07-19'", "difficulty": "simple" }, { "question_id": 559, "question": "Indicate the creation date of the maximum number of votes.", "db_id": "codebase_community", "evidence": "count of Id;", "code": "import pandas as pd\nvote_counts = votes.groupby('CreationDate').size().reset_index(name='count')\nresult = vote_counts.sort_values('count', ascending=False).head(1)[['CreationDate']]", "sql": "SELECT CreationDate FROM votes GROUP BY CreationDate ORDER BY COUNT(Id) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 560, "question": "Give the number of \"Revival\" badges.", "db_id": "codebase_community", "evidence": "number refers to Id; 'Revival' is the Name of badge", "code": "import pandas as pd\nresult = len(badges[badges['Name'] == 'Revival'])", "sql": "SELECT COUNT(Id) FROM badges WHERE Name = 'Revival'", "difficulty": "simple" }, { "question_id": 561, "question": "What is the title for the post which got the highest score comment?", "db_id": "codebase_community", "evidence": "highest score comment refers to Max(comments.Score)", "code": "import pandas as pd\n\n# Find the PostId with the highest score comment\nhighest_score_comment = comments[comments['Score'].notna()].nlargest(1, 'Score')\npost_id = highest_score_comment['PostId'].iloc[0]\n\n# Get the title of that post\nresult = posts[posts['Id'] == post_id][['Title']]", "sql": "SELECT Title FROM posts WHERE Id = ( SELECT PostId FROM comments WHERE Score IS NOT NULL ORDER BY Score DESC LIMIT 1 )", "difficulty": "simple" }, { "question_id": 562, "question": "For the post which got 1910 view counts, how many comments does it get?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\n\n# Filter posts with ViewCount = 1910\nfiltered_posts = posts[posts['ViewCount'] == 1910]\n\n# Merge with comments to get all comments for these posts\nmerged = pd.merge(filtered_posts[['Id']], comments, left_on='Id', right_on='PostId')\n\n# Count the number of comments\nresult = len(merged)", "sql": "SELECT COUNT(T1.Id) FROM posts AS T1 INNER JOIN comments AS T2 ON T1.Id = T2.PostId WHERE T1.ViewCount = 1910", "difficulty": "simple" }, { "question_id": 563, "question": "User No.3025 gave a comment at 20:29:39 on 2014/4/23 to a post, how many favorite counts did that post get?", "db_id": "codebase_community", "evidence": "user no. 3025 refers to UserId = '3025'; comment at 20:29:39 on 2014/4/23 refers to CreationDate = '2014/4/23 20:29:39.0'", "code": "import pandas as pd\nfiltered_comments = comments[(comments['UserId'] == 3025) & (comments['CreationDate'] == '2014-04-23 20:29:39.0')]\nmerged = pd.merge(posts, filtered_comments, left_on='Id', right_on='PostId')\nresult = merged['FavoriteCount'].iloc[0] if len(merged) > 0 else None", "sql": "SELECT T1.FavoriteCount FROM posts AS T1 INNER JOIN comments AS T2 ON T1.Id = T2.PostId WHERE T2.CreationDate = '2014-04-23 20:29:39.0' AND T2.UserId = 3025", "difficulty": "moderate" }, { "question_id": 564, "question": "Give the only one comment text of the post with parent id 107829.", "db_id": "codebase_community", "evidence": "CommentCount equals '1' in the database;", "code": "import pandas as pd\n\n# Find posts with ParentId = 107829 and CommentCount = 1\nfiltered_posts = posts[(posts['ParentId'] == 107829) & (posts['CommentCount'] == 1)]\n\n# Join with comments table to get comment text\nresult = pd.merge(filtered_posts[['Id']], comments[['PostId', 'Text']], left_on='Id', right_on='PostId', how='inner')[['Text']]", "sql": "SELECT T2.Text FROM posts AS T1 INNER JOIN comments AS T2 ON T1.Id = T2.PostId WHERE T1.ParentId = 107829 AND T1.CommentCount = 1", "difficulty": "simple" }, { "question_id": 565, "question": "User No.23853 gave a comment to a post at 9:08:18 on 2013/7/12, was that post well-finished?", "db_id": "codebase_community", "evidence": "user no. 23853 refers to UserId = '23853'; at 9:08:18 on 2013/7/12 refers to CreationDate = '2013-07-12 09:08:18.0'; not well-finished refers to ClosedDate IS NULL and vice versa", "code": "import pandas as pd\n\ndef solve_query(comments_df, posts_df):\n # Ensure datetime columns are properly converted\n if 'CreationDate' in comments_df.columns:\n comments_df['CreationDate'] = pd.to_datetime(comments_df['CreationDate'])\n if 'ClosedDate' in posts_df.columns:\n posts_df['ClosedDate'] = pd.to_datetime(posts_df['ClosedDate'])\n\n # Filter the comments DataFrame for the specific user and creation date\n filtered_comments = comments_df[(comments_df['UserId'] == 23853) & \n (comments_df['CreationDate'] == '2013-07-12 09:08:18')]\n\n # Merge with posts to get the post details\n merged_data = pd.merge(filtered_comments, posts_df, left_on='PostId', right_on='Id', how='inner')\n\n # Determine if the post is well-finished\n result = merged_data.apply(\n lambda row: 'NOT well-finished' if pd.isnull(row['ClosedDate']) else 'well-finished', axis=1\n )\n\n return result.tolist()\n\n# Example function call with placeholder DataFrames\ncomments_data = {\n 'Id': [1, 2],\n 'PostId': [101, 102],\n 'UserId': [23853, 23854],\n 'CreationDate': ['2013-07-12 09:08:18', '2013-07-13 10:00:00'],\n 'Text': ['Great post!', 'Interesting.']\n}\nposts_data = {\n 'Id': [101, 102],\n 'ClosedDate': [None, '2013-07-14 12:00:00']\n}\ncomments_df = pd.DataFrame(comments_data)\nposts_df = pd.DataFrame(posts_data)\n\nresult = solve_query(comments_df, posts_df)\nprint(result)", "sql": "SELECT IIF(T2.ClosedDate IS NULL, 'NOT well-finished', 'well-finished') AS resylt FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T1.UserId = 23853 AND T1.CreationDate = '2013-07-12 09:08:18.0'", "difficulty": "moderate" }, { "question_id": 566, "question": "For the owner user of post No. 65041, what is his/her reputation points?", "db_id": "codebase_community", "evidence": "post no. 65041 refers to Id = '65041'; reputation point refers to Reputation", "code": "import pandas as pd\nmerged = pd.merge(posts[posts['Id'] == 65041][['Id', 'OwnerUserId']], users[['Id', 'Reputation']], left_on='OwnerUserId', right_on='Id')\nresult = merged['Reputation'].iloc[0]", "sql": "SELECT T1.Reputation FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T2.Id = 65041", "difficulty": "simple" }, { "question_id": 567, "question": "For the user with the display name of \"Tiago Pasqualini\", how many posts did he/she own?", "db_id": "codebase_community", "evidence": "\"Tiago Pasqualini\" is the DisplayName;", "code": "import pandas as pd\n\n# Merge users and posts tables\nmerged = pd.merge(users, posts, left_on='Id', right_on='OwnerUserId')\n\n# Filter for the specific user\nfiltered = merged[merged['DisplayName'] == 'Tiago Pasqualini']\n\n# Count the number of posts\nresult = len(filtered)", "sql": "SELECT COUNT(T1.Id) FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.DisplayName = 'Tiago Pasqualini'", "difficulty": "simple" }, { "question_id": 568, "question": "Provide the display name of the user who made the vote No.6347.", "db_id": "codebase_community", "evidence": "Id equals '6347' in the database;", "code": "import pandas as pd\nresult = pd.merge(users, votes[votes['Id'] == 6347], left_on='Id', right_on='UserId')[['DisplayName']]", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.UserId WHERE T2.Id = 6347", "difficulty": "simple" }, { "question_id": 569, "question": "Give the number of votes for the post about data visualization.", "db_id": "codebase_community", "evidence": "About data visualization is the Title that contains 'data visualization';", "code": "import pandas as pd\n\n# Filter posts containing 'data visualization' in title\nfiltered_posts = posts[posts['Title'].str.contains('data visualization', case=False, na=False)]\n\n# Inner join with votes table\nmerged = pd.merge(filtered_posts[['Id']], votes, left_on='Id', right_on='PostId')\n\n# Count the number of votes\nresult = len(merged)", "sql": "SELECT COUNT(T2.Id) FROM posts AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.PostId WHERE T1.Title LIKE '%data visualization%'", "difficulty": "simple" }, { "question_id": 570, "question": "For the user whose display name is \"DatEpicCoderGuyWhoPrograms\", what is his/her badge's name?", "db_id": "codebase_community", "evidence": "\"DatEpicCoderGuyWhoPrograms\" is the DisplayName;", "code": "import pandas as pd\nresult = pd.merge(users[users['DisplayName'] == 'DatEpicCoderGuyWhoPrograms'], badges, left_on='Id', right_on='UserId')[['Name']]", "sql": "SELECT T2.Name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'DatEpicCoderGuyWhoPrograms'", "difficulty": "simple" }, { "question_id": 571, "question": "For the user No.24, how many times is the number of his/her posts compared to his/her votes?", "db_id": "codebase_community", "evidence": "user no. 24 refers to UserId = OwnerUserId = '24'; times of his/her post than votes = Divide (Count(post.Id), Count(votes.Id))", "code": "import pandas as pd\n\ndef solve_query(votes, posts):\n # Filter votes for UserId = 24\n votes_filtered = votes[votes['UserId'] == 24]\n\n # Filter posts for OwnerUserId = 24\n posts_filtered = posts[posts['OwnerUserId'] == 24]\n\n # Count distinct post IDs and vote IDs\n post_count = posts_filtered['Id'].nunique()\n vote_count = votes_filtered['Id'].nunique()\n\n # Calculate the ratio: votes count / posts count (matching SQL logic)\n ratio = vote_count / post_count if post_count != 0 else None\n\n return [[ratio]]", "sql": "SELECT CAST(COUNT(T2.Id) AS REAL) / COUNT(DISTINCT T1.Id) FROM votes AS T1 INNER JOIN posts AS T2 ON T1.UserId = T2.OwnerUserId WHERE T1.UserId = 24", "difficulty": "moderate" }, { "question_id": 572, "question": "How many views did the post titled 'Integration of Weka and/or RapidMiner into Informatica PowerCenter/Developer' get?", "db_id": "codebase_community", "evidence": "\"Integration of Weka and/or RapidMiner into Informatica PowerCenter/Developer\" is the Title of post; views refers to ViewCount", "code": "import pandas as pd\nresult = posts[posts['Title'] == 'Integration of Weka and/or RapidMiner into Informatica PowerCenter/Developer']['ViewCount'].values[0]", "sql": "SELECT ViewCount FROM posts WHERE Title = 'Integration of Weka and/or RapidMiner into Informatica PowerCenter/Developer'", "difficulty": "moderate" }, { "question_id": 573, "question": "Write the contents of comments with a score of 17.", "db_id": "codebase_community", "evidence": "score of 17 refers to Score = 17; contents of comments refers to Text", "code": "import pandas as pd\nresult = comments[comments['Score'] == 17][['Text']]", "sql": "SELECT Text FROM comments WHERE Score = 17", "difficulty": "simple" }, { "question_id": 574, "question": "Which user has the website URL listed at 'http://stackoverflow.com'", "db_id": "codebase_community", "evidence": "\"http://stackoverflow.com\" is the WebsiteUrl; user refers to DisplayName", "code": "import pandas as pd\nresult = users[users['WebsiteUrl'] == 'http://stackoverflow.com'][['DisplayName']]", "sql": "SELECT DisplayName FROM users WHERE WebsiteUrl = 'http://stackoverflow.com'", "difficulty": "simple" }, { "question_id": 575, "question": "What is the badge name that user 'SilentGhost' obtained?", "db_id": "codebase_community", "evidence": "\"SilentGhost\" is the DisplayName of user;", "code": "import pandas as pd\nresult = pd.merge(users[users['DisplayName'] == 'SilentGhost'], badges, left_on='Id', right_on='UserId')[['Name']]", "sql": "SELECT T2.Name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'SilentGhost'", "difficulty": "simple" }, { "question_id": 576, "question": "Name the user that commented 'thank you user93!'", "db_id": "codebase_community", "evidence": "\"thank you user93\" is the Text of comment; user refers to DisplayName", "code": "import pandas as pd\nresult = pd.merge(users, comments, left_on='Id', right_on='UserId')[lambda x: x['Text'] == 'thank you user93!'][['DisplayName']]", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN comments AS T2 ON T1.Id = T2.UserId WHERE T2.Text = 'thank you user93!'", "difficulty": "simple" }, { "question_id": 577, "question": "Write all comments made by user 'A Lion.'", "db_id": "codebase_community", "evidence": "\"A Lion\" is the DisplayName of user; comment refers to Text", "code": "import pandas as pd\nmerged = pd.merge(users, comments, left_on='Id', right_on='UserId')\nfiltered = merged[merged['DisplayName'] == 'A Lion']\nresult = filtered[['Text']]", "sql": "SELECT T2.Text FROM users AS T1 INNER JOIN comments AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'A Lion'", "difficulty": "simple" }, { "question_id": 578, "question": "Which user made a post titled 'Understanding what Dassault iSight is doing?' and how much is the reputation of the user?", "db_id": "codebase_community", "evidence": "\"Understanding what Dassault iSight is doing?\" is the Title of post; user refers to DisplayName;", "code": "import pandas as pd\n\n# Assuming the DataFrames 'users' and 'posts' are already loaded\ndef get_user_reputation(users, posts):\n # Filter posts by title\n filtered_posts = posts[posts['Title'] == 'Understanding what Dassault iSight is doing?']\n\n # Merge with users to get user details\n result = pd.merge(filtered_posts, users, left_on='OwnerUserId', right_on='Id', how='inner')\n\n # Select required columns\n result = result[['DisplayName', 'Reputation']]\n\n return result", "sql": "SELECT T1.DisplayName, T1.Reputation FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T2.Title = 'Understanding what Dassault iSight is doing?'", "difficulty": "moderate" }, { "question_id": 579, "question": "Write all comments made on the post titled 'How does gentle boosting differ from AdaBoost?'", "db_id": "codebase_community", "evidence": "\"How does gentle boosting differ from AdaBoost?\" is the Title of post; comments refers to Text", "code": "import pandas as pd\n\ndef solve_query(comments_df, posts_df):\n # Ensure the Title column exists in posts_df\n if 'Title' not in posts_df.columns:\n return pd.DataFrame({'Text': []})\n\n # Filter posts with the specified title\n target_post = posts_df[posts_df['Title'] == 'How does gentle boosting differ from AdaBoost?']\n\n # Check if the target post is empty\n if target_post.empty:\n return pd.DataFrame({'Text': []})\n\n # Get the PostId of the target post\n target_post_id = target_post['Id'].iloc[0]\n\n # Ensure the PostId column exists in comments_df\n if 'PostId' not in comments_df.columns or 'Text' not in comments_df.columns:\n return pd.DataFrame({'Text': []})\n\n # Filter comments that match the PostId\n result_comments = comments_df[comments_df['PostId'] == target_post_id][['Text']]\n\n return result_comments\n\n# Example function call (replace example DataFrames with actual data)\ncomments_data = pd.DataFrame({'Id': [1, 2, 3], 'PostId': [101, 102, 101], 'Text': ['Great post!', 'I disagree.', 'Thanks!']})\nposts_data = pd.DataFrame({'Id': [101, 102], 'Title': ['How does gentle boosting differ from AdaBoost?', 'Another Post Title']})\nresult = solve_query(comments_data, posts_data)\nprint(result)", "sql": "SELECT T1.Text FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.Title = 'How does gentle boosting differ from AdaBoost?'", "difficulty": "simple" }, { "question_id": 580, "question": "Name 10 users with the badge name 'Necromancer.'", "db_id": "codebase_community", "evidence": "\"Necromancer\" is the Name of badge; users refers to DisplayName", "code": "import pandas as pd\n\n# 读取数据表\nusers = pd.read_csv('users.csv')\nbadges = pd.read_csv('badges.csv')\n\n# 筛选 Name 为 'Necromancer' 的徽章\n# 对应 SQL: WHERE T2.Name = 'Necromancer'\nnecromancer_badges = badges[badges['Name'] == 'Necromancer']\n\n# 合并 badges 和 users 表\n# 对应 SQL: FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId\nmerged_df = pd.merge(users, necromancer_badges, left_on='Id', right_on='UserId', how='inner')\n\n# 选择 DisplayName 列并限制前 10 行\n# 对应 SQL: SELECT T1.DisplayName ... LIMIT 10\nresult = merged_df['DisplayName'].head(10)\n\nprint(result)", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Name = 'Necromancer' LIMIT 10", "difficulty": "simple" }, { "question_id": 581, "question": "Who is the editor of the post titled 'Open source tools for visualizing multi-dimensional data?'", "db_id": "codebase_community", "evidence": "'Open source tools for visualizing multi-dimensional data' is the Title of Post; editor refers to DisplayName;", "code": "import pandas as pd\nfiltered = posts[posts['Title'] == 'Open source tools for visualizing multi-dimensional data?']\nmerged = pd.merge(filtered, users, left_on='OwnerUserId', right_on='Id')\nresult = merged[['DisplayName']]", "sql": "SELECT T2.DisplayName FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.Title = 'Open source tools for visualizing multi-dimensional data?'", "difficulty": "moderate" }, { "question_id": 582, "question": "List the title of posts which were edited by Vebjorn Ljosa.", "db_id": "codebase_community", "evidence": "\"Vebjorn Ljosa\" is the DisplayName; last edited refers to LastEditorUserId", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='OwnerUserId', right_on='Id')\nresult = merged[merged['DisplayName'] == \"Vebjorn Ljosa\"][['Title']]", "sql": "SELECT T1.Title FROM posts AS T1 INNER JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T2.DisplayName = 'Vebjorn Ljosa'", "difficulty": "simple" }, { "question_id": 583, "question": "What is the total score of the posts edited by Yevgeny and include the user's website URL.", "db_id": "codebase_community", "evidence": "\"Yevgeny\" is the DisplayName; edited refers to LastEditorUserId", "code": "import pandas as pd\nmerged = pd.merge(posts, users, left_on='LastEditorUserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'Yevgeny']\nresult = filtered.groupby(['Id_y', 'WebsiteUrl'])['Score'].sum().reset_index()\nresult.columns = ['Id', 'WebsiteUrl', 'TotalScore']\nresult = result[['TotalScore', 'WebsiteUrl']]", "sql": "SELECT SUM(T1.Score) AS TotalScore, T2.WebsiteUrl FROM posts AS T1 INNER JOIN users AS T2 ON T1.LastEditorUserId = T2.Id WHERE T2.DisplayName = 'Yevgeny' GROUP BY T2.Id, T2.WebsiteUrl", "difficulty": "simple" }, { "question_id": 584, "question": "Write all the comments left by users who edited the post titled 'Why square the difference instead of taking the absolute value in standard deviation?'", "db_id": "codebase_community", "evidence": "\"Why square the difference instead of taking the absolute value in standard deviation?\" is the Title of post;", "code": "import pandas as pd\nmerged = pd.merge(posts, postHistory, left_on='Id', right_on='PostId')\nfiltered = merged[merged['Title'] == \"Why square the difference instead of taking the absolute value in standard deviation?\"]\nresult = filtered['Comment']", "sql": "SELECT T2.Comment FROM posts AS T1 INNER JOIN postHistory AS T2 ON T1.Id = T2.PostId WHERE T1.Title = 'Why square the difference instead of taking the absolute value in standard deviation?'", "difficulty": "moderate" }, { "question_id": 585, "question": "How much is the total bounty amount of the post titled about 'data'", "db_id": "codebase_community", "evidence": "About data means the title contains 'data'; total bounty Amount refers to Sum(BountyAmount)", "code": "import pandas as pd\nmerged = pd.merge(posts[posts['Title'].str.contains('data', case=False, na=False)], votes, left_on='Id', right_on='PostId')\nresult = merged['BountyAmount'].sum()", "sql": "SELECT SUM(T2.BountyAmount) FROM posts AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.PostId WHERE T1.Title LIKE '%data%'", "difficulty": "simple" }, { "question_id": 586, "question": "Which user added a bounty amount of 50 to the post title mentioning variance?", "db_id": "codebase_community", "evidence": "bounty amount of 50 refers to BountyAmount = 50; user refers to DisplayName; title mentioning variance refers to Title include 'variance'", "code": "import pandas as pd\nfiltered_posts = posts[posts['Title'].str.contains('variance', case=False, na=False)]\nfiltered_votes = votes[votes['BountyAmount'] == 50]\nmerged = pd.merge(filtered_posts, filtered_votes, left_on='Id', right_on='PostId')\nresult = pd.merge(merged, users, left_on='UserId', right_on='Id')[['DisplayName', 'Title']]", "sql": "SELECT T3.DisplayName, T1.Title FROM posts AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.PostId INNER JOIN users AS T3 ON T3.Id = T2.UserId WHERE T2.BountyAmount = 50 AND T1.Title LIKE '%variance%'", "difficulty": "challenging" }, { "question_id": 587, "question": "Calculate the average view count of each post tagged as 'humor' and list the title and the comment of each post.", "db_id": "codebase_community", "evidence": "tagged as 'humor' refers to tag = ''; comment of the post refers to Text; average view count = AVG(ViewCount)", "code": "import pandas as pd\nimport numpy as np\n\n# Merge comments with posts\nmerged = pd.merge(comments, posts, left_on='PostId', right_on='Id')\n\n# Filter posts tagged as 'humor'\nfiltered = merged[merged['Tags'] == '']\n\n# Group by Title and Text (comment), calculate average ViewCount\nresult = filtered.groupby(['Title', 'Text'])['ViewCount'].mean().reset_index()\nresult.columns = ['Title', 'Text', 'AvgViewCount']", "sql": "SELECT T2.ViewCount, T2.Title, T1.Text\nFROM posts AS T2\nLEFT JOIN comments AS T1 ON T2.Id = T1.PostId\nWHERE EXISTS (\n SELECT 1 FROM tags \n WHERE TagName = 'humor' \n AND T2.Tags LIKE '%<'||TagName||'>%'\n)\nORDER BY T2.Id", "difficulty": "moderate" }, { "question_id": 588, "question": "Give the total number of comments posted by user ID 13.", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\nresult = comments[comments['UserId'] == 13]['Id'].count()", "sql": "SELECT COUNT(Id) FROM comments WHERE UserId = 13", "difficulty": "simple" }, { "question_id": 589, "question": "Which user ID has the highest reputation?", "db_id": "codebase_community", "evidence": "highest reputation refers to Max(Reputation)", "code": "import pandas as pd\nmax_reputation = users['Reputation'].max()\nresult = users[users['Reputation'] == max_reputation][['Id']]", "sql": "SELECT Id FROM users WHERE Reputation = ( SELECT MAX(Reputation) FROM users )", "difficulty": "simple" }, { "question_id": 590, "question": "Which user ID has the lowest view?", "db_id": "codebase_community", "evidence": "lowest views refers to Min(Views)", "code": "import pandas as pd\nmin_views = users['Views'].min()\nresult = users[users['Views'] == min_views][['Id']]", "sql": "SELECT Id FROM users WHERE Views = ( SELECT MIN(Views) FROM users )", "difficulty": "simple" }, { "question_id": 591, "question": "How many users are awarded with supporter badge during year 2011?", "db_id": "codebase_community", "evidence": "\"Supporter\" is the Name of badge; in year 2011 refers to year(Date) = 2011", "code": "import pandas as pd\n\n# Convert Date column to datetime\nbadges['Date'] = pd.to_datetime(badges['Date'])\n\n# Filter for year 2011 and Name = 'Supporter'\nfiltered = badges[(badges['Date'].dt.year == 2011) & (badges['Name'] == 'Supporter')]\n\n# Count the number of records\nresult = len(filtered)", "sql": "SELECT COUNT(Id) FROM badges WHERE STRFTIME('%Y', Date) = '2011' AND Name = 'Supporter'", "difficulty": "simple" }, { "question_id": 592, "question": "How many users are awarded with more than 5 badges?", "db_id": "codebase_community", "evidence": "more than 5 badges refers to Count (Name) > 5; user refers to UserId", "code": "import pandas as pd\nuser_badge_counts = badges[badges['UserId'].notna()].groupby('UserId').size()\nusers_with_more_than_5 = user_badge_counts[user_badge_counts > 5]\nresult = len(users_with_more_than_5)", "sql": "SELECT COUNT(UserId) FROM ( SELECT UserId FROM badges WHERE UserId IS NOT NULL GROUP BY UserId HAVING COUNT(*) > 5 ) T", "difficulty": "simple" }, { "question_id": 593, "question": "How many users from New York have a teacher and supporter badge?", "db_id": "codebase_community", "evidence": "\"Supporter\" and \"Teachers\" are both Name of badge; 'New York' is the Location; user refers to UserId", "code": "import pandas as pd\nny_users = users[users['Location'] == 'New York']\nny_badges = pd.merge(badges, ny_users[['Id']], left_on='UserId', right_on='Id')\nsupporter_teacher = ny_badges[ny_badges['Name'].isin(['Supporter', 'Teacher'])]\nuser_badge_counts = supporter_teacher.groupby('UserId')['Name'].nunique()\nusers_with_both = user_badge_counts[user_badge_counts == 2]\nresult = len(users_with_both)", "sql": "SELECT COUNT(DISTINCT T1.Id) FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Name IN ('Supporter', 'Teacher') AND T2.Location = 'New York';", "difficulty": "simple" }, { "question_id": 594, "question": "Which user created post ID 1 and what is the reputation of this user?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\n\ndef solve_query(comments_df, users_df):\n # Ensure relevant columns exist and handle data types\n if 'PostId' not in comments_df.columns or 'UserId' not in comments_df.columns:\n return pd.DataFrame(columns=['Id', 'Reputation'])\n if 'Id' not in users_df.columns or 'Reputation' not in users_df.columns:\n return pd.DataFrame(columns=['Id', 'Reputation'])\n\n # Filter comments for PostId = 1\n filtered_comments = comments_df[comments_df['PostId'] == 1]\n\n # Merge with users to get user details\n merged_data = pd.merge(filtered_comments, users_df, left_on='UserId', right_on='Id', how='inner')\n\n # Select required columns\n result = merged_data[['Id_y', 'Reputation']].rename(columns={'Id_y': 'Id'})\n\n return result\n\n# Example function call with placeholder DataFrames\ndata_comments = pd.DataFrame({\n 'Id': [1, 2, 3],\n 'PostId': [1, 2, 1],\n 'UserId': [101, 102, 103]\n})\ndata_users = pd.DataFrame({\n 'Id': [101, 102, 103],\n 'Reputation': [200, 300, 400]\n})\n\nresult = solve_query(data_comments, data_users)\nprint(result)", "sql": "SELECT T2.Id, T2.Reputation FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.PostId = 1", "difficulty": "simple" }, { "question_id": 595, "question": "Which user have only one post history per post and having at least 1000 views?", "db_id": "codebase_community", "evidence": "having at least 1000 view refers to Views > = 1000; user refers to UserId", "code": "import pandas as pd\nmerged1 = pd.merge(users, postHistory, left_on='Id', right_on='UserId')\nmerged2 = pd.merge(merged1, posts, left_on='PostId', right_on='Id')\nfiltered = merged2[merged2['ViewCount'] >= 1000]\ngrouped = filtered.groupby('UserId')['PostHistoryTypeId'].nunique().reset_index(name='count')\nresult = grouped[grouped['count'] == 1]['UserId']", "sql": "SELECT T2.UserId FROM users AS T1 INNER JOIN postHistory AS T2 ON T1.Id = T2.UserId INNER JOIN posts AS T3 ON T2.PostId = T3.Id WHERE T3.ViewCount >= 1000 GROUP BY T2.UserId HAVING COUNT(DISTINCT T2.PostHistoryTypeId) = 1", "difficulty": "moderate" }, { "question_id": 596, "question": "Which users have posted the most comments. List out the user's badge?", "db_id": "codebase_community", "evidence": "count of Id;", "code": "import pandas as pd\nmerged = pd.merge(badges, comments, on='UserId')\ngrouped = merged.groupby('UserId').size().reset_index(name='count')\nsorted_group = grouped.sort_values('count', ascending=False)\ntop_id = sorted_group.iloc[0]['UserId']\nresult = badges[badges['UserId'] == top_id][['Name']]", "sql": "SELECT Name FROM badges AS T1 INNER JOIN comments AS T2 ON T1.UserId = T2.UserId GROUP BY T2.UserId ORDER BY COUNT(T2.UserId) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 597, "question": "How many users from India have the teacher badges?", "db_id": "codebase_community", "evidence": "\"India\" is the Location; \"Teacher\" is the Name of badge", "code": "import pandas as pd\nmerged = pd.merge(badges[badges['Name'] == 'Teacher'], users[users['Location'] == 'India'], left_on='UserId', right_on='Id')\nresult = merged['UserId'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.UserId) FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.Location = 'India' AND T1.Name = 'Teacher'", "difficulty": "simple" }, { "question_id": 598, "question": "What is the percentage difference of student badges given during 2010 and 2011?", "db_id": "codebase_community", "evidence": "student badges refers to badge's name = 'Student'; during 2010 refers to Year(Date) = 2010; during 2011 refers to Year(Date) = 2011; percentage difference = Subtract (Divide(Count(Name where Year(Date) = 2010), Count (Name)) *100, Divide(Count(Name where Year(Date) = 2011), Count(Name)) * 100)", "code": "import pandas as pd\n\n# Filter badges for 'Student' badges\nstudent_badges = badges[badges['Name'] == 'Student'].copy()\n\n# Convert Date to datetime and extract year\nstudent_badges['Date'] = pd.to_datetime(student_badges['Date'])\nstudent_badges['Year'] = student_badges['Date'].dt.year\n\n# Calculate counts for 2010 and 2011\ncount_2010 = (student_badges['Year'] == 2010).sum()\ncount_2011 = (student_badges['Year'] == 2011).sum()\ntotal_count = len(student_badges)\n\n# Calculate percentages\npercentage_2010 = (count_2010 / total_count) * 100\npercentage_2011 = (count_2011 / total_count) * 100\n\n# Calculate percentage difference\nresult = percentage_2010 - percentage_2011", "sql": "SELECT CAST(SUM(IIF(STRFTIME('%Y', Date) = '2010', 1, 0)) AS REAL) * 100 / COUNT(Id) - CAST(SUM(IIF(STRFTIME('%Y', Date) = '2011', 1, 0)) AS REAL) * 100 / COUNT(Id) FROM badges WHERE Name = 'Student'", "difficulty": "challenging" }, { "question_id": 599, "question": "What are the post history type IDs for post ID 3720 and how many unique users have commented on the post?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\npost_history_3720 = postHistory[postHistory['PostId'] == 3720][['PostHistoryTypeId']]\ncomment_users = comments[comments['PostId'] == 3720]['UserId'].nunique()\nresult = post_history_3720.assign(NumberOfUsers=comment_users)", "sql": "SELECT T1.PostHistoryTypeId, (SELECT COUNT(DISTINCT UserId) FROM comments WHERE PostId = 3720) AS NumberOfUsers FROM postHistory AS T1 WHERE T1.PostId = 3720", "difficulty": "simple" }, { "question_id": 600, "question": "List out all post that are related to post ID 61217 and what is the popularity of this post?", "db_id": "codebase_community", "evidence": "post related refers to RelatedPostId; popularity refers to ViewCount", "code": "import pandas as pd\n\ndef solve_query(posts_data, postlinks_data):\n # Filter postLinks for RelatedPostId == 61217\n filtered_postlinks = postlinks_data[postlinks_data['RelatedPostId'] == 61217]\n\n # Merge with posts to get ViewCount\n merged_data = pd.merge(filtered_postlinks, posts_data, left_on='PostId', right_on='Id', how='inner')\n\n # Select the ViewCount column\n result = merged_data[['ViewCount']]\n\n return result", "sql": "SELECT T1.ViewCount FROM posts AS T1 INNER JOIN postLinks AS T2 ON T1.Id = T2.PostId WHERE T2.PostId = 61217", "difficulty": "simple" }, { "question_id": 601, "question": "What is the score and the link type ID for post ID 395?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\nresult = pd.merge(posts[posts['Id'] == 395][['Id', 'Score']], postLinks[postLinks['PostId'] == 395][['PostId', 'LinkTypeId']], left_on='Id', right_on='PostId')[['Score', 'LinkTypeId']]", "sql": "SELECT T1.Score, T2.LinkTypeId FROM posts AS T1 INNER JOIN postLinks AS T2 ON T1.Id = T2.PostId WHERE T2.PostId = 395", "difficulty": "simple" }, { "question_id": 602, "question": "List out all post ID with score more than 60 and list out all the user ID that created these post.", "db_id": "codebase_community", "evidence": "Score is greater than 60 in the database;", "code": "import pandas as pd\nresult = postHistory[postHistory['PostId'].isin(posts[posts['Score'] > 60]['Id'])][['PostId', 'UserId']]", "sql": "SELECT PostId, UserId FROM postHistory WHERE PostId IN ( SELECT Id FROM posts WHERE Score > 60 )", "difficulty": "simple" }, { "question_id": 603, "question": "What is the sum of favourite count gained by user ID 686 in 2011?", "db_id": "codebase_community", "evidence": "in 2011 refers to year (CreatinDate) = 2011", "code": "import pandas as pd\n\ndef solve_query(posts_df, postHistory_df):\n # Ensure CreationDate is datetime type\n postHistory_df['CreationDate'] = pd.to_datetime(postHistory_df['CreationDate'], errors='coerce')\n\n # Filter postHistory for UserId 686 and year 2011\n filtered_postHistory = postHistory_df[\n (postHistory_df['UserId'] == 686) & \n (postHistory_df['CreationDate'].dt.year == 2011)\n ]\n\n # Extract PostId values from the filtered data\n post_ids = filtered_postHistory['PostId'].unique()\n\n # Filter posts table to include only relevant rows\n relevant_posts = posts_df[posts_df['Id'].isin(post_ids)]\n\n # Handle NULL values in FavoriteCount by filling with 0 or dropping\n if 'FavoriteCount' in relevant_posts.columns:\n favorite_counts = relevant_posts['FavoriteCount'].dropna()\n else:\n favorite_counts = pd.Series([])\n\n # Calculate sum of distinct FavoriteCount values\n result = favorite_counts.unique().sum()\n\n return result", "sql": "SELECT SUM(DISTINCT FavoriteCount) FROM posts WHERE Id IN ( SELECT PostId FROM postHistory WHERE UserId = 686 AND STRFTIME('%Y', CreationDate) = '2011' )", "difficulty": "simple" }, { "question_id": 604, "question": "What is the average of the up votes and the average user age for users creating more than 10 posts?", "db_id": "codebase_community", "evidence": "creating more than 10 post refers to Count (UserId) > 10; average of the up votes = Divide (Sum(UpVotes), Count (UserId)); average age = Divide (Sum(Age), Count(UserId))", "code": "import pandas as pd\npost_counts = posts.groupby('OwnerUserId').size().reset_index(name='post_count')\nactive_users = post_counts[post_counts['post_count'] > 10]\nmerged = pd.merge(users, active_users, left_on='Id', right_on='OwnerUserId')\nresult = pd.DataFrame({'avg_upvotes': [merged['UpVotes'].mean()], 'avg_age': [merged['Age'].mean()]})", "sql": "SELECT AVG(T1.UpVotes) AS avg_upvotes, AVG(T1.Age) AS avg_age FROM users AS T1 INNER JOIN (SELECT OwnerUserId, COUNT(*) AS post_count FROM posts GROUP BY OwnerUserId HAVING post_count > 10) AS T2 ON T1.Id = T2.OwnerUserId", "difficulty": "moderate" }, { "question_id": 605, "question": "How many users obtained the \"Announcer\" badge?", "db_id": "codebase_community", "evidence": "\"Announcer\" is the Name of badge; user refers to UserId", "code": "import pandas as pd\nresult = len(badges[badges['Name'] == 'Announcer'])", "sql": "SELECT COUNT(Id) FROM badges WHERE Name = 'Announcer';", "difficulty": "simple" }, { "question_id": 606, "question": "List out the name of badges that users obtained on 7/19/2010 7:39:08 PM.", "db_id": "codebase_community", "evidence": "Date equals '2010-07-19 19:39:08.0' in the database; ratio calculated by dividing 7 by 19;", "code": "import pandas as pd\nresult = badges[badges['Date'] == '2010-07-19 19:39:08.0'][['Name']]", "sql": "SELECT Name FROM badges WHERE Date = '2010-07-19 19:39:08.0'", "difficulty": "simple" }, { "question_id": 607, "question": "How many positive comments are there on the list?", "db_id": "codebase_community", "evidence": "score is greater than 60 in the database;", "code": "import pandas as pd\nresult = len(comments[comments['Score'] > 60])", "sql": "SELECT COUNT(id) FROM comments WHERE score > 60", "difficulty": "simple" }, { "question_id": 608, "question": "State the detailed content of the comment which was created on 7/19/2010 7:25:47 PM.", "db_id": "codebase_community", "evidence": "detailed content of the comment refers to Text; created on 7/19/2010 7:16:14 PM refers to CreationDate = '2010-07-19 19:16:14.0'", "code": "import pandas as pd\n\ndef solve_query(badges):\n # Filter rows where Name is 'Announcer'\n announcer_badges = badges[badges['Name'] == 'Announcer']\n \n # Count the number of Ids\n result = len(announcer_badges)\n \n return result", "sql": "SELECT Text FROM comments WHERE CreationDate = '2010-07-19 19:16:14.0'", "difficulty": "simple" }, { "question_id": 609, "question": "How many posts have a score of 10 on the list?", "db_id": "codebase_community", "evidence": "score of 10 refers to Score = 10; post refers to Id", "code": "import pandas as pd\nresult = len(posts[posts['Score'] == 10])", "sql": "SELECT COUNT(id) FROM posts WHERE Score = 10", "difficulty": "simple" }, { "question_id": 610, "question": "What are the name of badge that users who have the highest reputation obtained?", "db_id": "codebase_community", "evidence": "highest reputation refers to Max(Reputation); user refers to UserId", "code": "import pandas as pd\n\ndef solve_query(comments):\n # Ensure CreationDate is in datetime format\n comments['CreationDate'] = pd.to_datetime(comments['CreationDate'], errors='coerce')\n\n # Filter rows where CreationDate matches the specified timestamp\n target_date = pd.Timestamp('2010-07-19 19:16:14.0')\n result = comments[comments['CreationDate'] == target_date]\n\n # Select only the 'Text' column and return the result\n return result[['Text']] if 'Text' in result.columns else pd.DataFrame(columns=['Text'])", "sql": "SELECT T2.name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId ORDER BY T1.Reputation DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 611, "question": "Mention the reputation of users who had obtained the badge on 7/19/2010 7:39:08 PM.", "db_id": "codebase_community", "evidence": "Date equals '2010-07-19 19:39:08.0' in the database; ratio calculated by dividing 7 by 19;", "code": "import pandas as pd\n\n# Assuming the DataFrames 'users' and 'badges' are already loaded\ndate_filter = '2010-07-19 19:39:08.0'\n\n# Filter badges DataFrame for the specified date\nfiltered_badges = badges[badges['Date'] == date_filter]\n\n# Perform an inner join between users and filtered_badges on Id and UserId\nresult = pd.merge(users, filtered_badges, left_on='Id', right_on='UserId', how='inner')\n\n# Select the Reputation column from the joined DataFrame\noutput = result[['Reputation']]\n\n# Handle potential NULL values by dropping rows where Reputation is NaN (if necessary)\noutput = output.dropna(subset=['Reputation'])", "sql": "SELECT T1.Reputation FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Date = '2010-07-19 19:39:08.0'", "difficulty": "simple" }, { "question_id": 612, "question": "What is the name of badge that the user whose display name is \"Pierre\" obtained?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\nresult = pd.merge(users[users['DisplayName'] == 'Pierre'], badges, left_on='Id', right_on='UserId')[['Name']]", "sql": "SELECT T2.Name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'Pierre'", "difficulty": "simple" }, { "question_id": 613, "question": "List out the dates that users who are located in Rochester, NY obtained their badges?", "db_id": "codebase_community", "evidence": "\"Rochester, NY\" is the Location of user; user refers to UserId", "code": "import pandas as pd\nresult = pd.merge(users[users['Location'] == 'Rochester, NY'][['Id']], badges, left_on='Id', right_on='UserId')[['Date']]", "sql": "SELECT T2.Date FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.Location = 'Rochester, NY';", "difficulty": "simple" }, { "question_id": 614, "question": "Among the users who obtained the \"Teacher\" badge, calculate their percentage of users", "db_id": "codebase_community", "evidence": "count of UserId where it's \"Teacher\"; count of UserId;", "code": "import pandas as pd\nimport numpy as np\n\n# Get users with Teacher badge\nteacher_users = badges[badges['Name'] == 'Teacher']['UserId'].unique()\n\n# Calculate percentage\nteacher_count = len(teacher_users)\ntotal_users = len(users)\npercentage = (teacher_count / total_users) * 100\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(COUNT(DISTINCT T1.Id) AS REAL) * 100 / (SELECT COUNT(Id) FROM users) FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Name = 'Teacher'", "difficulty": "simple" }, { "question_id": 615, "question": "Among the users who obtained the \"Organizer\" badges, calculate the percentage of users who are teenagers.", "db_id": "codebase_community", "evidence": "\"Organizer\" is the Name of badge; teenager refers to Age BETWEEN 13 AND 18; percentage = Divide (Count(UserId where Age BETWEEN 13 AND 18), Count(UserId)) *100", "code": "import pandas as pd\norganizer_badges = badges[badges['Name'] == 'Organizer']\nmerged = pd.merge(organizer_badges, users, left_on='UserId', right_on='Id')\nteenager_count = merged[(merged['Age'] >= 13) & (merged['Age'] <= 18)]['UserId'].nunique()\ntotal_count = merged['UserId'].nunique()\nresult = (teenager_count / total_count) * 100 if total_count > 0 else 0", "sql": "SELECT CAST(SUM(IIF(T2.Age BETWEEN 13 AND 18, 1, 0)) AS REAL) * 100 / COUNT(DISTINCT T1.UserId) FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.`Name` = 'Organizer'", "difficulty": "moderate" }, { "question_id": 616, "question": "What is the comment's rating score of the post which was created on 7/19/2010 7:19:56 PM", "db_id": "codebase_community", "evidence": "CreationDate equals '2010-07-19 19:19:56.0' in the database; ratio calculated by dividing 7 by 19;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_comments = pd.read_csv('comments.csv')\ndf_posts = pd.read_csv('posts.csv')\n\n# SQL: WHERE T1.CreationDate = '2010-07-19 19:19:56.0'\n# Filter comments (T1) first. This avoids column ambiguity for the filter condition.\nfiltered_comments = df_comments[df_comments['CreationDate'] == '2010-07-19 19:19:56.0']\n\n# SQL: FROM comments AS T1 JOIN posts AS T2 ON T1.PostId = T2.Id\n# Perform Inner Join\nmerged = pd.merge(filtered_comments, df_posts, left_on='PostId', right_on='Id', how='inner')\n\n# SQL: SELECT T1.Score\n# Since both tables have a 'Score' column, Pandas renames them to Score_x (from comments/T1) and Score_y (from posts/T2).\n# We select Score_x to match T1.Score.\n# We convert to list of lists to match standard SQL execution output format [[11]].\nif 'Score_x' in merged.columns:\n result = merged[['Score_x']].values.tolist()\nelse:\n result = merged[['Score']].values.tolist()\n\nprint(result)", "sql": "SELECT T1.Score FROM comments AS T1 JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T1.CreationDate = '2010-07-19 19:19:56.0'", "difficulty": "simple" }, { "question_id": 617, "question": "What is the detailed content of the comment of the post which was created on 7/19/2010 7:37:33 PM?", "db_id": "codebase_community", "evidence": "detailed content of the comment refers to Text; created on 7/19/2010 7:37:33 PM CreationDate = 2010-07-19 19:37:33.0'", "code": "import pandas as pd\nresult = comments[comments['CreationDate'] == '2010-07-19 19:37:33.0']['Text']", "sql": "SELECT T1.Text FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T1.CreationDate = '2010-07-19 19:37:33.0'", "difficulty": "simple" }, { "question_id": 618, "question": "List out the age of users who located in Vienna, Austria obtained the badge?", "db_id": "codebase_community", "evidence": "\"Vienna, Austria\" is the Location", "code": "import pandas as pd\nmerged = pd.merge(users, badges, left_on='Id', right_on='UserId')\nfiltered = merged[merged['Location'] == 'Vienna, Austria']\nresult = filtered[['Age']]", "sql": "SELECT T1.Age FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.Location = 'Vienna, Austria'", "difficulty": "simple" }, { "question_id": 619, "question": "How many adults who obtained the badge Supporter?", "db_id": "codebase_community", "evidence": "Supporter is the Name of badge; adult refers to Age BETWEEN 19 AND 65", "code": "import pandas as pd\nmerged = pd.merge(users, badges, left_on='Id', right_on='UserId')\nfiltered = merged[(merged['Name'] == 'Supporter') & (merged['Age'] >= 19) & (merged['Age'] <= 65)]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.Id) FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Name = 'Supporter' AND T1.Age BETWEEN 19 AND 65", "difficulty": "simple" }, { "question_id": 620, "question": "State the number of views of users who obtained the badge on 7/19/2010 7:39:08 PM.", "db_id": "codebase_community", "evidence": "Date equals '2010-07-19 19:39:08.0' in the database; ratio calculated by dividing 7 by 19;", "code": "import pandas as pd\n\n# Merge users and badges tables\nmerged = pd.merge(users, badges, left_on='Id', right_on='UserId')\n\n# Filter for the specific date\nfiltered = merged[merged['Date'] == '2010-07-19 19:39:08.0']\n\n# Select only the Views column\nresult = filtered[['Views']]", "sql": "SELECT T1.Views FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Date = '2010-07-19 19:39:08.0'", "difficulty": "simple" }, { "question_id": 621, "question": "What are the name of badges that users who have the lowest reputation obtained?", "db_id": "codebase_community", "evidence": "lowest reputation refers to Min(Reputation); user refers to UserId", "code": "import pandas as pd\n\ndef solve_query(users_df, badges_df):\n # 找到最低声誉值\n min_reputation = users_df['Reputation'].min()\n \n # 筛选具有最低声誉的用户\n low_reputation_users = users_df[users_df['Reputation'] == min_reputation]\n \n # 合并用户和徽章表\n merged = pd.merge(low_reputation_users, badges_df, left_on='Id', right_on='UserId', how='inner')\n \n # 选择徽章名称列\n result = merged[['Name']]\n \n return result", "sql": "SELECT T2.Name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.Reputation = (SELECT MIN(Reputation) FROM users)", "difficulty": "simple" }, { "question_id": 622, "question": "State the name of badge that the user whose display name is \"Sharpie\" obtained.", "db_id": "codebase_community", "evidence": "\"Sharpie\" is the DisplayName of user; user refers to UserId", "code": "import pandas as pd\nimport numpy as np\n\n# Merge users and badges tables\nmerged = pd.merge(users[users['DisplayName'] == 'Sharpie'], badges, left_on='Id', right_on='UserId')\n\n# Select the Name column\nresult = merged[['Name']]", "sql": "SELECT T2.Name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'Sharpie'", "difficulty": "simple" }, { "question_id": 623, "question": "How many elders obtained the \"Supporter\" badge?", "db_id": "codebase_community", "evidence": "\"Supporter\" is the Name of badge;  elders refers to Age > 65", "code": "import pandas as pd\nimport numpy as np\n\n# Merge users and badges tables\nmerged = pd.merge(users, badges, left_on='Id', right_on='UserId')\n\n# Filter for users over 65 with 'Supporter' badge\nfiltered = merged[(merged['Age'] > 65) & (merged['Name'] == 'Supporter')]\n\n# Count distinct user IDs\nresult = filtered['Id_x'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.Id) FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T1.Age > 65 AND T2.Name = 'Supporter'", "difficulty": "simple" }, { "question_id": 624, "question": "What is the name of user with the ID of 30?", "db_id": "codebase_community", "evidence": "name of user refers to DisplayName;", "code": "import pandas as pd\nresult = users[users['Id'] == 30]['DisplayName']", "sql": "SELECT DisplayName FROM users WHERE Id = 30", "difficulty": "simple" }, { "question_id": 625, "question": "How many users were from New York?", "db_id": "codebase_community", "evidence": "New York refers to Location;", "code": "import pandas as pd\nresult = len(users[users['Location'] == 'New York'])", "sql": "SELECT COUNT(Id) FROM users WHERE Location = 'New York';", "difficulty": "simple" }, { "question_id": 626, "question": "How many votes were made in 2010?", "db_id": "codebase_community", "evidence": "YEAR(CreationDate) = 2010;", "code": "import pandas as pd\nvotes['CreationDate'] = pd.to_datetime(votes['CreationDate'])\nresult = len(votes[votes['CreationDate'].dt.year == 2010])", "sql": "SELECT COUNT(id) FROM votes WHERE STRFTIME('%Y', CreationDate) = '2010'", "difficulty": "simple" }, { "question_id": 627, "question": "How many users were adult?", "db_id": "codebase_community", "evidence": "adult refers to user where Age BETWEEN 19 and 65;", "code": "import pandas as pd\nresult = users[(users['Age'] >= 19) & (users['Age'] <= 65)]['Id'].count()", "sql": "SELECT COUNT(id) FROM users WHERE Age BETWEEN 19 AND 65", "difficulty": "simple" }, { "question_id": 628, "question": "Which users have the highest number of views?", "db_id": "codebase_community", "evidence": "users have the highest number of views refer to DisplayName where MAX(Views);", "code": "import pandas as pd\nmax_views = users['Views'].max()\nresult = users[users['Views'] == max_views][['Id', 'DisplayName']]", "sql": "SELECT Id, DisplayName FROM users WHERE Views = ( SELECT MAX(Views) FROM users )", "difficulty": "simple" }, { "question_id": 629, "question": "Calculate the ratio of votes in 2010 and 2011.", "db_id": "codebase_community", "evidence": "count of Id where YEAR(CreationDate;", "code": "import pandas as pd\nvotes['Year'] = pd.to_datetime(votes['CreationDate']).dt.year\nvotes_2010 = votes[votes['Year'] == 2010].shape[0]\nvotes_2011 = votes[votes['Year'] == 2011].shape[0]\nresult = votes_2010 / votes_2011", "sql": "SELECT CAST(SUM(IIF(STRFTIME('%Y', CreationDate) = '2010', 1, 0)) AS REAL) / SUM(IIF(STRFTIME('%Y', CreationDate) = '2011', 1, 0)) FROM votes", "difficulty": "simple" }, { "question_id": 630, "question": "What is the name of tags used by John Salvatier's?", "db_id": "codebase_community", "evidence": "DisplayName equals 'John Salvatier' in the database;", "code": "import pandas as pd\n\ndef solve_query(users_df, postHistory_df, posts_df):\n # 筛选用户名为'John Salvatier'的用户\n filtered_users = users_df[users_df['DisplayName'] == 'John Salvatier']\n \n # 连接users和postHistory表\n merged_1 = pd.merge(filtered_users, postHistory_df, left_on='Id', right_on='UserId', how='inner')\n \n # 连接postHistory和posts表\n merged_2 = pd.merge(merged_1, posts_df, left_on='PostId', right_on='Id', how='inner')\n \n # 选择Tags列\n result = merged_2[['Tags']]\n \n return result", "sql": "SELECT T3.Tags FROM users AS T1 INNER JOIN postHistory AS T2 ON T1.Id = T2.UserId INNER JOIN posts AS T3 ON T2.PostId = T3.Id WHERE T1.DisplayName = 'John Salvatier'", "difficulty": "simple" }, { "question_id": 631, "question": "How many posts were created by Daniel Vassallo?", "db_id": "codebase_community", "evidence": "DisplayName equals 'Daniel Vassallo' in the database;", "code": "import pandas as pd\nuser_id = users[users['DisplayName'] == 'Daniel Vassallo']['Id'].iloc[0]\nresult = len(postHistory[postHistory['UserId'] == user_id])", "sql": "SELECT COUNT(T1.Id) FROM users AS T1 INNER JOIN postHistory AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'Daniel Vassallo'", "difficulty": "simple" }, { "question_id": 632, "question": "How many votes were made by Harlan?", "db_id": "codebase_community", "evidence": "DisplayName equals 'Harlan' in the database;", "code": "import pandas as pd\n\ndef solve_query(users_df, votes_df):\n # 筛选用户名为'Harlan'的用户\n filtered_users = users_df[users_df['DisplayName'] == 'Harlan']\n \n # 连接users和votes表\n merged = pd.merge(filtered_users, votes_df, left_on='Id', right_on='UserId', how='inner')\n \n # 计算投票数量\n result = len(merged)\n \n return result", "sql": "SELECT COUNT(T2.Id) FROM users AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'Harlan'", "difficulty": "simple" }, { "question_id": 633, "question": "Which post by slashnick has the most answers count? State the post ID.", "db_id": "codebase_community", "evidence": "most answers count refers to MAX(AnswerCount); post by slashnick refers to DisplayName = 'slashnick';", "code": "import pandas as pd\n\n# Filter users for slashnick\nslashnick_user = users[users['DisplayName'] == 'slashnick']\n\n# Get the user ID\nuser_id = slashnick_user['Id'].iloc[0]\n\n# Filter postHistory for this user\nuser_posts = postHistory[postHistory['UserId'] == user_id]\n\n# Merge with posts to get AnswerCount\nmerged = pd.merge(user_posts, posts, left_on='PostId', right_on='Id')\n\n# Sort by AnswerCount in descending order and get the top post\nresult = merged.sort_values('AnswerCount', ascending=False).head(1)['PostId'].iloc[0]", "sql": "SELECT Id FROM posts WHERE OwnerUserId = (SELECT Id FROM users WHERE DisplayName = 'slashnick') ORDER BY AnswerCount DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 634, "question": "Among posts by Harvey Motulsky and Noah Snyder, which one has higher popularity?", "db_id": "codebase_community", "evidence": "DisplayName equals 'Harvey Motulsky' in the database; DisplayName equals 'Noah Snyder' in the database; sum of ViewCount;", "code": "import pandas as pd\nfiltered_users = users[users['DisplayName'].isin(['Harvey Motulsky', 'Noah Snyder'])]\nmerged = pd.merge(filtered_users, posts, left_on='Id', right_on='OwnerUserId')\ngrouped = merged.groupby('DisplayName')['ViewCount'].sum().reset_index()\nresult = grouped.sort_values('ViewCount', ascending=False).head(1)['DisplayName'].iloc[0]", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN posts AS T3 ON T1.Id = T3.OwnerUserId WHERE T1.DisplayName IN ('Harvey Motulsky', 'Noah Snyder') GROUP BY T1.DisplayName ORDER BY SUM(T3.ViewCount) DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 635, "question": "How many posts by Matt Parker have more than 4 votes?", "db_id": "codebase_community", "evidence": "DisplayName equals 'Matt Parker' in the database; PostId is greater than 4 in the database;", "code": "import pandas as pd\n# 找到所有Matt Parker的用户ID\nuser_ids = users[users['DisplayName'] == 'Matt Parker']['Id']\n# 筛选对应的帖子\nposts_matt = posts[posts['OwnerUserId'].isin(user_ids)]\n# 获取帖子ID\npost_ids = posts_matt['Id']\n# 筛选投票记录\nvotes_matt = votes[votes['PostId'].isin(post_ids)]\n# 分组统计投票数\nvote_counts = votes_matt.groupby('PostId').size().reset_index(name='count')\n# 过滤并统计结果\nresult = vote_counts[vote_counts['count'] > 4].shape[0]", "sql": "SELECT COUNT(DISTINCT T1.Id) \nFROM users AS T1 \nINNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId \nINNER JOIN votes AS T3 ON T2.Id = T3.PostId \nWHERE T1.DisplayName = 'Matt Parker' \nGROUP BY T2.Id \nHAVING COUNT(T3.Id) > 4", "difficulty": "moderate" }, { "question_id": 636, "question": "How many negative comments did Neil McGuigan get in his posts?", "db_id": "codebase_community", "evidence": "Negative comment refers to score < 60; DisplayName = 'Neil McGuigan';", "code": "import pandas as pd\n\nusers = pd.read_csv('users.csv')\nposts = pd.read_csv('posts.csv')\ncomments = pd.read_csv('comments.csv')\n\n# 1. 筛选特定用户 (SQL: WHERE T1.DisplayName = 'Neil McGuigan')\ntarget_user = users[users['DisplayName'] == 'Neil McGuigan']\n\n# 2. 连接 Users 和 Posts (SQL: T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId)\n# 注意:两个表都有 'Id',合并后 users.Id 变为 Id_x,posts.Id 变为 Id_y\nuser_posts = pd.merge(target_user, posts, left_on='Id', right_on='OwnerUserId')\n\n# 3. 连接 Posts 和 Comments (SQL: INNER JOIN comments AS T3 ON T2.Id = T3.PostId)\n# 注意:user_posts 中的 Post ID 是 'Id_y'\n# 注意:posts 和 comments 都有 'Score' 列。合并后 posts.Score 变为 Score_x,comments.Score 变为 Score_y\nmerged_all = pd.merge(user_posts, comments, left_on='Id_y', right_on='PostId')\n\n# 4. 筛选评论分数 (SQL: AND T3.Score < 60)\n# T3 是 comments 表,对应 Score_y\nnegative_comments = merged_all[merged_all['Score_y'] < 60]\n\n# 5. 计数 (SQL: COUNT(T3.Id))\nresult = len(negative_comments)\n\nprint(result)", "sql": "SELECT COUNT(T3.Id) FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId INNER JOIN comments AS T3 ON T2.Id = T3.PostId WHERE T1.DisplayName = 'Neil McGuigan' AND T3.Score < 60", "difficulty": "simple" }, { "question_id": 637, "question": "State all the tags used by Mark Meckes in his posts that doesn't have comments.", "db_id": "codebase_community", "evidence": "used by Mark Meckes refers to DisplayName = 'Mark Meckes'; Doen't have comments refers to CommentCount = 0;T3.Tags refers to Tags column in posts table", "code": "import pandas as pd\n# 假设users和posts已作为DataFrame存在\nmark_user = users[users['DisplayName'] == 'Mark Meckes']\nmark_id = mark_user['Id'].values[0]\nresult = posts[(posts['OwnerUserId'] == mark_id) & (posts['CommentCount'] == 0)][['Tags']]", "sql": "SELECT T2.Tags FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.DisplayName = 'Mark Meckes' AND T2.CommentCount = 0", "difficulty": "moderate" }, { "question_id": 638, "question": "List all the name of users that obtained the Organizer Badges.", "db_id": "codebase_community", "evidence": "name of users refers to DisplayName; the Organizer Badges refer to badges where Name = 'Organizer';", "code": "import pandas as pd\n\ndef solve_query(users_df, badges_df):\n # 筛选名称为'Organizer'的徽章\n filtered_badges = badges_df[badges_df['Name'] == 'Organizer']\n \n # 连接users和badges表\n merged = pd.merge(users_df, filtered_badges, left_on='Id', right_on='UserId', how='inner')\n \n # 选择DisplayName列\n result = merged[['DisplayName']]\n \n return result", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Name = 'Organizer'", "difficulty": "simple" }, { "question_id": 639, "question": "Based on posts posted by Community, calculate the percentage of posts that use the R language.", "db_id": "codebase_community", "evidence": "DIVIDE(COUNT(PostId WHERE TagName = 'r')), (COUNT(PostId WHERE DisplayName = 'Community')) as percentage; R language refers to tagname = 'r'tags linked to posts via ExcerptPostId; posts posted by Community refers to OwnerUserId = users.Id", "code": "import pandas as pd\ncommunity_ids = users[users['DisplayName'] == 'Community']['Id']\nph_community = postHistory[postHistory['UserId'].isin(community_ids)]\nmerged = pd.merge(ph_community, tags, left_on='PostId', right_on='ExcerptPostId')\nis_r = (merged['TagName'] == 'r').sum()\ntotal = len(merged)\nresult = pd.DataFrame({'percentage': [is_r / total * 100]})", "sql": "SELECT CAST(SUM(IIF(tags.TagName = 'r', 1, 0)) AS REAL) * 100 / COUNT(*) AS percentage FROM users INNER JOIN postHistory ON users.Id = postHistory.UserId INNER JOIN tags ON tags.ExcerptPostId = postHistory.PostId WHERE users.DisplayName = 'Community'", "difficulty": "challenging" }, { "question_id": 640, "question": "Calculate the difference in view count from post posted by Mornington and view count from posts posted by Amos.", "db_id": "codebase_community", "evidence": "DisplayName equals 'Mornington' in the database; DisplayName equals 'Amos' in the database; sum of ViewCount where DisplayName = 'Mornington'; sum of ViewCount where DisplayName = 'Amos';ViewCount refers to T3.ViewCount; DisplayName refers to T1.DisplayName", "code": "import pandas as pd\nmerged = pd.merge(users, posts, left_on='Id', right_on='OwnerUserId')\nmornington_views = merged[merged['DisplayName'] == 'Mornington']['ViewCount'].sum()\namos_views = merged[merged['DisplayName'] == 'Amos']['ViewCount'].sum()\nresult = pd.DataFrame({'diff': [mornington_views - amos_views]})", "sql": "SELECT SUM(IIF(T1.DisplayName = 'Mornington', T2.ViewCount, 0)) - SUM(IIF(T1.DisplayName = 'Amos', T2.ViewCount, 0)) AS diff FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.DisplayName IN ('Mornington', 'Amos')", "difficulty": "moderate" }, { "question_id": 641, "question": "How many users received commentator badges in 2014?", "db_id": "codebase_community", "evidence": "Commentator is the name of the badge; year(Date) = 2014;", "code": "import pandas as pd\nresult = len(badges[(badges['Name'] == 'Commentator') & (pd.to_datetime(badges['Date']).dt.year == 2014)])", "sql": "SELECT COUNT(Id) FROM badges WHERE Name = 'Commentator' AND STRFTIME('%Y', Date) = '2014'", "difficulty": "simple" }, { "question_id": 642, "question": "How many posts were created on 21st July, 2010?", "db_id": "codebase_community", "evidence": "created on 21st July, 2010 refers to CreationDate BETWEEN '2010-07-21 00:00:00' and '2012-07-21 23:59:59';created on 21st July, 2010 refers to CreationDate BETWEEN '2010-07-21 00:00:00' and '2010-07-21 23:59:59'; CreationDate in posts table refers to post creation time", "code": "import pandas as pd\nposts['CreaionDate'] = pd.to_datetime(posts['CreaionDate'])\nresult = posts[posts['CreaionDate'].dt.strftime('%Y-%m-%d') == '2010-07-21'].shape[0]", "sql": "SELECT COUNT(Id) FROM posts WHERE date(CreaionDate) = '2010-07-21'", "difficulty": "simple" }, { "question_id": 643, "question": "What are the display names and ages of user who got the highest in views?", "db_id": "codebase_community", "evidence": "the highest in views refers to MAX(Views);", "code": "import pandas as pd\nmax_views = users['Views'].max()\nresult = users[users['Views'] == max_views][['DisplayName', 'Age']]", "sql": "SELECT DisplayName, Age FROM users WHERE Views = ( SELECT MAX(Views) FROM users )", "difficulty": "simple" }, { "question_id": 644, "question": "Provide the last edit date and last edit user ID for the post \"Detecting a given face in a database of facial images\".", "db_id": "codebase_community", "evidence": "Title equals 'Detecting a given face in a database of facial images' in the database;", "code": "import pandas as pd\nresult = posts[posts['Title'] == 'Detecting a given face in a database of facial images'][['LastEditDate', 'LastEditorUserId']]", "sql": "SELECT LastEditDate, LastEditorUserId FROM posts WHERE Title = 'Detecting a given face in a database of facial images'", "difficulty": "simple" }, { "question_id": 645, "question": "How many negative comments were given by user ID 13?", "db_id": "codebase_community", "evidence": "Score is less than 60 in the database;", "code": "import pandas as pd\nresult = len(comments[(comments['UserId'] == 13) & (comments['Score'] < 60)])", "sql": "SELECT COUNT(Id) FROM comments WHERE UserId = 13 AND Score < 60", "difficulty": "simple" }, { "question_id": 646, "question": "Describe the post title which got positive comments and display names of the users who posted those comments.", "db_id": "codebase_community", "evidence": "Score is greater than 60 in the database;", "code": "import pandas as pd\n\n# Filter posts with Score > 60\nfiltered_posts = posts[posts['Score'] > 60][['Id', 'Title']]\n\n# Filter comments with positive scores (Score > 0)\npositive_comments = comments[comments['Score'] > 0][['PostId', 'UserDisplayName']]\n\n# Join filtered posts with positive comments\nresult = pd.merge(filtered_posts, positive_comments, left_on='Id', right_on='PostId')[['Title', 'UserDisplayName']]", "sql": "SELECT T1.Title, T2.UserDisplayName FROM posts AS T1 INNER JOIN comments AS T2 ON T2.PostId = T1.Id WHERE T2.Score > 60", "difficulty": "simple" }, { "question_id": 647, "question": "Provide the badge names received in 2011 for the user whose location is in the North Pole.", "db_id": "codebase_community", "evidence": "received in 2011 refers to year(Date) = 2011;", "code": "import pandas as pd\n\ndef solve_query(users_df, badges_df):\n # 筛选位置为'North Pole'的用户\n filtered_users = users_df[users_df['Location'] == 'North Pole']\n \n # 连接users和badges表\n merged = pd.merge(filtered_users, badges_df, left_on='Id', right_on='UserId', how='inner')\n \n # 将Date列转换为datetime类型并筛选2011年的徽章\n merged['Date'] = pd.to_datetime(merged['Date'], errors='coerce')\n filtered_badges = merged[merged['Date'].dt.year == 2011]\n \n # 选择Name列\n result = filtered_badges[['Name']]\n \n return result", "sql": "SELECT T2.Name FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE STRFTIME('%Y', T2.Date) = '2011' AND T1.Location = 'North Pole'", "difficulty": "simple" }, { "question_id": 648, "question": "Provide the users' display names and available website URLs of the post with favorite count of more than 150.", "db_id": "codebase_community", "evidence": "favorite count of more than 150 refers to FavoriteCount > 150;", "code": "import pandas as pd\nfiltered_posts = posts[posts['FavoriteCount'] > 150]\nmerged = pd.merge(filtered_posts, users, left_on='OwnerUserId', right_on='Id')\nresult = merged[['DisplayName', 'WebsiteUrl']]", "sql": "SELECT T1.DisplayName, T1.WebsiteUrl FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T2.FavoriteCount > 150", "difficulty": "simple" }, { "question_id": 649, "question": "Describe the post history counts and last edit date of the post title \"What is the best introductory Bayesian statistics textbook?\"", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Merge postHistory with posts on PostId = Id\nmerged = pd.merge(postHistory, posts, left_on='PostId', right_on='Id', suffixes=('_history', '_post'))\n\n# Filter for the specific title\nfiltered = merged[merged['Title'] == 'What is the best introductory Bayesian statistics textbook?']\n\n# Select only the required columns: postHistory.Id and posts.LastEditDate\nresult = filtered[['Id_history', 'LastEditDate']].rename(columns={'Id_history': 'Id'})", "sql": "SELECT T1.Id, T2.LastEditDate FROM postHistory AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.Title = 'What is the best introductory Bayesian statistics textbook?'", "difficulty": "simple" }, { "question_id": 650, "question": "Describe the last accessed date and location of the users who received the outliers badge.", "db_id": "codebase_community", "evidence": "Outliers is the name of the badge;Outliers refers to the badge name 'outliers'", "code": "import pandas as pd\nresult = users.merge(badges, left_on='Id', right_on='UserId').query(\"Name == 'outliers'\")[['LastAccessDate', 'Location']]", "sql": "SELECT T1.LastAccessDate, T1.Location FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.Name = 'outliers'", "difficulty": "simple" }, { "question_id": 651, "question": "Provide the related post title of \"How to tell if something happened in a data set which monitors a value over time\".", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\n\n# Find posts with the specific title\ntarget_posts = posts[posts['Title'] == 'How to tell if something happened in a data set which monitors a value over time']\n\n# Get PostIds from target posts\npost_ids = target_posts['Id'].values\n\n# Find post links where PostId matches our target posts\nrelated_links = postLinks[postLinks['PostId'].isin(post_ids)]\n\n# Get related post IDs\nrelated_post_ids = related_links['RelatedPostId'].values\n\n# Get the titles of related posts\nrelated_posts = posts[posts['Id'].isin(related_post_ids)]\n\nresult = related_posts[['Title']]", "sql": "SELECT T3.Title FROM postLinks AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id INNER JOIN posts AS T3 ON T1.RelatedPostId = T3.Id WHERE T2.Title = 'How to tell if something happened in a data set which monitors a value over time'", "difficulty": "simple" }, { "question_id": 652, "question": "List the post IDs and badge names of the user Samuel in 2013.", "db_id": "codebase_community", "evidence": "Samuel refers to UserDisplayName; YEAR(CreationDate) = 2013 relates to PostId; YEAR(Date) = 2013 relates to the badge;", "code": "import pandas as pd\nmerged = pd.merge(postHistory, badges, on='UserId')\nfiltered = merged[(merged['UserDisplayName'] == 'Samuel') & (pd.to_datetime(merged['CreationDate']).dt.year == 2013) & (pd.to_datetime(merged['Date']).dt.year == 2013)]\nresult = filtered[['PostId', 'Name']]", "sql": "SELECT T1.PostId, T2.Name FROM postHistory AS T1 INNER JOIN badges AS T2 ON T1.UserId = T2.UserId WHERE T1.UserDisplayName = 'Samuel' AND STRFTIME('%Y', T1.CreationDate) = '2013' AND STRFTIME('%Y', T2.Date) = '2013'", "difficulty": "moderate" }, { "question_id": 653, "question": "What is the owner's display name of the most popular post?", "db_id": "codebase_community", "evidence": "Higher view count means the post has higher popularity; the most popular post refers to MAX(ViewCount);", "code": "import pandas as pd\n\n# Get the post with maximum ViewCount\nmost_popular_post = posts.nlargest(1, 'ViewCount').iloc[0]\n\n# Get the owner's display name from users table\nresult = users[users['Id'] == most_popular_post['OwnerUserId']]['DisplayName'].iloc[0]", "sql": "SELECT DisplayName FROM users WHERE Id = (SELECT OwnerUserId FROM posts ORDER BY ViewCount DESC LIMIT 1);", "difficulty": "simple" }, { "question_id": 654, "question": "Mention the display name and location of the user who owned the excerpt post with hypothesis-testing tag.", "db_id": "codebase_community", "evidence": "user who owned the excerpt post with hypothesis-testing tag refers to OwnerUserId WHERE TagName = 'hypothesis-testing';", "code": "import pandas as pd\n\n# Filter tags for hypothesis-testing\nhypothesis_tag = tags[tags['TagName'] == 'hypothesis-testing']\n\n# Merge with posts to get OwnerUserId\nmerged = pd.merge(hypothesis_tag, posts, left_on='ExcerptPostId', right_on='Id')\n\n# Merge with users to get DisplayName and Location\nresult = pd.merge(merged, users, left_on='OwnerUserId', right_on='Id')[['DisplayName', 'Location']]", "sql": "SELECT T3.DisplayName, T3.Location FROM tags AS T1 INNER JOIN posts AS T2 ON T1.ExcerptPostId = T2.Id INNER JOIN users AS T3 ON T3.Id = T2.OwnerUserId WHERE T1.TagName = 'hypothesis-testing'", "difficulty": "moderate" }, { "question_id": 655, "question": "Write down the related posts titles and link type IDs of the post \"What are principal component scores?\".", "db_id": "codebase_community", "evidence": "Title equals 'What are principal component scores?' in the database;", "code": "import pandas as pd\n\n# Filter posts to find the post with the specific title\npost = posts[posts['Title'] == 'What are principal component scores?']\n\n# Get the post ID\npost_id = post['Id'].iloc[0]\n\n# Filter postLinks where PostId matches our post\nrelated_links = postLinks[postLinks['PostId'] == post_id]\n\n# Merge with posts table to get related post titles\nresult = pd.merge(related_links, posts, left_on='RelatedPostId', right_on='Id', suffixes=('_link', '_related'))\n\n# Select only the Title and LinkTypeId columns\nresult = result[['Title', 'LinkTypeId']]", "sql": "SELECT T3.Title, T2.LinkTypeId FROM posts AS T1 INNER JOIN postLinks AS T2 ON T1.Id = T2.PostId INNER JOIN posts AS T3 ON T2.RelatedPostId = T3.Id WHERE T1.Title = 'What are principal component scores?'", "difficulty": "simple" }, { "question_id": 656, "question": "Describe the display name of the parent ID for child post with the highest score.", "db_id": "codebase_community", "evidence": "If the parent id is not null, the post is the child post; the highest score refers to MAX(Score);ParentId refers to the Id of the parent post; OwnerUserId of the parent post refers to the user who owns the parent post", "code": "import pandas as pd\nparent_id = posts[posts['ParentId'].notnull()].sort_values('Score', ascending=False).iloc[0]['ParentId']\nowner_user_id = posts[posts['Id'] == parent_id]['OwnerUserId'].iloc[0]\nresult = users[users['Id'] == owner_user_id]['DisplayName'].iloc[0]", "sql": "SELECT u.DisplayName FROM users u WHERE u.Id = ( SELECT p_parent.OwnerUserId FROM posts p_child INNER JOIN posts p_parent ON p_child.ParentId = p_parent.Id WHERE p_child.ParentId IS NOT NULL ORDER BY p_child.Score DESC LIMIT 1 )", "difficulty": "simple" }, { "question_id": 657, "question": "Under the vote type of 8, provide the display names and websites URLs of the user who got the highest bounty amount.", "db_id": "codebase_community", "evidence": "vote type of 8 refers to VoteTypeId = 8; the highest bounty amount refers to MAX(BountyAmount);", "code": "import pandas as pd\nvotes_filtered = votes[votes['VoteTypeId'] == 8]\nmax_bounty_vote = votes_filtered.loc[votes_filtered['BountyAmount'].idxmax()]\nuser_id = max_bounty_vote['UserId']\nresult = users[users['Id'] == user_id][['DisplayName', 'WebsiteUrl']]", "sql": "SELECT DisplayName, WebsiteUrl FROM users WHERE Id = ( SELECT UserId FROM votes WHERE VoteTypeId = 8 ORDER BY BountyAmount DESC LIMIT 1 )", "difficulty": "moderate" }, { "question_id": 658, "question": "What are the titles of the top 5 posts with the highest popularity?", "db_id": "codebase_community", "evidence": "Higher view count means the post has higher popularity; the highest popularity refers to MAX(ViewCount);", "code": "import pandas as pd\nresult = posts.nlargest(5, 'ViewCount')[['Title']]", "sql": "SELECT Title FROM posts ORDER BY ViewCount DESC LIMIT 5", "difficulty": "simple" }, { "question_id": 659, "question": "How many tags have post count between 5,000 to 7,000?", "db_id": "codebase_community", "evidence": "post count between 5,000 to 7,000 refers to Count BETWEEN 5000 and 7000;", "code": "import pandas as pd\nresult = len(tags[(tags['Count'] >= 5000) & (tags['Count'] <= 7000)])", "sql": "SELECT COUNT(Id) FROM tags WHERE Count BETWEEN 5000 AND 7000", "difficulty": "simple" }, { "question_id": 660, "question": "What is the owner user id of the most valuable post?", "db_id": "codebase_community", "evidence": "the most valuable post refers to MAX(FavoriteCount);", "code": "import pandas as pd\n\nmax_favorite = posts['FavoriteCount'].max()\nresult = posts[posts['FavoriteCount'] == max_favorite]['OwnerUserId']", "sql": "SELECT OwnerUserId FROM posts WHERE FavoriteCount = ( SELECT MAX(FavoriteCount) FROM posts )", "difficulty": "simple" }, { "question_id": 661, "question": "How old is the most influential user?", "db_id": "codebase_community", "evidence": "How old describes age; the most influential refers to user where MAX(Reputation);", "code": "import pandas as pd\nmax_reputation = users['Reputation'].max()\nresult = users[users['Reputation'] == max_reputation]['Age'].values[0]", "sql": "SELECT Age FROM users WHERE Reputation = ( SELECT MAX(Reputation) FROM users )", "difficulty": "simple" }, { "question_id": 662, "question": "How many posts with votes that were created in 2011 have a bounty of 50?", "db_id": "codebase_community", "evidence": "BountyAmount equals 50 in the database;", "code": "import pandas as pd\n\ndef solve_query(posts_data, votes_data):\n try:\n # Ensure the required columns exist\n if 'Id' not in posts_data.columns or 'PostId' not in votes_data.columns or 'BountyAmount' not in votes_data.columns or 'CreationDate' not in votes_data.columns:\n return pd.DataFrame({'count': [0]})\n\n # Convert CreationDate to datetime\n votes_data['CreationDate'] = pd.to_datetime(votes_data['CreationDate'], errors='coerce')\n\n # Filter votes with BountyAmount = 50 and created in 2011\n filtered_votes = votes_data[(votes_data['BountyAmount'] == 50) & (votes_data['CreationDate'].dt.year == 2011)]\n\n # Merge posts and filtered votes on PostId and Id\n merged_data = pd.merge(posts_data, filtered_votes, left_on='Id', right_on='PostId', how='inner')\n\n # Count the number of matching posts\n result_count = len(merged_data)\n return pd.DataFrame({'count': [result_count]})\n\n except Exception as e:\n return pd.DataFrame({'count': [0]})\n\n# Example usage with placeholder DataFrames\nposts_df = pd.DataFrame({'Id': [1, 2, 3]})\nvotes_df = pd.DataFrame({'PostId': [1, 2], 'BountyAmount': [50, 50], 'CreationDate': ['2011-05-01', '2011-08-15']})\n\nresult = solve_query(posts_df, votes_df)\nprint(result)", "sql": "SELECT COUNT(T1.Id) FROM posts AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.PostId WHERE T2.BountyAmount = 50 AND STRFTIME('%Y', T2.CreationDate) = '2011'", "difficulty": "simple" }, { "question_id": 663, "question": "What is the id of the youngest user?", "db_id": "codebase_community", "evidence": "the youngest user refers to MIN(Age);", "code": "import pandas as pd\nimport numpy as np\n\nmin_age = users['Age'].min()\nresult = users[users['Age'] == min_age][['Id']]", "sql": "SELECT Id FROM users WHERE Age = ( SELECT MIN(Age) FROM users )", "difficulty": "simple" }, { "question_id": 664, "question": "What is the sum of score of the post on 2010-07-19?", "db_id": "codebase_community", "evidence": "on 2010-07-19 refers to LasActivityDate LIKE '2010-07-19%';", "code": "import pandas as pd\nfiltered = posts[posts['LasActivityDate'].str.startswith('2010-07-19')]\nresult = filtered['Score'].sum()", "sql": "SELECT SUM(Score) FROM posts WHERE LasActivityDate LIKE '2010-07-19%'", "difficulty": "simple" }, { "question_id": 665, "question": "What is the average monthly number of links created in 2010 for posts that have no more than 2 answers?", "db_id": "codebase_community", "evidence": "count of Id where YEAR(CreationDate;", "code": "import pandas as pd\nmerged = pd.merge(postLinks, posts, left_on='PostId', right_on='Id')\nfiltered = merged[(merged['AnswerCount'] <= 2) & (pd.to_datetime(merged['CreationDate']).dt.year == 2010)]\nresult = len(filtered) / 12.0", "sql": "SELECT CAST(COUNT(T1.Id) AS REAL) / 12 FROM postLinks AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.AnswerCount <= 2 AND STRFTIME('%Y', T1.CreationDate) = '2010'", "difficulty": "moderate" }, { "question_id": 666, "question": "Among the posts that were voted by user 1465, what is the id of the most valuable post?", "db_id": "codebase_community", "evidence": "user 1465 refers to UserId = 1465; the most valuable post refers to MAX(FavoriteCount);", "code": "import pandas as pd\n\ndef solve_query(votes_df, posts_df):\n try:\n # Ensure required columns are present\n if 'UserId' not in votes_df.columns or 'PostId' not in votes_df.columns:\n return pd.DataFrame(columns=['Id'])\n if 'Id' not in posts_df.columns or 'FavoriteCount' not in posts_df.columns:\n return pd.DataFrame(columns=['Id'])\n\n # Filter votes by UserId = 1465\n filtered_votes = votes_df[votes_df['UserId'] == 1465]\n\n # Merge with posts on PostId and Id\n merged_data = pd.merge(filtered_votes, posts_df, left_on='PostId', right_on='Id', how='inner')\n\n # Handle NULL values in FavoriteCount\n merged_data['FavoriteCount'] = pd.to_numeric(merged_data['FavoriteCount'], errors='coerce')\n\n # Sort by FavoriteCount descending and take the top result\n most_valuable_post = merged_data.sort_values(by='FavoriteCount', ascending=False).head(1)\n\n # Return only the Id column\n return most_valuable_post[['Id_y']].rename(columns={'Id_y': 'Id'})\n except Exception as e:\n return pd.DataFrame(columns=['Id'])\n\n# Example function call\ndata_votes = pd.DataFrame({\"Id\": [1, 2], \"PostId\": [101, 102], \"UserId\": [1465, 1465]})\ndata_posts = pd.DataFrame({\"Id\": [101, 102], \"FavoriteCount\": [10, 20]})\nresult = solve_query(data_votes, data_posts)", "sql": "SELECT T2.Id FROM votes AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T1.UserId = 1465 ORDER BY T2.FavoriteCount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 667, "question": "What is the title of the post with the oldest post link?", "db_id": "codebase_community", "evidence": "the oldest post link refers to MIN(CreaionDate);", "code": "import pandas as pd\nmin_date = postLinks['CreationDate'].min()\nfiltered_postLinks = postLinks[postLinks['CreationDate'] == min_date]\nmerged = pd.merge(posts, filtered_postLinks, left_on='Id', right_on='PostId')\nresult = merged[['Title']].head(1)", "sql": "SELECT T1.Title FROM posts AS T1 INNER JOIN postLinks AS T2 ON T2.PostId = T1.Id WHERE T2.CreationDate = (SELECT MIN(CreationDate) FROM postLinks) LIMIT 1;", "difficulty": "simple" }, { "question_id": 668, "question": "What is the display name of the user who acquired the highest amount of badges?", "db_id": "codebase_community", "evidence": "highest amount of badges refers to MAX(COUNT(Name));", "code": "import pandas as pd\nmerged = pd.merge(users, badges, left_on='Id', right_on='UserId')\ngrouped = merged.groupby('DisplayName').size().reset_index(name='badge_count')\nresult = grouped.sort_values('badge_count', ascending=False).head(1)['DisplayName'].iloc[0]", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId GROUP BY T1.DisplayName ORDER BY COUNT(T1.Id) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 669, "question": "When did 'chl' cast its first vote in a post?", "db_id": "codebase_community", "evidence": "DisplayName = 'chl'; cast its first vote refers to MIN(CreationDate);", "code": "import pandas as pd\n\n# Load necessary tables\nusers_df = pd.read_csv('users.csv')\nvotes_df = pd.read_csv('votes.csv')\n\n# Filter user with DisplayName 'chl'\nchl_user = users_df[users_df['DisplayName'] == 'chl']\n\n# Get UserId of 'chl'\nchl_user_id = chl_user['Id'].values[0]\n\n# Filter votes by UserId of 'chl'\nchl_votes = votes_df[votes_df['UserId'] == chl_user_id]\n\n# Find the earliest CreationDate for 'chl's votes\nfirst_vote_date = chl_votes['CreationDate'].min()\n\n# Record the final result\nresult = first_vote_date\n\n# Print the final result\nprint(result)", "sql": "SELECT T2.CreationDate FROM users AS T1 INNER JOIN votes AS T2 ON T1.Id = T2.UserId WHERE T1.DisplayName = 'chl' ORDER BY T2.CreationDate LIMIT 1", "difficulty": "simple" }, { "question_id": 670, "question": "What is the date when the youngest user made his or her first post?", "db_id": "codebase_community", "evidence": "the youngest user refers to MIN(Age); first post refers to MIN(CreaionDate);", "code": "import pandas as pd\nmerged = pd.merge(users[users['Age'].notna()], posts, left_on='Id', right_on='OwnerUserId')\nmerged = merged.sort_values(['Age', 'CreaionDate'])\nresult = merged.iloc[0]['CreaionDate']", "sql": "SELECT T2.CreaionDate FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.Age IS NOT NULL ORDER BY T1.Age, T2.CreaionDate LIMIT 1", "difficulty": "simple" }, { "question_id": 671, "question": "What is the display name of the user who acquired the first Autobiographer badge?", "db_id": "codebase_community", "evidence": "Autobiographer is the name of the badge; acquired the first refers to MIN(Date);", "code": "import pandas as pd\n\ndef solve_query(users_df, badges_df):\n # 筛选名称为'Autobiographer'的徽章\n filtered_badges = badges_df[badges_df['Name'] == 'Autobiographer']\n \n # 连接users和badges表\n merged = pd.merge(users_df, filtered_badges, left_on='Id', right_on='UserId', how='inner')\n \n #按Date排序并取第一条记录\n sorted_badges = merged.sort_values('Date')\n \n # 选择DisplayName列\n result = sorted_badges.iloc[[0]][['DisplayName']]\n \n return result", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN badges AS T2 ON T1.Id = T2.UserId WHERE T2.`Name` = 'Autobiographer' ORDER BY T2.Date LIMIT 1", "difficulty": "simple" }, { "question_id": 672, "question": "Among the users located in United Kingdom, how many users whose post have a total favorite amount of 4 or more?", "db_id": "codebase_community", "evidence": "favorite amount of 4 or more refers to FavoriteCount > = 4; Location = 'United Kingdom';", "code": "import pandas as pd\n# 筛选英国用户\nuk_users = users[users['Location'] == 'United Kingdom']\n# 筛选对应用户的收藏数>=4的帖子\nfiltered = posts[(posts['OwnerUserId'].isin(uk_users['Id'])) & (posts['FavoriteCount'] >= 4)]\n# 统计不同用户数量\nresult = filtered['OwnerUserId'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.Id) FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.Location = 'United Kingdom' AND T2.FavoriteCount >= 4", "difficulty": "moderate" }, { "question_id": 673, "question": "What is the average number of posts voted by the oldest users?", "db_id": "codebase_community", "evidence": "average number of posts voted refers to AVG(PostId) FROM votes; the oldest users refer to MAX(Age);", "code": "import pandas as pd\n\n# Find the maximum age\nmax_age = users['Age'].max()\n\n# Get user IDs of the oldest users\noldest_user_ids = users[users['Age'] == max_age]['Id']\n\n# Filter votes by oldest users and calculate average PostId\noldest_user_votes = votes[votes['UserId'].isin(oldest_user_ids)]\nresult = oldest_user_votes['PostId'].mean()", "sql": "SELECT AVG(PostId) FROM votes WHERE UserId IN ( SELECT Id FROM users WHERE Age = ( SELECT MAX(Age) FROM users ) )", "difficulty": "simple" }, { "question_id": 674, "question": "Who has the highest reputation? Please give the display name.", "db_id": "codebase_community", "evidence": "the highest reputation refers to MAX(Reputation);", "code": "import pandas as pd\nmax_reputation = users['Reputation'].max()\nresult = users[users['Reputation'] == max_reputation]['DisplayName']", "sql": "SELECT DisplayName FROM users WHERE Reputation = ( SELECT MAX(Reputation) FROM users )", "difficulty": "simple" }, { "question_id": 675, "question": "How many users whose reputations are higher than 2000 and the number of views is higher than 1000?", "db_id": "codebase_community", "evidence": "reputations are higher than 2000 refer to Reputation > 2000; number of views is higher than 1000 refers to Views > 1000;", "code": "import pandas as pd\nresult = len(users[(users['Reputation'] > 2000) & (users['Views'] > 1000)])", "sql": "SELECT COUNT(id) FROM users WHERE Reputation > 2000 AND Views > 1000", "difficulty": "simple" }, { "question_id": 676, "question": "Please list all display names of users who are adults.", "db_id": "codebase_community", "evidence": "adults refer to users where Age BETWEEN 19 and 65;", "code": "import pandas as pd\nresult = users[(users['Age'] >= 19) & (users['Age'] <= 65)][['DisplayName']]", "sql": "SELECT DisplayName FROM users WHERE Age BETWEEN 19 AND 65", "difficulty": "simple" }, { "question_id": 677, "question": "How many posts did Jay Stevens have in 2010?", "db_id": "codebase_community", "evidence": "DisplayName = 'Jay Stevens'; in 2010 refers to YEAR(CreationDate) = 2010;", "code": "import pandas as pd\n\ndef solve_query(users_df, posts_df):\n # 筛选用户名为'Jay Stevens'的用户\n filtered_users = users_df[users_df['DisplayName'] == 'Jay Stevens']\n \n # 连接users和posts表\n merged = pd.merge(filtered_users, posts_df, left_on='Id', right_on='OwnerUserId', how='inner')\n \n # 将CreaionDate列转换为datetime类型并筛选2010年的帖子\n merged['CreaionDate'] = pd.to_datetime(merged['CreaionDate'], errors='coerce')\n filtered_posts = merged[merged['CreaionDate'].dt.year == 2010]\n \n # 计算帖子数量\n result = len(filtered_posts)\n \n return result", "sql": "SELECT COUNT(T1.Id) FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE STRFTIME('%Y', T2.CreaionDate) = '2010' AND T1.DisplayName = 'Jay Stevens'", "difficulty": "simple" }, { "question_id": 678, "question": "Which post by Harvey Motulsky has the most views? Please give the id and title of this post.", "db_id": "codebase_community", "evidence": "DisplayName equals 'Harvey Motulsky' in the database;", "code": "import pandas as pd\n\n# Load the necessary tables\nusers = pd.read_csv('users.csv')\nposts = pd.read_csv('posts.csv')\n\n# Filter users for Harvey Motulsky\nharvey_motulsky = users[users['DisplayName'] == 'Harvey Motulsky']\n\n# Get the user ID of Harvey Motulsky\nharvey_user_id = harvey_motulsky['Id'].values[0]\n\n# Filter posts by Harvey Motulsky's user ID\nharvey_posts = posts[posts['OwnerUserId'] == harvey_user_id]\n\n# Find the post with the most views\nmost_viewed_post = harvey_posts.loc[harvey_posts['ViewCount'].idxmax()]\n\n# Extract the post ID and title\nresult = {\n 'PostId': most_viewed_post['Id'],\n 'Title': most_viewed_post['Title']\n}\n\nprint(result)", "sql": "SELECT T2.Id, T2.Title FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.DisplayName = 'Harvey Motulsky' ORDER BY T2.ViewCount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 679, "question": "Which post has the highest score? Please give its id and title's name.", "db_id": "codebase_community", "evidence": "the highest score refers to MAX(Score); owner's name refers to DisplayName;", "code": "import pandas as pd\nresult = posts.sort_values('Score', ascending=False)[['Id', 'Title']].head(1)", "sql": "SELECT Id, Title FROM posts ORDER BY Score DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 680, "question": "What is the average score of Stephen Turner's posts?", "db_id": "codebase_community", "evidence": "DisplayName = 'Stephen Turner'; average score refers to AVG(Score);", "code": "import pandas as pd\nmerged = pd.merge(users, posts, left_on='Id', right_on='OwnerUserId')\nfiltered = merged[merged['DisplayName'] == 'Stephen Turner']\nresult = filtered['Score'].mean()", "sql": "SELECT AVG(T2.Score) FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE T1.DisplayName = 'Stephen Turner'", "difficulty": "simple" }, { "question_id": 681, "question": "Please list the users' display names whose posts had over 20000 views in 2011.", "db_id": "codebase_community", "evidence": "had over 20000 views in 2011 refers to ViewCount > 20000 where YEAR(CreationDate) = 2011;had over 20000 views in 2011 refers to ViewCount > 20000 where YEAR(CreaionDate) = 2011", "code": "import pandas as pd\nposts['CreaionDate'] = pd.to_datetime(posts['CreaionDate'])\nmerged = pd.merge(users, posts, left_on='Id', right_on='OwnerUserId')\nfiltered = merged[(merged['CreaionDate'].dt.year == 2011) & (merged['ViewCount'] > 20000)]\nresult = filtered[['DisplayName']]", "sql": "SELECT T1.DisplayName FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE STRFTIME('%Y', T2.CreaionDate) = '2011' AND T2.ViewCount > 20000", "difficulty": "simple" }, { "question_id": 682, "question": "Which is the most valuable post in 2010? Please give its id and the owner's display name.", "db_id": "codebase_community", "evidence": "the most valuable post in 2015 refers to MAX(FavoriteCount) where year(CreationDate) = 2010;", "code": "import pandas as pd\nposts['CreaionDate'] = pd.to_datetime(posts['CreaionDate'])\nresult = posts[posts['CreaionDate'].dt.year == 2010].sort_values('FavoriteCount', ascending=False).head(1)[['Id', 'OwnerDisplayName']]", "sql": "SELECT T2.Id, T2.OwnerDisplayName FROM posts AS T2 WHERE STRFTIME('%Y', T2.CreaionDate) = '2010' ORDER BY T2.FavoriteCount DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 683, "question": "What is the percentage of posts whose owners had a reputation of over 1000 in 2011?", "db_id": "codebase_community", "evidence": "Reputation is greater than 1000 in the database; count of Id where YEAR(CreationDate; count of Id;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge users and posts on owner relationship\nmerged = pd.merge(users, posts, left_on='Id', right_on='OwnerUserId')\n\n# Extract year from creation date\nmerged['Year'] = pd.to_datetime(merged['CreaionDate']).dt.year\n\n# Filter for posts from 2011\nposts_2011 = merged[merged['Year'] == 2011]\n\n# Count posts where owner had reputation > 1000\nhigh_rep_posts = posts_2011[posts_2011['Reputation'] > 1000].shape[0]\n\n# Total posts in 2011\ntotal_posts = posts_2011.shape[0]\n\n# Calculate percentage\npercentage = (high_rep_posts / total_posts) * 100 if total_posts > 0 else 0\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(SUM(IIF(STRFTIME('%Y', T2.CreaionDate) = '2011' AND T1.Reputation > 1000, 1, 0)) AS REAL) * 100.0 / COUNT(T2.Id) FROM users AS T1 INNER JOIN posts AS T2 ON T1.Id = T2.OwnerUserId WHERE STRFTIME('%Y', T2.CreaionDate) = '2011'", "difficulty": "moderate" }, { "question_id": 684, "question": "Identify the percentage of teenage users.", "db_id": "codebase_community", "evidence": "count of Id where Age BETWEEN 13 and 18; count of Id;", "code": "import pandas as pd\nteenage_count = users[(users['Age'] >= 13) & (users['Age'] <= 18)]['Id'].count()\ntotal_count = users['Id'].count()\npercentage = (teenage_count / total_count) * 100\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(SUM(IIF(Age BETWEEN 13 AND 18, 1, 0)) AS REAL) * 100 / COUNT(Id) FROM users", "difficulty": "simple" }, { "question_id": 685, "question": "Identify the total views on the post 'Computer Game Datasets'. Name the user who posted it last time.", "db_id": "codebase_community", "evidence": "total views refer to ViewCount; Name the user refers to DisplayName; post 'Computer Game Datasets' refers to Text = 'Computer Game Datasets';", "code": "import pandas as pd\nmerged = pd.merge(posts[posts['Title'] == 'Computer Game Datasets'], users, left_on='OwnerUserId', right_on='Id')\nresult = merged[['ViewCount', 'DisplayName']]", "sql": "SELECT T2.ViewCount, T3.DisplayName FROM postHistory AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id INNER JOIN users AS T3 ON T2.LastEditorUserId = T3.Id WHERE T1.Text = 'Computer Game Datasets'", "difficulty": "moderate" }, { "question_id": 686, "question": "Identify the total number of posts with views above average.", "db_id": "codebase_community", "evidence": "average of ViewCount;count of posts where ViewCount exceeds average ViewCount", "code": "import pandas as pd\nresult = posts[posts['ViewCount'] > posts['ViewCount'].mean()].shape[0]", "sql": "SELECT COUNT(Id) FROM posts WHERE ViewCount > (SELECT AVG(ViewCount) FROM posts)", "difficulty": "simple" }, { "question_id": 687, "question": "How many comments were added to the post with the highest score?", "db_id": "codebase_community", "evidence": "the highest score refers to MAX(Score);the highest score refers to MAX(posts.Score)", "code": "import pandas as pd\nmax_score = posts['Score'].max()\ntop_posts = posts[posts['Score'] == max_score]\nfiltered_comments = comments[comments['PostId'].isin(top_posts['Id'])]\nresult = len(filtered_comments)", "sql": "SELECT COUNT(comments.Id) FROM posts INNER JOIN comments ON posts.Id = comments.PostId WHERE posts.Score = (SELECT MAX(Score) FROM posts)", "difficulty": "simple" }, { "question_id": 688, "question": "Identify the number of posts that have been viewed over 35000 times but have received no comments from other users.", "db_id": "codebase_community", "evidence": "have been viewed over 35000 times refers to ViewCount > 35000; received no comments refers to CommentCount = 0;", "code": "import pandas as pd\nresult = posts[(posts['ViewCount'] > 35000) & (posts['CommentCount'] == 0)]['Id'].count()", "sql": "SELECT COUNT(Id) FROM posts WHERE ViewCount > 35000 AND CommentCount = 0", "difficulty": "simple" }, { "question_id": 689, "question": "Identify the display name and location of the user, who was the last to edit the post with ID 183.", "db_id": "codebase_community", "evidence": "last to edit refers to MAX(LastEditDate);", "code": "import pandas as pd\nresult = posts[posts['Id'] == 183].merge(users, left_on='OwnerUserId', right_on='Id').sort_values('LastEditDate', ascending=False)[['DisplayName', 'Location']].head(1)", "sql": "SELECT T2.DisplayName, T2.Location FROM posts AS T1 INNER JOIN users AS T2 ON T1.LastEditorUserId = T2.Id WHERE T1.Id = 183 ORDER BY T1.LastEditDate DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 690, "question": "Identify the latest badge awarded to the user with the display name Emmett.", "db_id": "codebase_community", "evidence": "the latest badge refers to Name FROM badges where MAX(Date);", "code": "import pandas as pd\nmerged = pd.merge(badges, users, left_on='UserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'Emmett']\nsorted_badges = filtered.sort_values('Date', ascending=False)\nresult = sorted_badges[['Name']].head(1)", "sql": "SELECT T1.Name FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.DisplayName = 'Emmett' ORDER BY T1.Date DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 691, "question": "Identify the number of adult users who have cast over 5000 upvotes.", "db_id": "codebase_community", "evidence": "UpVotes is greater than 5000 in the database;", "code": "import pandas as pd\nresult = len(users[(users['Age'] >= 18) & (users['UpVotes'] > 5000)])", "sql": "SELECT COUNT(Id) FROM users WHERE Age >= 18 AND UpVotes > 5000", "difficulty": "simple" }, { "question_id": 692, "question": "How long did it take the user, known by his or her display name 'Zolomon' to get the badge? Count from the date the user's account was created.", "db_id": "codebase_community", "evidence": "DisplayName equals 'Zolomon' in the database;", "code": "import pandas as pd\nmerged = pd.merge(badges, users, left_on='UserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'Zolomon']\ndays_diff = (pd.to_datetime(filtered['Date']) - pd.to_datetime(filtered['CreationDate'])).dt.days\nresult = days_diff.to_frame('days_diff')", "sql": "SELECT JULIANDAY(T1.Date) - JULIANDAY(T2.CreationDate) AS days_diff FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.DisplayName = 'Zolomon'", "difficulty": "moderate" }, { "question_id": 693, "question": "Identify the number of posts and comments left by the user, who has the latest created user account.", "db_id": "codebase_community", "evidence": "the latest created user account refers to MAX(CreationDate);the latest created user account refers to MAX(CreationDate); the count refers to the sum of COUNT(T2.Id) and COUNT(T3.Id)", "code": "import pandas as pd\n# 假设所有表已作为DataFrame存在\nusers['CreationDate'] = pd.to_datetime(users['CreationDate'])\nlatest_user_id = users.loc[users['CreationDate'].idxmax(), 'Id']\npost_count = posts[posts['OwnerUserId'] == latest_user_id].shape[0]\ncomment_count = comments[comments['UserId'] == latest_user_id].shape[0]\nresult = pd.DataFrame({'post_count': [post_count], 'comment_count': [comment_count]})", "sql": "SELECT (SELECT COUNT(Id) FROM posts WHERE OwnerUserId = (SELECT Id FROM users ORDER BY CreationDate DESC LIMIT 1)) AS post_count, (SELECT COUNT(Id) FROM comments WHERE UserId = (SELECT Id FROM users ORDER BY CreationDate DESC LIMIT 1)) AS comment_count", "difficulty": "simple" }, { "question_id": 694, "question": "Provide the text of the latest 10 comments to the post with the title 'Analysing wind data with R' and the display name of the user who left it.", "db_id": "codebase_community", "evidence": "the latest comment refers to MAX(CreationDate);", "code": "import pandas as pd\n\n# 读取数据\ncomments = pd.read_csv('comments.csv')\nposts = pd.read_csv('posts.csv')\nusers = pd.read_csv('users.csv')\n\n# 1. 筛选帖子 (SQL: WHERE p.Title = 'Analysing wind data with R')\nfiltered_posts = posts[posts['Title'] == 'Analysing wind data with R']\n\n# 2. 连接 Comments 和 Posts (SQL: FROM comments JOIN posts ON c.PostId = p.Id)\n# 注意:comments 和 posts 都有 CreationDate,合并后 comments 的变为 CreationDate_x\nmerged_1 = pd.merge(comments, filtered_posts, left_on='PostId', right_on='Id', how='inner')\n\n# 3. 连接结果和 Users (SQL: JOIN users ON c.UserId = u.Id)\nmerged_2 = pd.merge(merged_1, users, left_on='UserId', right_on='Id', how='inner')\n\n# 4. 排序 (SQL: ORDER BY c.CreationDate DESC)\n# 使用 comments 表的时间列 (CreationDate_x)\nsorted_result = merged_2.sort_values('CreationDate_x', ascending=False).head(10)\n\n# 5. 选择列 (SQL: SELECT c.Text, u.DisplayName)\n# Text 来自 comments (Text), DisplayName 来自 users (DisplayName)\nresult = sorted_result[['Text', 'DisplayName']]\n\nprint(result)", "sql": "SELECT c.Text, u.DisplayName FROM comments AS c INNER JOIN posts AS p ON c.PostId = p.Id INNER JOIN users AS u ON c.UserId = u.Id WHERE p.Title = 'Analysing wind data with R' ORDER BY c.CreationDate DESC LIMIT 10", "difficulty": "moderate" }, { "question_id": 695, "question": "How many users were awarded with 'Citizen Patrol' badge?", "db_id": "codebase_community", "evidence": "Citizen Patrol' is the name of the badge;", "code": "import pandas as pd\nresult = badges[badges['Name'] == 'Citizen Patrol']['Id'].count()", "sql": "SELECT COUNT(id) FROM badges WHERE `Name` = 'Citizen Patrol'", "difficulty": "simple" }, { "question_id": 696, "question": "Count the number of posts with a tag specified as 'careers'.", "db_id": "codebase_community", "evidence": "tag specified as 'careers' refers to TagName = 'careers';", "code": "import pandas as pd\nresult = posts[posts['Tags'].str.contains('', na=False)].shape[0]", "sql": "SELECT COUNT(Id) FROM posts WHERE Tags LIKE '%%'", "difficulty": "simple" }, { "question_id": 697, "question": "What is the reputation and view count of the user, who is known by his or her display name 'Jarrod Dixon'?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\nresult = users[users['DisplayName'] == 'Jarrod Dixon'][['Reputation', 'Views']]", "sql": "SELECT Reputation, Views FROM users WHERE DisplayName = 'Jarrod Dixon'", "difficulty": "simple" }, { "question_id": 698, "question": "How many comments and answers were left by the users on the post with the title 'Clustering 1D data'?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\nresult = posts[posts['Title'] == 'Clustering 1D data'][['CommentCount', 'AnswerCount']]", "sql": "SELECT CommentCount, AnswerCount FROM posts WHERE Title = 'Clustering 1D data'", "difficulty": "simple" }, { "question_id": 699, "question": "When did the user known as 'IrishStat' create his or her account?", "db_id": "codebase_community", "evidence": "DisplayName = 'IrishStat'; when create his or her account refers to CreationDate;", "code": "import pandas as pd\nresult = users[users['DisplayName'] == 'IrishStat']['CreationDate']", "sql": "SELECT CreationDate FROM users WHERE DisplayName = 'IrishStat'", "difficulty": "simple" }, { "question_id": 700, "question": "Identify the number of posts that offer a bounty amount over 30.", "db_id": "codebase_community", "evidence": "bounty amount over 30 refers to BountyAmount > = 30;BountyAmount refers to the amount specified in the votes table for a post's bounty; PostId in votes table links to posts table to identify the post associated with the bounty", "code": "import pandas as pd\n# 假设votes表已作为DataFrame存在\n# 过滤符合条件的悬赏记录\nfiltered_bounties = votes[votes['BountyAmount'] >= 30]\n# 统计唯一帖子数量\nresult = filtered_bounties['PostId'].nunique()", "sql": "SELECT COUNT(DISTINCT PostId) FROM votes WHERE BountyAmount >= 30", "difficulty": "simple" }, { "question_id": 701, "question": "Among all the posts posted by the most influential user, identify the percentage with a score above 50.", "db_id": "codebase_community", "evidence": "Score is greater than 50 in the database; count of stats_posts.Id where Score > 50 and MAX(Reputation; count of stats_posts.Id where MAX(Reputation;most influential user refers to user with MAX(Reputation); count of posts by most influential user; percentage calculated by dividing posts with Score > 50 by total posts of most influential user", "code": "import pandas as pd\nmi_users = users[users['Reputation'] == users['Reputation'].max()]['Id']\nmi_posts = posts[posts['OwnerUserId'].isin(mi_users)]\nhigh_score = (mi_posts['Score'] > 50).sum()\ntotal = len(mi_posts)\npercentage = high_score / total * 100\nresult = pd.DataFrame({'percentage_above_50': [percentage]})", "sql": "SELECT CAST(SUM(CASE WHEN T2.Score > 50 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T2.Id) AS percentage_above_50 FROM users T1 INNER JOIN posts T2 ON T1.Id = T2.OwnerUserId WHERE T1.Reputation = (SELECT MAX(Reputation) FROM users)", "difficulty": "challenging" }, { "question_id": 702, "question": "How many posts have a score less than 20?", "db_id": "codebase_community", "evidence": "score less than 20 refers to Score < 20;", "code": "import pandas as pd\nresult = len(posts[posts['Score'] < 20])", "sql": "SELECT COUNT(id) FROM posts WHERE Score < 20", "difficulty": "simple" }, { "question_id": 703, "question": "Among the tags with tag ID below 15, how many of them have 20 count of posts and below?", "db_id": "codebase_community", "evidence": "ID below 15 refers to Id < 15; have 20 count of posts and below refers to Count < = 20;", "code": "import pandas as pd\nresult = tags[(tags['Id'] < 15) & (tags['Count'] <= 20)].shape[0]", "sql": "SELECT COUNT(id) FROM tags WHERE Count <= 20 AND Id < 15", "difficulty": "simple" }, { "question_id": 704, "question": "What is the excerpt post ID and wiki post ID of the tag named sample?", "db_id": "codebase_community", "evidence": "tag named sample refers to TagName = 'sample';", "code": "import pandas as pd\nresult = tags[tags['TagName'] == 'sample'][['ExcerptPostId', 'WikiPostId']]", "sql": "SELECT ExcerptPostId, WikiPostId FROM tags WHERE TagName = 'sample'", "difficulty": "simple" }, { "question_id": 705, "question": "Give the user's reputation and up vote number of the user that commented \"fine, you win :)\".", "db_id": "codebase_community", "evidence": "Text equals 'fine, you win :)' in the database;", "code": "import pandas as pd\nmerged = pd.merge(comments[comments['Text'] == 'fine, you win :)'], users, left_on='UserId', right_on='Id')\nresult = merged[['Reputation', 'UpVotes']]", "sql": "SELECT T2.Reputation, T2.UpVotes FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Text = 'fine, you win :)'", "difficulty": "simple" }, { "question_id": 706, "question": "Give the texts commented on the post about linear regression.", "db_id": "codebase_community", "evidence": "about linear regression refers to Title contains 'linear regression'", "code": "import pandas as pd\nmerged = pd.merge(comments, posts, left_on='PostId', right_on='Id')\nfiltered = merged[merged['Title'].str.contains('linear regression', case=False, na=False)]\nresult = filtered[['Text']]", "sql": "SELECT T1.Text FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.Title LIKE '%linear regression%'", "difficulty": "simple" }, { "question_id": 707, "question": "Among the posts with views ranging from 100 to 150, what is the comment with the highest score?", "db_id": "codebase_community", "evidence": "views ranging from 100 to 150 refers to ViewCount BETWEEN 100 and 150; comment with the highest score refers to Text where MAX(Score);", "code": "import pandas as pd\n\n# Filter posts with ViewCount between 100 and 150\nfiltered_posts = posts[(posts['ViewCount'] >= 100) & (posts['ViewCount'] <= 150)]\n\n# Get comments for these posts\nfiltered_comments = comments[comments['PostId'].isin(filtered_posts['Id'])]\n\n# Get the comment with highest score\nresult = filtered_comments.loc[filtered_comments['Score'].idxmax(), 'Text']", "sql": "SELECT Text FROM comments WHERE PostId IN ( SELECT Id FROM posts WHERE ViewCount BETWEEN 100 AND 150 ) ORDER BY Score DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 708, "question": "List the creation date and age of the user that commented with webiste.", "db_id": "codebase_community", "evidence": "commented with webiste refers to the value contains 'http://'", "code": "import pandas as pd\n\ncomments = pd.read_csv('comments.csv')\nusers = pd.read_csv('users.csv')\n\n# 1. 筛选包含 URL 的评论 (SQL: WHERE T1.Text LIKE '%http://%')\nfiltered_comments = comments[comments['Text'].str.contains('http://', na=False)]\n\n# 2. 连接 Comments 和 Users (SQL: FROM comments JOIN users ON T1.UserId = T2.Id)\n# 注意:两个表都有 CreationDate,合并后 comments 的变为 CreationDate_x,users 的变为 CreationDate_y\nmerged = pd.merge(filtered_comments, users, left_on='UserId', right_on='Id', how='inner')\n\n# 3. 选择列 (SQL: SELECT T2.CreationDate, T2.Age)\n# T2 是 users 表,对应 CreationDate_y\nresult = merged[['CreationDate_y', 'Age']].rename(columns={'CreationDate_y': 'CreationDate'})\n\nprint(result)", "sql": "SELECT T2.CreationDate, T2.Age FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Text LIKE '%http://%'", "difficulty": "moderate" }, { "question_id": 709, "question": "In comments with 0 score, how many of the posts have view count lower than 5?", "db_id": "codebase_community", "evidence": "view count lower than 5 refers to ViewCount < 5;comments with 0 score refers to T1.Score = 0", "code": "import pandas as pd\n# Filter comments with Score=0\nfiltered_comments = comments[comments['Score'] == 0]\n# Merge with posts table\nmerged = pd.merge(filtered_comments, posts, left_on='PostId', right_on='Id')\n# Filter posts with ViewCount < 5\nfinal_data = merged[merged['ViewCount'] < 5]\n# Count unique PostIds\nresult = final_data['PostId'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.PostId) FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T1.Score = 0 AND T2.ViewCount < 5", "difficulty": "simple" }, { "question_id": 710, "question": "In posts with 1 comment, how many of the comments have 0 score?", "db_id": "codebase_community", "evidence": "in posts with 1 comment refers to CommentCount = 1;", "code": "import pandas as pd\n\ncomments = pd.read_csv('comments.csv')\nposts = pd.read_csv('posts.csv')\n\n# 1. 筛选 CommentCount 为 1 的帖子 (SQL: WHERE T2.CommentCount = 1)\nfiltered_posts = posts[posts['CommentCount'] == 1]\n\n# 2. 连接 Comments 和 Posts (SQL: FROM comments JOIN posts ON T1.PostId = T2.Id)\n# 注意:两个表都有 Score 列,合并后 comments 的变为 Score_x,posts 的变为 Score_y\nmerged = pd.merge(comments, filtered_posts, left_on='PostId', right_on='Id', how='inner')\n\n# 3. 筛选评论分数为 0 (SQL: AND T1.Score = 0)\n# T1 是 comments 表,对应 Score_x\nzero_score_comments = merged[merged['Score_x'] == 0]\n\n# 4. 计数 (SQL: SELECT COUNT(T1.id))\nresult = len(zero_score_comments)\n\nprint(result)", "sql": "SELECT COUNT(T1.id) FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.CommentCount = 1 AND T1.Score = 0", "difficulty": "simple" }, { "question_id": 711, "question": "Among products comments with 0 score, what is the total number of users ages 40 years old?", "db_id": "codebase_community", "evidence": "", "code": "import pandas as pd\n\ndef solve_query(comments_df, users_df):\n # Check if required columns exist\n if 'Score' not in comments_df.columns or 'UserId' not in comments_df.columns:\n return pd.DataFrame({'count': [0]})\n if 'Id' not in users_df.columns or 'Age' not in users_df.columns:\n return pd.DataFrame({'count': [0]})\n\n # Filter comments with Score = 0\n filtered_comments = comments_df[comments_df['Score'] == 0]\n\n # Merge with users on UserId and Id\n merged_data = pd.merge(filtered_comments, users_df, left_on='UserId', right_on='Id', how='inner')\n\n # Filter users with Age = 40\n filtered_users = merged_data[merged_data['Age'] == 40]\n\n # Count distinct user IDs\n result_count = filtered_users['Id_y'].nunique()\n\n return pd.DataFrame({'count': [result_count]})\n\n# Example function call with placeholder DataFrames\ncomments_data = pd.DataFrame({\n 'Id': [1, 2, 3],\n 'PostId': [101, 102, 103],\n 'Score': [0, 1, 0],\n 'UserId': [10, 20, 10]\n})\nusers_data = pd.DataFrame({\n 'Id': [10, 20],\n 'Reputation': [100, 200],\n 'Age': [40, 30]\n})\nresult = solve_query(comments_data, users_data)\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.id) FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Score = 0 AND T2.Age = 40", "difficulty": "simple" }, { "question_id": 712, "question": "What is the post ID and the comments commented in the post titled by \"Group differences on a five point Likert item\"?", "db_id": "codebase_community", "evidence": "Title equals 'Group differences on a five point Likert item' in the database;", "code": "import pandas as pd\n\ndef solve_query(comments_df, posts_df):\n # Ensure the necessary columns exist\n if 'Title' not in posts_df.columns or 'PostId' not in comments_df.columns or 'Id' not in posts_df.columns:\n return pd.DataFrame(columns=['Id', 'Text'])\n\n # Filter posts with the specified title\n filtered_posts = posts_df[posts_df['Title'] == 'Group differences on a five point Likert item']\n\n # Merge comments with the filtered posts on PostId and Id\n merged_data = pd.merge(\n comments_df,\n filtered_posts,\n left_on='PostId',\n right_on='Id',\n how='inner'\n )\n\n # Select the required columns\n result = merged_data[['Id_y', 'Text']].rename(columns={'Id_y': 'Id'})\n\n return result\n\n# Example function call (replace example DataFrames with actual data)\ncomments_data = pd.DataFrame({\n 'Id': [1, 2, 3],\n 'PostId': [101, 102, 103],\n 'Text': ['Comment1', 'Comment2', 'Comment3']\n})\n\nposts_data = pd.DataFrame({\n 'Id': [101, 102, 103],\n 'Title': ['Group differences on a five point Likert item', 'Another Title', None]\n})\n\nresult = solve_query(comments_data, posts_data)\nprint(result)", "sql": "SELECT T2.Id, T1.Text FROM comments AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.Title = 'Group differences on a five point Likert item'", "difficulty": "simple" }, { "question_id": 713, "question": "What is the up vote number of the user that commented \"R is also lazy evaluated.\"?", "db_id": "codebase_community", "evidence": "commented \"R is also lazy evaluated.\" refers to Text of the comment;", "code": "import pandas as pd\nimport numpy as np\n\n# Filter comments for the specific text\nfiltered_comments = comments[comments['Text'] == 'R is also lazy evaluated.']\n\n# Merge with users table to get UpVotes\nmerged = pd.merge(filtered_comments, users, left_on='UserId', right_on='Id')\n\n# Get the UpVotes value\nresult = merged['UpVotes'].iloc[0] if len(merged) > 0 else None", "sql": "SELECT T2.UpVotes FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Text = 'R is also lazy evaluated.'", "difficulty": "simple" }, { "question_id": 714, "question": "List the comments commented by the user with a username of Harvey Motulsky.", "db_id": "codebase_community", "evidence": "comments refer to Text; username of Harvey Motulsky refers to DisplayName = 'Harvey Motulsky';", "code": "import pandas as pd\nmerged = pd.merge(comments, users, left_on='UserId', right_on='Id')\nfiltered = merged[merged['DisplayName'] == 'Harvey Motulsky']\nresult = filtered[['Text']]", "sql": "SELECT T1.Text FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.DisplayName = 'Harvey Motulsky'", "difficulty": "simple" }, { "question_id": 715, "question": "In comments with score between 1 to 5, list down the display names of the users with 0 down votes.", "db_id": "codebase_community", "evidence": "DownVotes equals 0 in the database;", "code": "import pandas as pd\n\ndef solve_query(comments_df, users_df):\n # 筛选Score在1到5之间的评论\n filtered_comments = comments_df[(comments_df['Score'] >= 1) & (comments_df['Score'] <= 5)]\n \n # 连接comments和users表\n merged = pd.merge(filtered_comments, users_df, left_on='UserId', right_on='Id', how='inner')\n \n # 筛选DownVotes为0的用户\n filtered_users = merged[merged['DownVotes'] == 0]\n \n # 选择DisplayName列并去重\n result = filtered_users[['DisplayName']].drop_duplicates()\n \n return result", "sql": "SELECT T2.DisplayName FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Score BETWEEN 1 AND 5 AND T2.DownVotes = 0", "difficulty": "simple" }, { "question_id": 716, "question": "Among the comments with scores between 5 to 10, what is the percentage of the users with 0 up votes?", "db_id": "codebase_community", "evidence": "UpVotes equals 0 in the database; count of UserId where UpVotes = 0 and Score BETWEEN 5 and 10; count of UserId where Score BETWEEN 5 and 10;", "code": "import pandas as pd\n\ncomments = pd.read_csv('comments.csv')\nusers = pd.read_csv('users.csv')\n\n# 1. 筛选 Score 在 5 到 10 之间的评论\nfiltered_comments = comments[(comments['Score'] >= 5) & (comments['Score'] <= 10)]\n\n# 2. 合并表\n# comments 有 UserId, users 有 Id。两者都有 'Id' 列,合并后 users 的 Id 变为 Id_y\nmerged = pd.merge(filtered_comments, users, left_on='UserId', right_on='Id', how='inner')\n\n# 3. 计算分子:UpVotes 为 0 的不同用户数量\n# 注意:使用 'UserId' (或 'Id_y') 来指代用户 ID,不能用 'Id'\nzero_upvotes_count = merged[merged['UpVotes'] == 0]['UserId'].nunique()\n\n# 4. 计算分母:总的不同用户数量\ntotal_users_count = merged['UserId'].nunique()\n\n# 5. 计算百分比\nresult = zero_upvotes_count * 100.0 / total_users_count\n\nprint(result)", "sql": "SELECT COUNT(DISTINCT CASE WHEN users.UpVotes = 0 THEN users.Id END) * 100.0 / COUNT(DISTINCT users.Id) AS per FROM users INNER JOIN comments ON users.Id = comments.UserId WHERE comments.Score BETWEEN 5 AND 10", "difficulty": "moderate" }, { "question_id": 717, "question": "Please list all the superpowers of 3-D Man.", "db_id": "superhero", "evidence": "3-D Man refers to superhero_name = '3-D Man'; superpowers refers to power_name", "code": "import pandas as pd\n\ndef solve_query(superhero_df, hero_power_df, superpower_df):\n # 筛选超级英雄名称为'3-D Man'的记录\n filtered_superhero = superhero_df[superhero_df['superhero_name'] == '3-D Man']\n \n # 连接superhero和hero_power表\n merged_1 = pd.merge(filtered_superhero, hero_power_df, left_on='id', right_on='hero_id', how='inner')\n \n # 连接结果和superpower表\n merged_2 = pd.merge(merged_1, superpower_df, left_on='power_id', right_on='id', how='inner')\n \n # 选择power_name列\n result = merged_2[['power_name']]\n \n return result", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.superhero_name = '3-D Man'", "difficulty": "simple" }, { "question_id": 718, "question": "How many superheroes have the super power of \"Super Strength\"?", "db_id": "superhero", "evidence": "power_name equals 'Super Strength' in the database;", "code": "import pandas as pd\nmerged = pd.merge(hero_power, superpower, left_on='power_id', right_on='id')\nfiltered = merged[merged['power_name'] == 'Super Strength']\nresult = filtered['hero_id'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.hero_id) FROM hero_power AS T1 INNER JOIN superpower AS T2 ON T1.power_id = T2.id WHERE T2.power_name = 'Super Strength'", "difficulty": "simple" }, { "question_id": 719, "question": "Among the superheroes with the super power of \"Super Strength\", how many of them have a height of over 200cm?", "db_id": "superhero", "evidence": "super power of \"Super Strength\" refers to power_name = 'Super Strength'; a height of over 200cm refers to height_cm > 200", "code": "import pandas as pd\nmerged = pd.merge(superhero, hero_power, left_on='id', right_on='hero_id')\nmerged = pd.merge(merged, superpower, left_on='power_id', right_on='id')\nfiltered = merged[(merged['power_name'] == 'Super Strength') & (merged['height_cm'] > 200)]\nresult = len(filtered['id_x'].unique())", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T3.power_name = 'Super Strength' AND T1.height_cm > 200", "difficulty": "moderate" }, { "question_id": 720, "question": "Please list the full names of all the superheroes with over 15 super powers.", "db_id": "superhero", "evidence": "count of full_name;", "code": "import pandas as pd\nmerged = pd.merge(superhero, hero_power, left_on='id', right_on='hero_id')\ngrouped = merged.groupby('full_name')['power_id'].nunique().reset_index()\nresult = grouped[grouped['power_id'] > 15]['full_name']", "sql": "SELECT T1.full_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id GROUP BY T1.full_name HAVING COUNT(DISTINCT T2.power_id) > 15", "difficulty": "simple" }, { "question_id": 721, "question": "How many superheroes have blue eyes?", "db_id": "superhero", "evidence": "blue eyes refers to colour = 'Blue' and eye_colour_id = colour.id;", "code": "import pandas as pd\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id')\nblue_eyes = merged[merged['colour'] == 'Blue']\nresult = len(blue_eyes)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T2.colour = 'Blue'", "difficulty": "simple" }, { "question_id": 722, "question": "What is the colour of Apocalypse's skin?", "db_id": "superhero", "evidence": "Apocalypse refers to superhero_name = 'Apocalypse'; colour of skin refers to colour where skin_colour_id = colour.id", "code": "import pandas as pd\nmerged = pd.merge(superhero[superhero['superhero_name'] == 'Apocalypse'], colour, left_on='skin_colour_id', right_on='id')\nresult = merged[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.skin_colour_id = T2.id WHERE T1.superhero_name = 'Apocalypse'", "difficulty": "simple" }, { "question_id": 723, "question": "Among the superheroes with blue eyes, how many of them have the super power of \"Agility\"?", "db_id": "superhero", "evidence": "blue eyes refers to colour = 'Blue' and eye_colour_id = colour.id; super power of \"Agility\" refers to power_name = 'Agility'", "code": "import pandas as pd\n\ndef solve_query(superhero_df, hero_power_df, superpower_df, colour_df):\n # 筛选超级能力为\"Agility\"的记录\n filtered_superpower = superpower_df[superpower_df['power_name'] == 'Agility']\n \n # 连接superhero和hero_power表\n merged_1 = pd.merge(superhero_df, hero_power_df, left_on='id', right_on='hero_id', how='inner')\n \n # 连接结果和superpower表\n merged_2 = pd.merge(merged_1, filtered_superpower, left_on='power_id', right_on='id', how='inner')\n \n # 连接结果和colour表\n merged_3 = pd.merge(merged_2, colour_df, left_on='eye_colour_id', right_on='id', how='inner')\n \n # 筛选眼睛颜色为\"Blue\"的超级英雄\n filtered_result = merged_3[merged_3['colour'] == 'Blue']\n \n # 计算符合条件的超级英雄数量\n result = len(filtered_result)\n \n return result", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id INNER JOIN colour AS T4 ON T1.eye_colour_id = T4.id WHERE T3.power_name = 'Agility' AND T4.colour = 'Blue'", "difficulty": "moderate" }, { "question_id": 724, "question": "Please list the superhero names of all the superheroes that have blue eyes and blond hair.", "db_id": "superhero", "evidence": "blue eyes refers to colour = 'Blue' and eye_colour_id = colour.id; blond hair refers to colour = 'Blond' and hair_colour_id = colour.id; super power of \"Agility\" refers to power_name = 'Agility'", "code": "import pandas as pd\n\n# Merge superhero with eye colour\ndf1 = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id', suffixes=('', '_eye'))\n# Filter for blue eyes\ndf1 = df1[df1['colour'] == 'Blue']\n\n# Merge with hair colour\ndf2 = pd.merge(df1, colour, left_on='hair_colour_id', right_on='id', suffixes=('', '_hair'))\n# Filter for blond hair\ndf2 = df2[df2['colour_hair'] == 'Blond']\n\n# Select superhero names\nresult = df2[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id INNER JOIN colour AS T3 ON T1.hair_colour_id = T3.id WHERE T2.colour = 'Blue' AND T3.colour = 'Blond'", "difficulty": "challenging" }, { "question_id": 725, "question": "How many superheroes are published by Marvel Comics?", "db_id": "superhero", "evidence": "publisher_name equals 'Marvel Comics' in the database;", "code": "import pandas as pd\n\ndef solve_query(superhero_df, publisher_df):\n # 筛选出版商名称为'Marvel Comics'的记录\n filtered_publisher = publisher_df[publisher_df['publisher_name'] == 'Marvel Comics']\n \n # 连接superhero和publisher表\n merged = pd.merge(superhero_df, filtered_publisher, left_on='publisher_id', right_on='id', how='inner')\n \n # 计算符合条件的超级英雄数量\n result = len(merged)\n \n return result", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T2.publisher_name = 'Marvel Comics'", "difficulty": "simple" }, { "question_id": 726, "question": "Rank heroes published by Marvel Comics by their height in descending order.", "db_id": "superhero", "evidence": "name refers to superhero_name; the tallest hero refers to MAX(height_cm); published by Marvel Comics refers to publisher_name = 'Marvel Comics'", "code": "import pandas as pd\n\ndef solve_query(superhero_df, publisher_df):\n # 筛选出版商名称为'Marvel Comics'的记录\n filtered_publisher = publisher_df[publisher_df['publisher_name'] == 'Marvel Comics']\n \n # 连接superhero和publisher表\n merged = pd.merge(superhero_df, filtered_publisher, left_on='publisher_id', right_on='id', how='inner')\n \n # 按身高降序排序\n sorted_result = merged.sort_values('height_cm', ascending=False)\n \n # 添加排名列\n sorted_result['HeightRank'] = sorted_result['height_cm'].rank(method='min', ascending=False)\n \n # 选择superhero_name, height_cm和HeightRank列\n result = sorted_result[['superhero_name', 'height_cm', 'HeightRank']]\n \n return result", "sql": "SELECT superhero_name, height_cm, RANK() OVER (ORDER BY height_cm DESC) AS HeightRank FROM superhero INNER JOIN publisher ON superhero.publisher_id = publisher.id WHERE publisher.publisher_name = 'Marvel Comics'", "difficulty": "moderate" }, { "question_id": 727, "question": "Who is the publisher of Sauron?", "db_id": "superhero", "evidence": "the publisher refers to publisher_name; Sauron refers to superhero_name = 'Sauron'", "code": "import pandas as pd\nfiltered_superhero = superhero[superhero['superhero_name'] == 'Sauron']\nmerged = pd.merge(filtered_superhero, publisher, left_on='publisher_id', right_on='id')\nresult = merged[['publisher_name']]", "sql": "SELECT T2.publisher_name FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.superhero_name = 'Sauron'", "difficulty": "simple" }, { "question_id": 728, "question": "Rank superheroes from Marvel Comics by their eye color popularity, starting with the most common color.", "db_id": "superhero", "evidence": "the superheroes from Marvel Comics refers to publisher_name = 'Marvel Comics'; most common color refers to COUNT(superhero.id) DESC;", "code": "import pandas as pd\n\ndef solve_query(superhero_df, colour_df, publisher_df):\n # 筛选出版商名称为'Marvel Comics'的记录\n filtered_publisher = publisher_df[publisher_df['publisher_name'] == 'Marvel Comics']\n \n # 连接superhero和publisher表\n merged_1 = pd.merge(superhero_df, filtered_publisher, left_on='publisher_id', right_on='id', how='inner')\n \n # 连接结果和colour表\n merged_2 = pd.merge(merged_1, colour_df, left_on='eye_colour_id', right_on='id', how='inner')\n \n # 按眼睛颜色分组并计算每种颜色的超级英雄数量\n grouped = merged_2.groupby('colour').agg({'id': 'count'}).reset_index()\n grouped.columns = ['EyeColor', 'Count']\n \n # 按数量降序排序\n sorted_result = grouped.sort_values('Count', ascending=False)\n \n # 添加排名列\n sorted_result['PopularityRank'] = sorted_result['Count'].rank(method='min', ascending=False)\n \n # 选择EyeColor, Count和PopularityRank列\n result = sorted_result[['EyeColor', 'Count', 'PopularityRank']]\n \n return result", "sql": "SELECT colour.colour AS EyeColor, COUNT(superhero.id) AS Count, RANK() OVER (ORDER BY COUNT(superhero.id) DESC) AS PopularityRank FROM superhero INNER JOIN colour ON superhero.eye_colour_id = colour.id INNER JOIN publisher ON superhero.publisher_id = publisher.id WHERE publisher.publisher_name = 'Marvel Comics' GROUP BY colour.colour", "difficulty": "moderate" }, { "question_id": 729, "question": "What is the average height of the superheroes from Marvel Comics?", "db_id": "superhero", "evidence": "superheroes from Marvel Comics refers to publisher_name = 'Marvel Comics'; average height of the superheroes refers to AVG(height_cm)", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nmarvel_heroes = merged[merged['publisher_name'] == 'Marvel Comics']\nresult = marvel_heroes['height_cm'].mean()", "sql": "SELECT AVG(T1.height_cm) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T2.publisher_name = 'Marvel Comics'", "difficulty": "simple" }, { "question_id": 730, "question": "List the superheroes from Marvel Comics who have the super power of 'Super Strength'.", "db_id": "superhero", "evidence": "the superheroes from Marvel Comics refers to publisher_name = 'Marvel Comics'; super power of \"Super Strength\" refers to power_name = 'Super Strength';", "code": "import pandas as pd\n\n# Read the CSV files into DataFrames\nalignment_df = pd.read_csv('alignment.csv')\nattribute_df = pd.read_csv('attribute.csv')\ncolour_df = pd.read_csv('colour.csv')\ngender_df = pd.read_csv('gender.csv')\npublisher_df = pd.read_csv('publisher.csv')\nrace_df = pd.read_csv('race.csv')\nsuperhero_df = pd.read_csv('superhero.csv')\nhero_attribute_df = pd.read_csv('hero_attribute.csv')\nsuperpower_df = pd.read_csv('superpower.csv')\nhero_power_df = pd.read_csv('hero_power.csv')\n\n# Filter superheroes from Marvel Comics\nmarvel_superheroes = superhero_df[superhero_df['publisher_id'] == publisher_df[publisher_df['publisher_name'] == 'Marvel Comics']['id'].values[0]]\n\n# Filter superheroes with the superpower 'Super Strength'\nsuper_strength_power_id = superpower_df[superpower_df['power_name'] == 'Super Strength']['id'].values[0]\nsuper_strength_heroes = hero_power_df[hero_power_df['power_id'] == super_strength_power_id]\n\n# Get the list of superhero names\nresult = marvel_superheroes[marvel_superheroes['id'].isin(super_strength_heroes['hero_id'])]['superhero_name']\n\n# Print the result\nprint(result)", "sql": "SELECT T1.superhero_name\nFROM superhero AS T1\nINNER JOIN publisher AS T4 ON T1.publisher_id = T4.id\nWHERE T4.publisher_name = 'Marvel Comics' AND EXISTS (SELECT 1 FROM hero_power AS T2 INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T2.hero_id = T1.id AND T3.power_name = 'Super Strength')", "difficulty": "challenging" }, { "question_id": 731, "question": "How many superheroes did DC Comics publish?", "db_id": "superhero", "evidence": "publisher_name equals 'DC Comics' in the database;", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\ndc_heroes = merged[merged['publisher_name'] == 'DC Comics']\nresult = len(dc_heroes)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T2.publisher_name = 'DC Comics'", "difficulty": "simple" }, { "question_id": 732, "question": "Which publisher published the slowest superhero?", "db_id": "superhero", "evidence": "the slowest superhero refers to attribute_name = 'Speed' where MIN(attribute_value); publisher refers to publisher_name", "code": "import pandas as pd\n\ndef solve_query(superhero_df, publisher_df, hero_attribute_df, attribute_df):\n # Filter for 'Speed' attribute\n speed_filter = attribute_df['attribute_name'] == 'Speed'\n speed_attributes = attribute_df[speed_filter]\n\n # Merge to get corresponding hero attributes\n merged_data = pd.merge(hero_attribute_df, speed_attributes, left_on='attribute_id', right_on='id')\n\n # Merge with superhero and publisher tables\n merged_data = pd.merge(merged_data, superhero_df, left_on='hero_id', right_on='id')\n merged_data = pd.merge(merged_data, publisher_df, left_on='publisher_id', right_on='id')\n\n # Handle NULL values in attribute_value\n merged_data['attribute_value'] = pd.to_numeric(merged_data['attribute_value'], errors='coerce')\n\n # Find the publisher of the slowest superhero (min speed)\n slowest_hero_publisher = merged_data.loc[merged_data['attribute_value'].idxmin()]\n return slowest_hero_publisher['publisher_name']\n\n# Example usage\ndata = {\n 'superhero': pd.DataFrame({'id': [1, 2], 'publisher_id': [101, 102]}),\n 'publisher': pd.DataFrame({'id': [101, 102], 'publisher_name': ['Marvel', 'DC']}),\n 'hero_attribute': pd.DataFrame({'hero_id': [1, 2], 'attribute_id': [501, 502], 'attribute_value': [3, 1]}),\n 'attribute': pd.DataFrame({'id': [501, 502], 'attribute_name': ['Speed', 'Speed']})\n}\n\nresult = solve_query(data['superhero'], data['publisher'], data['hero_attribute'], data['attribute'])\nprint(result)", "sql": "SELECT T2.publisher_name\nFROM superhero AS T1\nINNER JOIN publisher AS T2 ON T1.publisher_id = T2.id\nINNER JOIN hero_attribute AS T3 ON T1.id = T3.hero_id\nINNER JOIN attribute AS T4 ON T3.attribute_id = T4.id\nWHERE T4.attribute_name = 'Speed' AND T3.attribute_value = (SELECT MIN(attribute_value) FROM hero_attribute WHERE attribute_id = T4.id)", "difficulty": "moderate" }, { "question_id": 733, "question": "How many gold-eyed superheroes did Marvel Comics publish?", "db_id": "superhero", "evidence": "gold-eyed refers to colour = 'Gold' where eye_colour_id = colour.id; superheroes that Marvel Comics published refers to publisher_name = 'Marvel Comics'", "code": "import pandas as pd\n\n# Merge superhero with publisher\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\n\n# Merge with colour for eye color\nmerged = pd.merge(merged, colour, left_on='eye_colour_id', right_on='id')\n\n# Filter for Marvel Comics and Gold eyes\nfiltered = merged[(merged['publisher_name'] == 'Marvel Comics') & (merged['colour'] == 'Gold')]\n\n# Count the number of superheroes\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN colour AS T3 ON T1.eye_colour_id = T3.id WHERE T2.publisher_name = 'Marvel Comics' AND T3.colour = 'Gold'", "difficulty": "moderate" }, { "question_id": 734, "question": "What is the publisher's name of Blue Beetle II?", "db_id": "superhero", "evidence": "superhero_name equals 'Blue Beetle II' in the database;", "code": "import pandas as pd\n\n# Assuming the tables are loaded into DataFrames: superhero, publisher\n# Example: superhero = pd.read_csv('superhero.csv'); publisher = pd.read_csv('publisher.csv')\n\n# Filter the superhero DataFrame for the name 'Blue Beetle II'\nfiltered_superhero = superhero[superhero['superhero_name'] == 'Blue Beetle II']\n\n# Join with the publisher DataFrame on the publisher_id and id columns\nresult = pd.merge(filtered_superhero, publisher, left_on='publisher_id', right_on='id', how='inner')\n\n# Select the publisher_name column\nfinal_result = result[['publisher_name']]\n\n# Handle empty results gracefully\nif final_result.empty:\n final_result = pd.DataFrame({'publisher_name': [None]})\n\n# Output the result (publisher_name)\nprint(final_result)", "sql": "SELECT T2.publisher_name FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.superhero_name = 'Blue Beetle II'", "difficulty": "simple" }, { "question_id": 735, "question": "How many superheroes with blonde hair are there?", "db_id": "superhero", "evidence": "colour equals 'Blond' in the database;", "code": "import pandas as pd\n\ndef solve_query(superhero_df, colour_df):\n # Check if required columns exist\n if 'hair_colour_id' not in superhero_df.columns or 'id' not in colour_df.columns or 'colour' not in colour_df.columns:\n return pd.DataFrame({'count': [0]})\n\n # Merge superhero and colour tables on hair_colour_id and id\n merged_df = pd.merge(superhero_df, colour_df, left_on='hair_colour_id', right_on='id', how='inner')\n\n # Filter rows where colour is 'Blond'\n blond_hair_df = merged_df[merged_df['colour'] == 'Blond']\n\n # Count the number of matching superheroes\n count_result = blond_hair_df['id_x'].count()\n\n # Return result as a DataFrame\n return pd.DataFrame({'count': [count_result]})\n\n# Example function call with placeholder DataFrames\nsuperhero_data = {'id': [1, 2, 3], 'hair_colour_id': [1, 2, None]}\ncolour_data = {'id': [1, 2], 'colour': ['Blond', 'Black']}\nsuperhero_df = pd.DataFrame(superhero_data)\ncolour_df = pd.DataFrame(colour_data)\nresult = solve_query(superhero_df, colour_df)\nprint(result)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.hair_colour_id = T2.id WHERE T2.colour = 'Blond'", "difficulty": "simple" }, { "question_id": 736, "question": "Who is the dumbest superhero?", "db_id": "superhero", "evidence": "attribute_name equals 'Intelligence' in the database;", "code": "import pandas as pd\nmerged = pd.merge(superhero, hero_attribute, left_on='id', right_on='hero_id')\nmerged = pd.merge(merged, attribute, left_on='attribute_id', right_on='id')\nfiltered = merged[merged['attribute_name'] == 'Intelligence']\nresult = filtered.sort_values('attribute_value').head(1)[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T3.attribute_name = 'Intelligence' ORDER BY T2.attribute_value LIMIT 1", "difficulty": "moderate" }, { "question_id": 737, "question": "What is Copycat's race?", "db_id": "superhero", "evidence": "Copycat is the superhero_name;", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['superhero_name'] == 'Copycat'], race, left_on='race_id', right_on='id')[['race']]", "sql": "SELECT T2.race FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.superhero_name = 'Copycat'", "difficulty": "simple" }, { "question_id": 738, "question": "Which superheroes have a durability attribute value of less than 50?", "db_id": "superhero", "evidence": "attribute_name equals 'Durability' in the database; attribute_value is less than 50 in the database;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\ndf_attribute = pd.read_csv('attribute.csv')\n\nmerged_df = pd.merge(df_hero_attribute, df_attribute, left_on='attribute_id', right_on='id')\nfiltered_df = merged_df[(merged_df['attribute_name'] == 'Durability') & (merged_df['attribute_value'] < 50)]\nresult_df = df_superhero[df_superhero['id'].isin(filtered_df['hero_id'])][['superhero_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT superhero_name FROM superhero AS T1 WHERE EXISTS (SELECT 1 FROM hero_attribute AS T2 INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T3.attribute_name = 'Durability' AND T2.attribute_value < 50 AND T1.id = T2.hero_id)", "difficulty": "simple" }, { "question_id": 739, "question": "What are the names of the superheroes with the power of death touch?", "db_id": "superhero", "evidence": "name of superheroes refers to refers to superhero_name; the power of death touch refers to power_name = 'Death Touch'", "code": "import pandas as pd\nmerged = pd.merge(superhero, hero_power, left_on='id', right_on='hero_id')\nmerged = pd.merge(merged, superpower, left_on='power_id', right_on='id')\nfiltered = merged[merged['power_name'] == 'Death Touch']\nresult = filtered[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T3.power_name = 'Death Touch'", "difficulty": "moderate" }, { "question_id": 740, "question": "How many female superheroes have a strength value of 100?", "db_id": "superhero", "evidence": "female refers to gender = 'Female'; strength value of 100 refers to attribute_name = 'Strength' AND attribute_value = 100", "code": "import pandas as pd\n\n# Merge superhero with gender to filter females\nfemale_heroes = pd.merge(superhero, gender, left_on='gender_id', right_on='id')\nfemale_heroes = female_heroes[female_heroes['gender'] == 'Female']\n\n# Merge hero_attribute with attribute to filter strength\nstrength_attrs = pd.merge(hero_attribute, attribute, left_on='attribute_id', right_on='id')\nstrength_attrs = strength_attrs[(strength_attrs['attribute_name'] == 'Strength') & (strength_attrs['attribute_value'] == 100)]\n\n# Merge female heroes with strength attributes\nresult_df = pd.merge(female_heroes, strength_attrs, left_on='id_x', right_on='hero_id')\n\n# Count the number of female superheroes with strength 100\nresult = len(result_df)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id INNER JOIN gender AS T4 ON T1.gender_id = T4.id WHERE T3.attribute_name = 'Strength' AND T2.attribute_value = 100 AND T4.gender = 'Female'", "difficulty": "moderate" }, { "question_id": 741, "question": "What is the name of the superhero that has the most powers?", "db_id": "superhero", "evidence": "name of the superhero refers to superhero_name; superhero that has the most powers refers to MAX(COUNT(superhero_name))", "code": "import pandas as pd\nmerged = pd.merge(superhero[['id', 'superhero_name']], hero_power, left_on='id', right_on='hero_id')\npower_counts = merged.groupby('superhero_name').size().reset_index(name='power_count')\nresult = power_counts.sort_values('power_count', ascending=False).head(1)[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id GROUP BY T1.superhero_name ORDER BY COUNT(T2.hero_id) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 742, "question": "How many vampire superheroes are there?", "db_id": "superhero", "evidence": "race equals 'Vampire' in the database;", "code": "import pandas as pd\n\n# Merge superhero and race tables\nmerged = pd.merge(superhero, race, left_on='race_id', right_on='id')\n\n# Filter for Vampire race\nvampire_heroes = merged[merged['race'] == 'Vampire']\n\n# Count the number of vampire superheroes\nresult = len(vampire_heroes)", "sql": "SELECT COUNT(T1.superhero_name) FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T2.race = 'Vampire'", "difficulty": "simple" }, { "question_id": 743, "question": "What is the percentage of superheroes who act in their own self-interest or make decisions based on their own moral code? Indicate how many of the said superheroes were published by Marvel Comics.", "db_id": "superhero", "evidence": "published by Marvel Comics refers to publisher_name = 'Marvel Comics'; superheroes who act in their own self-interest or make decisions based on their own moral code refers to alignment = 'Bad'; calculation = MULTIPLY(DIVIDE(SUM(alignment = 'Bad); count(id)), 100)", "code": "import pandas as pd\n\n# Merge superhero with alignment and publisher tables\nmerged = pd.merge(superhero, alignment, left_on='alignment_id', right_on='id', suffixes=('', '_align'))\nmerged = pd.merge(merged, publisher, left_on='publisher_id', right_on='id', suffixes=('', '_pub'))\n\n# Filter for 'Bad' alignment\nbad_heroes = merged[merged['alignment'] == 'Bad']\n\n# Calculate percentage of bad heroes\ntotal_heroes = len(superhero)\nbad_count = len(bad_heroes)\npercentage = (bad_count * 100.0) / total_heroes\n\n# Count Marvel Comics bad heroes\nmarvel_count = len(bad_heroes[bad_heroes['publisher_name'] == 'Marvel Comics'])\n\n# Create result\nresult = pd.DataFrame({'percentage': [percentage], 'marvel_count': [float(marvel_count)]})", "sql": "SELECT (CAST(COUNT(*) AS REAL) * 100 / (SELECT COUNT(*) FROM superhero)) AS percentage, CAST(SUM(CASE WHEN T2.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) AS REAL) AS marvel_count FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN alignment AS T3 ON T3.id = T1.alignment_id WHERE T3.alignment = 'Bad';", "difficulty": "challenging" }, { "question_id": 744, "question": "Between DC and Marvel Comics, which publisher has published more superheroes? Find the difference in the number of superheroes they have published.", "db_id": "superhero", "evidence": "DC refers to publisher_name = 'DC Comics'; Marvel Comics refers to publisher_name = 'Marvel Comics'; calculation = SUBTRACT(SUM(publisher_name = 'Marvel Comics'), SUM(publisher_name = 'DC Comics'))", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nmarvel_count = len(merged[merged['publisher_name'] == 'Marvel Comics'])\ndc_count = len(merged[merged['publisher_name'] == 'DC Comics'])\nresult = marvel_count - dc_count", "sql": "SELECT SUM(CASE WHEN T2.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) - SUM(CASE WHEN T2.publisher_name = 'DC Comics' THEN 1 ELSE 0 END) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id", "difficulty": "challenging" }, { "question_id": 745, "question": "Give the publisher ID of Star Trek.", "db_id": "superhero", "evidence": "Star Trek is the publisher_name;", "code": "import pandas as pd\nresult = publisher[publisher['publisher_name'] == 'Star Trek'][['id']]", "sql": "SELECT id FROM publisher WHERE publisher_name = 'Star Trek'", "difficulty": "simple" }, { "question_id": 746, "question": "Calculate the average attribute value of all superheroes.", "db_id": "superhero", "evidence": "average of attribute_value;", "code": "import pandas as pd\n\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\nresult = df_hero_attribute['attribute_value'].mean()", "sql": "SELECT AVG(attribute_value) FROM hero_attribute", "difficulty": "simple" }, { "question_id": 747, "question": "What is the total number of superheroes without full name?", "db_id": "superhero", "evidence": "superheroes without full name refers to full_name IS NULL", "code": "import pandas as pd\nresult = superhero[superhero['full_name'].isna()]['id'].count()", "sql": "SELECT COUNT(id) FROM superhero WHERE full_name IS NULL", "difficulty": "simple" }, { "question_id": 748, "question": "What is the eye colour of superhero with superhero ID 75?", "db_id": "superhero", "evidence": "eye colour refers to colour where eye_colour_id = colour.id;", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['id'] == 75][['id', 'eye_colour_id']], colour, left_on='eye_colour_id', right_on='id')[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.id = 75", "difficulty": "simple" }, { "question_id": 749, "question": "Provide the superpowers of the superhero called Deathlok.", "db_id": "superhero", "evidence": "superpowers refers to power_name; Deathlok refers to superhero_name = 'Deathlok'", "code": "import pandas as pd\n\n# 找出Deathlok的hero_id\ndeathlok = superhero[superhero['superhero_name'] == 'Deathlok']\n\n# 连接hero_power表获取power_id\nmerged = pd.merge(deathlok[['id']], hero_power, left_on='id', right_on='hero_id')\n\n# 连接superpower表获取power_name\nresult = pd.merge(merged[['power_id']], superpower, left_on='power_id', right_on='id')[['power_name']]", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.superhero_name = 'Deathlok'", "difficulty": "simple" }, { "question_id": 750, "question": "What is the average weight of all female superheroes?", "db_id": "superhero", "evidence": "female refers to gender = 'Female'; average weight refers to AVG(weight_kg)", "code": "import pandas as pd\nmerged = pd.merge(superhero, gender, left_on='gender_id', right_on='id')\nfemale_heroes = merged[merged['gender'] == 'Female']\nresult = female_heroes['weight_kg'].mean()", "sql": "SELECT AVG(T1.weight_kg) FROM superhero AS T1 INNER JOIN gender AS T2 ON T1.gender_id = T2.id WHERE T2.gender = 'Female'", "difficulty": "simple" }, { "question_id": 751, "question": "List down at least five superpowers of male superheroes.", "db_id": "superhero", "evidence": "male refers to gender = 'Male'; superpowers refers to power_name;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_power = pd.read_csv('hero_power.csv')\ndf_superpower = pd.read_csv('superpower.csv')\ndf_gender = pd.read_csv('gender.csv')\n\nmerged_df = df_superhero.merge(df_hero_power, left_on='id', right_on='hero_id')\nmerged_df = merged_df.merge(df_superpower, left_on='power_id', right_on='id')\nmerged_df = merged_df.merge(df_gender, left_on='gender_id', right_on='id')\n\nresult_df = merged_df[merged_df['gender'] == 'Male'][['power_name']]\nresult = result_df.head(5).reset_index(drop=True)", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T3.id = T2.power_id INNER JOIN gender AS T4 ON T4.id = T1.gender_id WHERE T4.gender = 'Male' LIMIT 5", "difficulty": "moderate" }, { "question_id": 752, "question": "Give the name of the alien superheroes.", "db_id": "superhero", "evidence": "alien superheroes refers to race = 'Alien'; name of superhero refers to superhero_name;", "code": "import pandas as pd\nmerged = pd.merge(superhero, race, left_on='race_id', right_on='id')\nalien_heroes = merged[merged['race'] == 'Alien']\nresult = alien_heroes[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T2.race = 'Alien'", "difficulty": "simple" }, { "question_id": 753, "question": "Among the superheroes with height from 170 to 190, list the names of the superheroes with no eye color.", "db_id": "superhero", "evidence": "height from 170 to 190 refers to height_cm BETWEEN 170 AND 190; no eye color refers to colour = 'No Colour'", "code": "import pandas as pd\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id')\nfiltered = merged[(merged['height_cm'].between(170, 190)) & (merged['colour'] == 'No Colour')]\nresult = filtered[['superhero_name']].drop_duplicates()", "sql": "SELECT DISTINCT T1.superhero_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.height_cm BETWEEN 170 AND 190 AND T2.colour = 'No Colour'", "difficulty": "moderate" }, { "question_id": 754, "question": "What is the superpower of hero ID 56?", "db_id": "superhero", "evidence": "superpower refers to hero_power", "code": "import pandas as pd\n\ndf_hero_power = pd.read_csv('hero_power.csv')\ndf_superpower = pd.read_csv('superpower.csv')\n\nmerged_df = df_hero_power.merge(df_superpower, left_on='power_id', right_on='id')\nresult_df = merged_df[merged_df['hero_id'] == 56][['power_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T2.power_name FROM hero_power AS T1 INNER JOIN superpower AS T2 ON T1.power_id = T2.id WHERE T1.hero_id = 56", "difficulty": "simple" }, { "question_id": 755, "question": "List down at least five full name of Demi-God superheroes.", "db_id": "superhero", "evidence": "race equals 'Demi-God' in the database;", "code": "import pandas as pd\nmerged = pd.merge(superhero, race, left_on='race_id', right_on='id')\nfiltered = merged[merged['race'] == 'Demi-God']\nresult = filtered[['full_name']].head(5)", "sql": "SELECT T1.full_name FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T2.race = 'Demi-God'", "difficulty": "simple" }, { "question_id": 756, "question": "How many bad superheroes are there?", "db_id": "superhero", "evidence": "bad superheroes refers to alignment_id = Bad", "code": "import pandas as pd\nbad_alignment = alignment[alignment['alignment'] == 'Bad']\nmerged = pd.merge(superhero, bad_alignment, left_on='alignment_id', right_on='id')\nresult = len(merged)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id WHERE T2.alignment = 'Bad'", "difficulty": "simple" }, { "question_id": 757, "question": "Identify the race of the superhero who weighed 169 kg.", "db_id": "superhero", "evidence": "weight_kg equals 169 in the database;", "code": "import pandas as pd\nfiltered_superhero = superhero[superhero['weight_kg'] == 169]\nmerged = pd.merge(filtered_superhero, race, left_on='race_id', right_on='id')\nresult = merged[['race']]", "sql": "SELECT T2.race FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.weight_kg = 169", "difficulty": "simple" }, { "question_id": 758, "question": "Provide the hair colour of the human superhero who is 185 cm tall.", "db_id": "superhero", "evidence": "185 cm tall refers to height_cm = 185; human superhero refers to race = 'human'; hair colour refers to colour where hair_colour_id = colour.id;", "code": "import pandas as pd\n\n# Merge superhero with race table\nmerged = pd.merge(superhero, race, left_on='race_id', right_on='id')\n\n# Filter for human superheroes with height 185 cm\nfiltered = merged[(merged['race'] == 'Human') & (merged['height_cm'] == 185)]\n\n# Merge with colour table to get hair colour\nresult_merged = pd.merge(filtered, colour, left_on='hair_colour_id', right_on='id')\n\n# Get distinct hair colours\nresult = result_merged[['colour']].drop_duplicates()", "sql": "SELECT DISTINCT T3.colour FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id INNER JOIN colour AS T3 ON T1.hair_colour_id = T3.id WHERE T1.height_cm = 185 AND T2.race = 'Human'", "difficulty": "moderate" }, { "question_id": 759, "question": "What is the eye clolour of the heaviest superhero?", "db_id": "superhero", "evidence": "the heaviest superhero refers to MAX(weight_kg); eye colour refers to colour where eye_colour_id = colour.id;", "code": "import pandas as pd\nimport numpy as np\n\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id')\nresult = merged.sort_values('weight_kg', ascending=False).head(1)[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id ORDER BY T1.weight_kg DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 760, "question": "In superheroes with height between 150 to 180, what is the percentage of heroes published by Marvel Comics?", "db_id": "superhero", "evidence": "height between 150 to 180 refers to height_cm BETWEEN 150 AND 180; heroes published by Marvel Comics refers to publisher_name = 'Marvel Comics'; calculation = MULTIPLY(DIVIDE(SUM(publisher.id = 13)), COUNT(publisher.id), 100)", "code": "import pandas as pd\n\n# Filter superheroes with height between 150 and 180\nfiltered_heroes = superhero[(superhero['height_cm'] >= 150) & (superhero['height_cm'] <= 180)]\n\n# Merge with publisher table\nmerged = pd.merge(filtered_heroes, publisher, left_on='publisher_id', right_on='id', how='inner')\n\n# Calculate percentage of Marvel Comics heroes\nmarvel_count = len(merged[merged['publisher_name'] == 'Marvel Comics'])\ntotal_count = len(merged)\n\nresult = (marvel_count / total_count) * 100 if total_count > 0 else 0", "sql": "SELECT CAST(COUNT(CASE WHEN T2.publisher_name = 'Marvel Comics' THEN 1 ELSE NULL END) AS REAL) * 100 / COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.height_cm BETWEEN 150 AND 180", "difficulty": "challenging" }, { "question_id": 761, "question": "Among the male superheroes, list the super hero names of superheroes with weight greater than the 79% average weight of all superheroes.", "db_id": "superhero", "evidence": "super hero names refers to superhero_name;male superheros refers to gender = 'Male';Calculation = weight_kg > MULTIPLY(AVG(weight_kg), 0.79)", "code": "import pandas as pd\navg_weight = superhero['weight_kg'].mean()\nfiltered = pd.merge(superhero, gender, left_on='gender_id', right_on='id')\nfiltered = filtered[(filtered['gender'] == 'Male') & (filtered['weight_kg'] > avg_weight * 0.79)]\nresult = filtered[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN gender AS T2 ON T1.gender_id = T2.id WHERE T2.gender = 'Male' AND T1.weight_kg * 100 > ( SELECT AVG(weight_kg) FROM superhero ) * 79", "difficulty": "moderate" }, { "question_id": 762, "question": "Which power do superheroes have the most of?", "db_id": "superhero", "evidence": "count of power_name;", "code": "import pandas as pd\nmerged = pd.merge(hero_power, superpower, left_on='power_id', right_on='id')\npower_counts = merged.groupby('power_name').size().reset_index(name='count')\nresult = power_counts.sort_values('count', ascending=False).head(1)[['power_name']]", "sql": "SELECT T2.power_name FROM hero_power AS T1 INNER JOIN superpower AS T2 ON T1.power_id = T2.id GROUP BY T2.power_name ORDER BY COUNT(T1.hero_id) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 763, "question": "Indicate the attribute value of superhero Abomination.", "db_id": "superhero", "evidence": "Abomination refers to superhero_name = 'Abomination';", "code": "import pandas as pd\nimport numpy as np\n\n# Filter superhero table for Abomination\nabomination = superhero[superhero['superhero_name'] == 'Abomination']\n\n# Get the hero_id\nhero_id = abomination['id'].iloc[0]\n\n# Filter hero_attribute table for this hero_id\nresult = hero_attribute[hero_attribute['hero_id'] == hero_id][['attribute_value']]", "sql": "SELECT T2.attribute_value FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id WHERE T1.superhero_name = 'Abomination'", "difficulty": "simple" }, { "question_id": 764, "question": "What are the superpowers of heroes with ID 1?", "db_id": "superhero", "evidence": "superpowers refers to power_name; heroes with ID 1 refers to hero_id = 1;", "code": "import pandas as pd\nmerged = pd.merge(hero_power[hero_power['hero_id'] == 1], superpower, left_on='power_id', right_on='id')\nresult = merged[['power_name']].drop_duplicates()", "sql": "SELECT DISTINCT T2.power_name FROM hero_power AS T1 INNER JOIN superpower AS T2 ON T1.power_id = T2.id WHERE T1.hero_id = 1", "difficulty": "simple" }, { "question_id": 765, "question": "How many heroes have stealth power?", "db_id": "superhero", "evidence": "stealth power refers to power_name = 'stealth';", "code": "import pandas as pd\nmerged = pd.merge(hero_power, superpower, left_on='power_id', right_on='id')\nfiltered = merged[merged['power_name'] == 'Stealth']\nresult = len(filtered['hero_id'])", "sql": "SELECT COUNT(DISTINCT T1.hero_id) FROM hero_power AS T1 INNER JOIN superpower AS T2 ON T1.power_id = T2.id WHERE T2.power_name = 'stealth'", "difficulty": "simple" }, { "question_id": 766, "question": "What is the hero's full name with the highest attribute in strength?", "db_id": "superhero", "evidence": "highest attribute in strength refers to MAX(attribute_value) WHERE attribute_name = 'strength';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\ndf_attribute = pd.read_csv('attribute.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_attribute, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_attribute, left_on='attribute_id', right_on='id')\n\nfiltered_df = merged_df[merged_df['attribute_name'] == 'Strength']\nsorted_df = filtered_df.sort_values(by='attribute_value', ascending=False)\nresult_df = sorted_df[['full_name']].head(1)\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T1.full_name FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T3.attribute_name = 'Strength' ORDER BY T2.attribute_value DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 767, "question": "What is the average of superheroes with no skin colour?", "db_id": "superhero", "evidence": "average = DIVIDE(COUNT(superhero.id), SUM(skin_colour_id = 1)); no skin colour refers to skin_colour_id WHERE colour.id = 1;", "code": "import pandas as pd\nno_skin_count = superhero[superhero['skin_colour_id'] == 1].shape[0]\ntotal = superhero.shape[0]\naverage = total / no_skin_count\nresult = pd.DataFrame([average], columns=['average'])", "sql": "SELECT CAST(COUNT(*) AS REAL) / SUM(CASE WHEN skin_colour_id = 1 THEN 1 ELSE 0 END) FROM superhero", "difficulty": "simple" }, { "question_id": 768, "question": "How many superheroes were published by Dark Horse Comics?", "db_id": "superhero", "evidence": "published by Dark Horse Comics refers to publisher_name = 'Dark Horse Comics';", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nfiltered = merged[merged['publisher_name'] == 'Dark Horse Comics']\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T2.publisher_name = 'Dark Horse Comics'", "difficulty": "simple" }, { "question_id": 769, "question": "Which superhero has the most durability published by Dark Horse Comics?", "db_id": "superhero", "evidence": "which superhero refers to superhero_name; most durability refers to MAX(attribute_value) WHERE attribute_name = 'durability'; published by Dark Horse Comics refers to publisher_name = 'Dark Horse Comics';", "code": "import pandas as pd\n\n# Merge superhero with publisher to filter by Dark Horse Comics\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nmerged = merged[merged['publisher_name'] == 'Dark Horse Comics']\n\n# Merge with hero_attribute\nmerged = pd.merge(merged, hero_attribute, left_on='id_x', right_on='hero_id')\n\n# Merge with attribute to filter by Durability\nmerged = pd.merge(merged, attribute, left_on='attribute_id', right_on='id')\nmerged = merged[merged['attribute_name'] == 'Durability']\n\n# Sort by attribute_value descending and get the top 1\nresult = merged.sort_values('attribute_value', ascending=False).head(1)[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T3.id = T2.attribute_id INNER JOIN publisher AS T4 ON T4.id = T1.publisher_id WHERE T4.publisher_name = 'Dark Horse Comics' AND T3.attribute_name = 'durability' ORDER BY T2.attribute_value DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 770, "question": "What is the eyes colour of Abraham Sapien?", "db_id": "superhero", "evidence": "eye colour refers to colour.colour where eye_colour_id = colour.id; Abraham Sapien is the full name of superhero;", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['full_name'] == 'Abraham Sapien'], colour, left_on='eye_colour_id', right_on='id')[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.full_name = 'Abraham Sapien'", "difficulty": "simple" }, { "question_id": 771, "question": "List the name of superheroes with flight power.", "db_id": "superhero", "evidence": "name of superheroes refers to superhero_name; flight power refers to power_name = 'Flight';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_power = pd.read_csv('hero_power.csv')\ndf_superpower = pd.read_csv('superpower.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_power, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_superpower, left_on='power_id', right_on='id')\n\nresult_df = merged_df[merged_df['power_name'] == 'Flight'][['superhero_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T3.power_name = 'Flight'", "difficulty": "simple" }, { "question_id": 772, "question": "List the eyes, hair and skin colour of all female superheroes published by Dark Horse Comics.", "db_id": "superhero", "evidence": "eyes refers to eye_colour_id; hair refers to hair_colour_id; skin colour refers to skin_colour_id; female superheroes refers to gender = 'Female'; published by Dark Horse Comics refers to publisher_name = 'Dark Horse Comics';", "code": "import pandas as pd\n\n# Merge superhero with publisher\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\n\n# Merge with gender\nmerged = pd.merge(merged, gender, left_on='gender_id', right_on='id')\n\n# Filter for Dark Horse Comics and Female\nfiltered = merged[(merged['publisher_name'] == 'Dark Horse Comics') & (merged['gender'] == 'Female')]\n\n# Select the required columns\nresult = filtered[['eye_colour_id', 'hair_colour_id', 'skin_colour_id']]", "sql": "SELECT T1.eye_colour_id, T1.hair_colour_id, T1.skin_colour_id FROM superhero AS T1 INNER JOIN publisher AS T2 ON T2.id = T1.publisher_id INNER JOIN gender AS T3 ON T3.id = T1.gender_id WHERE T2.publisher_name = 'Dark Horse Comics' AND T3.gender = 'Female'", "difficulty": "challenging" }, { "question_id": 773, "question": "Which superhero has the same eyes, hair and skin colour? Indicate the publisher of the superhero.", "db_id": "superhero", "evidence": "which superhero refers to superhero_name; the same eyes, hair and skin colour refers to hair_colour_id = skin_colour_id AND hair_colour_id = eye_colour_id; publisher refers to publisher_name;", "code": "import pandas as pd\nfiltered_superhero = superhero[(superhero['eye_colour_id'] == superhero['hair_colour_id']) & (superhero['eye_colour_id'] == superhero['skin_colour_id'])]\nresult = pd.merge(filtered_superhero[['superhero_name', 'publisher_id']], publisher, left_on='publisher_id', right_on='id')[['superhero_name', 'publisher_name']]", "sql": "SELECT T1.superhero_name, T2.publisher_name FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.eye_colour_id = T1.hair_colour_id AND T1.eye_colour_id = T1.skin_colour_id", "difficulty": "challenging" }, { "question_id": 774, "question": "Which group does superhero A-Bomb belong to?", "db_id": "superhero", "evidence": "group refers to race; A-Bomb refers to superhero_name = 'A-Bomb';", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['superhero_name'] == 'A-Bomb'], race, left_on='race_id', right_on='id')[['race']]", "sql": "SELECT T2.race FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.superhero_name = 'A-Bomb'", "difficulty": "simple" }, { "question_id": 775, "question": "What is the percentage of blue female superheroes among all female superheroes?", "db_id": "superhero", "evidence": "percentage = MULTIPLY(DIVIDE(SUM(colour = 'Blue' WHERE gender = 'Female'), COUNT(gender = 'Female')), 100); blue refers to the color = 'Blue' WHERE skin_colour_id = colour.id; female refers to gender = 'Female';", "code": "import pandas as pd\n\n# Merge superhero with gender and colour tables\nmerged = pd.merge(superhero, gender, left_on='gender_id', right_on='id', suffixes=('', '_gender'))\nmerged = pd.merge(merged, colour, left_on='skin_colour_id', right_on='id', suffixes=('', '_colour'))\n\n# Filter for female superheroes\nfemale_heroes = merged[merged['gender'] == 'Female']\n\n# Count blue female superheroes\nblue_female_count = len(female_heroes[female_heroes['colour'] == 'Blue'])\n\n# Count all female superheroes\ntotal_female_count = len(female_heroes)\n\n# Calculate percentage\nresult = (blue_female_count / total_female_count) * 100 if total_female_count > 0 else 0", "sql": "SELECT CAST(COUNT(CASE WHEN T3.colour = 'Blue' THEN T1.id ELSE NULL END) AS REAL) * 100 / COUNT(T1.id) FROM superhero AS T1 INNER JOIN gender AS T2 ON T1.gender_id = T2.id INNER JOIN colour AS T3 ON T1.skin_colour_id = T3.id WHERE T2.gender = 'Female'", "difficulty": "challenging" }, { "question_id": 776, "question": "Provide the hero name and race of Charles Chandler.", "db_id": "superhero", "evidence": "hero name refers to superhero_name; Charles Chandler is the full name of superhero;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_race = pd.read_csv('race.csv')\n\nmerged_df = pd.merge(df_superhero, df_race, left_on='race_id', right_on='id')\nresult_df = merged_df[merged_df['full_name'] == 'Charles Chandler'][['superhero_name', 'race']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T1.superhero_name, T2.race FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.full_name = 'Charles Chandler'", "difficulty": "simple" }, { "question_id": 777, "question": "What is the gender of Agent 13 hero?", "db_id": "superhero", "evidence": "Agent 13 hero refers to superhero_name = 'Agent 13';", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['superhero_name'] == 'Agent 13'][['gender_id']], gender, left_on='gender_id', right_on='id')[['gender']]", "sql": "SELECT T2.gender FROM superhero AS T1 INNER JOIN gender AS T2 ON T1.gender_id = T2.id WHERE T1.superhero_name = 'Agent 13'", "difficulty": "simple" }, { "question_id": 778, "question": "Provide superheroes' names who have the adaptation power.", "db_id": "superhero", "evidence": "adaptation power refers to power_name = 'Adaptation';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_power = pd.read_csv('hero_power.csv')\ndf_superpower = pd.read_csv('superpower.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_power, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_superpower, left_on='power_id', right_on='id')\n\nresult_df = merged_df[merged_df['power_name'] == 'Adaptation'][['superhero_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T3.power_name = 'Adaptation'", "difficulty": "simple" }, { "question_id": 779, "question": "How many powers does Amazo hero have?", "db_id": "superhero", "evidence": "Amazo hero refers to superhero_name = 'Amazo';", "code": "import pandas as pd\nmerged = pd.merge(hero_power, superhero, left_on='hero_id', right_on='id')\nfiltered = merged[merged['superhero_name'] == 'Amazo']\nresult = len(filtered)", "sql": "SELECT COUNT(T1.power_id) FROM hero_power AS T1 INNER JOIN superhero AS T2 ON T1.hero_id = T2.id WHERE T2.superhero_name = 'Amazo'", "difficulty": "simple" }, { "question_id": 780, "question": "List the powers of Hunter Zolomon.", "db_id": "superhero", "evidence": "Hunter Zolomon is the full name of superhero; list the powers refers to power_name;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_power = pd.read_csv('hero_power.csv')\ndf_superpower = pd.read_csv('superpower.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_power, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_superpower, left_on='power_id', right_on='id')\n\nresult_df = merged_df[merged_df['full_name'] == 'Hunter Zolomon'][['power_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.full_name = 'Hunter Zolomon'", "difficulty": "simple" }, { "question_id": 781, "question": "Provide the heights of the heroes whose eye colours are amber.", "db_id": "superhero", "evidence": "heights of the heroes refers to height_cm; eye colours are amber refers to colour.colour = 'Amber' WHERE eye_colour_id = colour.id;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge superhero with colour table on eye_colour_id\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id', suffixes=('', '_colour'))\n\n# Filter for amber eye colour\namber_heroes = merged[merged['colour'] == 'Amber']\n\n# Select only the height_cm column\nresult = amber_heroes[['height_cm']]", "sql": "SELECT T1.height_cm FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T2.colour = 'Amber'", "difficulty": "simple" }, { "question_id": 782, "question": "List the heroes' names whose eyes and hair colours are both black.", "db_id": "superhero", "evidence": "heroes' names refers to superhero_name; eyes and hair colours are both black refers to eye_colour_id AND hair_colour_id WHERE colour.colour = 'Black';", "code": "import pandas as pd\nimport numpy as np\n\n# Get black colour id\nblack_colour = colour[colour['colour'] == 'Black']\nblack_colour_id = black_colour['id'].iloc[0]\n\n# Filter superheroes with both black eyes and black hair\nfiltered_heroes = superhero[(superhero['eye_colour_id'] == black_colour_id) & (superhero['hair_colour_id'] == black_colour_id)]\n\n# Select only the superhero names\nresult = filtered_heroes[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id AND T1.hair_colour_id = T2.id WHERE T2.colour = 'Black'", "difficulty": "moderate" }, { "question_id": 783, "question": "Provide the eye colours of the heroes whose skin colours are gold.", "db_id": "superhero", "evidence": "skin colours are gold refers to colour.colour = 'Gold' WHERE skin_colour_id = colour.id;", "code": "import pandas as pd\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id')\nmerged = pd.merge(merged, colour, left_on='skin_colour_id', right_on='id', suffixes=('_eye', '_skin'))\nfiltered = merged[merged['colour_skin'] == 'Gold']\nresult = filtered[['colour_eye']].rename(columns={'colour_eye': 'colour'})", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id INNER JOIN colour AS T3 ON T1.skin_colour_id = T3.id WHERE T3.colour = 'Gold'", "difficulty": "simple" }, { "question_id": 784, "question": "Provide the full names of vampire heroes.", "db_id": "superhero", "evidence": "vampire heroes refers to race = 'Vampire';", "code": "import pandas as pd\nmerged = pd.merge(superhero, race, left_on='race_id', right_on='id')\nfiltered = merged[merged['race'] == 'Vampire']\nresult = filtered[['full_name']]", "sql": "SELECT T1.full_name FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T2.race = 'Vampire'", "difficulty": "simple" }, { "question_id": 785, "question": "Describe the names of neutral alignment superheroes.", "db_id": "superhero", "evidence": "names of superheroes refers to superhero_name; neutral alignment refers to alignment = 'Neutral';", "code": "import pandas as pd\nmerged = pd.merge(superhero, alignment, left_on='alignment_id', right_on='id')\nfiltered = merged[merged['alignment'] == 'Neutral']\nresult = filtered[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id WHERE T2.alignment = 'Neutral'", "difficulty": "simple" }, { "question_id": 786, "question": "How many heroes have the highest attribute value in strength?", "db_id": "superhero", "evidence": "highest attribute value in strength refers to MAX(attribute_value) WHERE attribute_name = 'Strength';", "code": "import pandas as pd\n\n# Get strength attribute id\nstrength_attr = attribute[attribute['attribute_name'] == 'Strength']\nstrength_id = strength_attr['id'].iloc[0]\n\n# Filter hero_attribute for strength only\nstrength_heroes = hero_attribute[hero_attribute['attribute_id'] == strength_id]\n\n# Find max strength value\nmax_strength = strength_heroes['attribute_value'].max()\n\n# Count heroes with max strength\nresult = len(strength_heroes[strength_heroes['attribute_value'] == max_strength])", "sql": "SELECT COUNT(T1.hero_id) FROM hero_attribute AS T1 INNER JOIN attribute AS T2 ON T1.attribute_id = T2.id WHERE T2.attribute_name = 'Strength' AND T1.attribute_value = ( SELECT MAX(T3.attribute_value) FROM hero_attribute AS T3 INNER JOIN attribute AS T4 ON T3.attribute_id = T4.id WHERE T4.attribute_name = 'Strength' )", "difficulty": "moderate" }, { "question_id": 787, "question": "What are the race and alignment of Cameron Hicks?", "db_id": "superhero", "evidence": "Cameron Hicks refers to superhero_name = 'Cameron Hicks';", "code": "import pandas as pd\nmerged = pd.merge(superhero[superhero['superhero_name'] == 'Cameron Hicks'], race, left_on='race_id', right_on='id')\nmerged = pd.merge(merged, alignment, left_on='alignment_id', right_on='id')\nresult = merged[['race', 'alignment']]", "sql": "SELECT T2.race, T3.alignment FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id INNER JOIN alignment AS T3 ON T1.alignment_id = T3.id WHERE T1.superhero_name = 'Cameron Hicks'", "difficulty": "simple" }, { "question_id": 788, "question": "How many percent of female heroes were published by Marvel Comics?", "db_id": "superhero", "evidence": "percent = MULTIPLY(DIVIDE(SUM(gender = 'Female' WHERE publisher_name = 'Marvel Comics'), COUNT(publisher_name = 'Marvel Comics')), 100); female heroes refers to gender = 'Female'; Marvel Comics refers to publisher_name = 'Marvel Comics';percent = MULTIPLY(DIVIDE(COUNT(T2.publisher_name = 'Marvel Comics' AND T3.gender = 'Female'), COUNT(T3.gender = 'Female')), 100); female heroes refers to T3.gender = 'Female'; Marvel Comics refers to T2.publisher_name = 'Marvel Comics'", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id', how='inner')\nmerged = pd.merge(merged, gender, left_on='gender_id', right_on='id', how='inner')\nmarvel = merged[merged['publisher_name'] == 'Marvel Comics']\nfemale_count = marvel[marvel['gender'] == 'Female'].shape[0]\ntotal_count = marvel.shape[0]\nresult = (female_count / total_count) * 100", "sql": "SELECT CAST(COUNT(CASE WHEN T2.publisher_name = 'Marvel Comics' AND T3.gender = 'Female' THEN 1 ELSE NULL END) AS REAL) * 100 / COUNT(CASE WHEN T2.publisher_name = 'Marvel Comics' THEN 1 ELSE NULL END) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN gender AS T3 ON T1.gender_id = T3.id", "difficulty": "challenging" }, { "question_id": 789, "question": "Find the average weight of the heroes who are aliens.", "db_id": "superhero", "evidence": "average = AVG(weight_kg); aliens refers to race = 'Alien';", "code": "import pandas as pd\nimport numpy as np\nalien_race = race[race['race'] == 'Alien']\nmerged = pd.merge(superhero, alien_race, left_on='race_id', right_on='id')\nresult = merged['weight_kg'].mean()", "sql": "SELECT CAST(SUM(T1.weight_kg) AS REAL) / COUNT(T1.id) FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T2.race = 'Alien'", "difficulty": "simple" }, { "question_id": 790, "question": "Calculate the difference between Emil Blonsky's weight and Charles Chandler's weight.", "db_id": "superhero", "evidence": "full_name equals 'Emil Blonsky' in the database; full_name equals 'Charles Chandler' in the database; sum of weight_kg WHERE full_name = 'Emil Blonsky'; sum of weight_kg WHERE full_name = 'Charles Chandler';", "code": "import pandas as pd\nemil_weight = superhero[superhero['full_name'] == 'Emil Blonsky']['weight_kg'].values[0]\ncharles_weight = superhero[superhero['full_name'] == 'Charles Chandler']['weight_kg'].values[0]\nresult = emil_weight - charles_weight", "sql": "SELECT ( SELECT weight_kg FROM superhero WHERE full_name LIKE 'Emil Blonsky' ) - ( SELECT weight_kg FROM superhero WHERE full_name LIKE 'Charles Chandler' ) AS CALCULATE", "difficulty": "moderate" }, { "question_id": 791, "question": "Calculate the average height for each superhero.", "db_id": "superhero", "evidence": "count of all heros; sum of height_cm;", "code": "import pandas as pd\nresult = superhero[['id', 'superhero_name', 'height_cm']].rename(columns={'height_cm': 'average_height'})", "sql": "SELECT id, superhero_name, height_cm AS average_height FROM superhero", "difficulty": "simple" }, { "question_id": 792, "question": "What is Abomination's superpower?", "db_id": "superhero", "evidence": "Abomination refers to superhero_name = 'Abomination'; superpower refers to power_name;", "code": "import pandas as pd\n\n# 假设数据已存在为DataFrame变量\n# superhero, hero_power, superpower\n\n# 筛选出Abomination的记录\nabomination = superhero[superhero['superhero_name'] == 'Abomination']\n\n# 与hero_power表连接\nmerged = pd.merge(abomination, hero_power, left_on='id', right_on='hero_id')\n\n# 与superpower表连接获取超能力名称\nresult = pd.merge(merged, superpower, left_on='power_id', right_on='id')[['power_name']]", "sql": "SELECT T3.power_name FROM superhero AS T1 JOIN hero_power AS T2 ON T1.id = T2.hero_id JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.superhero_name = 'Abomination'", "difficulty": "simple" }, { "question_id": 793, "question": "Among the superheroes with the race of god/eternal, how many of them are male", "db_id": "superhero", "evidence": "race \"god/eternal\" refers to race_id = 21; male refers to gender.id = 1", "code": "import pandas as pd\nresult = superhero[(superhero['race_id'] == 21) & (superhero['gender_id'] == 1)].shape[0]", "sql": "SELECT COUNT(*) FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id INNER JOIN gender AS T3 ON T3.id = T1.gender_id WHERE T1.race_id = 21 AND T1.gender_id = 1", "difficulty": "simple" }, { "question_id": 794, "question": "Which hero was the fastest?", "db_id": "superhero", "evidence": "which hero refers to superhero_name; fastest refers to MAX(attribute_value) WHERE attribute_name = 'Speed';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\ndf_attribute = pd.read_csv('attribute.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_attribute, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_attribute, left_on='attribute_id', right_on='id')\n\nfiltered_df = merged_df[merged_df['attribute_name'] == 'Speed']\nsorted_df = filtered_df.sort_values(by='attribute_value', ascending=False)\nresult_df = sorted_df[['superhero_name']].head(1)\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T3.attribute_name = 'Speed' ORDER BY T2.attribute_value DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 795, "question": "How many superheroes have a neutral alignment?", "db_id": "superhero", "evidence": "neutral alignment refers to alignment_id = 3;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge superhero with alignment table\nmerged = pd.merge(superhero, alignment, left_on='alignment_id', right_on='id', suffixes=('', '_align'))\n\n# Filter for neutral alignment and count\nresult = len(merged[merged['alignment'] == 'Neutral'])", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id WHERE T2.alignment = 'Neutral'", "difficulty": "simple" }, { "question_id": 796, "question": "State all of 3-D Man's attributes along with their values.", "db_id": "superhero", "evidence": "3-D Man is the superhero_name. attributes refers to attribute_name; values refers to attribute_value;", "code": "import pandas as pd\n\n# Filter superhero table for 3-D Man\nhero_3d_man = superhero[superhero['superhero_name'] == '3-D Man']\n\n# Get the hero_id\nhero_id = hero_3d_man['id'].iloc[0]\n\n# Filter hero_attribute for this hero\nhero_attrs = hero_attribute[hero_attribute['hero_id'] == hero_id]\n\n# Merge with attribute table to get attribute names\nresult = pd.merge(hero_attrs, attribute, left_on='attribute_id', right_on='id')\n\n# Select only the required columns\nresult = result[['attribute_name', 'attribute_value']]", "sql": "SELECT T3.attribute_name, T2.attribute_value FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T1.superhero_name = '3-D Man'", "difficulty": "moderate" }, { "question_id": 797, "question": "Which superheroes have blue eyes with brown hair?", "db_id": "superhero", "evidence": "which superheroes refers to superhero_name; blue eyes refers to color = 'Blue' and color.id = eye_colour_id; brown hair refers to color = 'Brown' and color.id = hair_colour_id;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge superhero with eye colour\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id', suffixes=('', '_eye'))\n# Filter for blue eyes\nblue_eyes = merged[merged['colour'] == 'Blue']\n\n# Merge with hair colour\nmerged2 = pd.merge(blue_eyes, colour, left_on='hair_colour_id', right_on='id', suffixes=('', '_hair'))\n# Filter for brown hair\nbrown_hair = merged2[merged2['colour_hair'] == 'Brown']\n\n# Select superhero names\nresult = brown_hair[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id INNER JOIN colour AS T3 ON T1.hair_colour_id = T3.id WHERE T2.colour = 'Blue' AND T3.colour = 'Brown'", "difficulty": "moderate" }, { "question_id": 798, "question": "What is the publisher for Hawkman, Karate Kid and Speedy?", "db_id": "superhero", "evidence": "publisher refers to publisher_name; Hawkman refers to superhero_name = 'Hawkman'; Karate Kid refers to superhero_name = 'Karate Kid'; Speedy refers to superhero_name = 'Speedy';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_publisher = pd.read_csv('publisher.csv')\n\nmerged_df = pd.merge(df_superhero, df_publisher, left_on='publisher_id', right_on='id')\nresult_df = merged_df[merged_df['superhero_name'].isin(['Hawkman', 'Karate Kid', 'Speedy'])][['publisher_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T2.publisher_name FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.superhero_name IN ('Hawkman', 'Karate Kid', 'Speedy')", "difficulty": "moderate" }, { "question_id": 799, "question": "How many superheroes didn't have any publisher?", "db_id": "superhero", "evidence": "didn't have any publisher refers to publisher.id = 1;", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nfiltered = merged[merged['id_y'] == 1]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T2.id = 1", "difficulty": "simple" }, { "question_id": 800, "question": "Calculate the percentage of superheroes with blue eyes.", "db_id": "superhero", "evidence": "percentage = MULTIPLY(DIVIDE(SUM(superhero_name WHERE color = 'Blue'), COUNT(superhero_name)), 100.0); blue eyes refers to color = 'Blue' and color.id = eye_colour_id = 7;", "code": "import pandas as pd\nmerged = pd.merge(superhero, colour, left_on='eye_colour_id', right_on='id')\nblue_eyes_count = len(merged[merged['colour'] == 'Blue'])\ntotal_count = len(superhero)\npercentage = (blue_eyes_count / total_count) * 100\nresult = percentage", "sql": "SELECT CAST(COUNT(CASE WHEN T2.colour = 'Blue' THEN 1 ELSE NULL END) AS REAL) * 100 / COUNT(T1.id) FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id", "difficulty": "moderate" }, { "question_id": 801, "question": "Find the ratio between male superheroes and female superheroes.", "db_id": "superhero", "evidence": "ratio = DIVIDE(SUM(gender_id = 1) / SUM(gender_id = 2)); male superheroes refers to gender = 'Female'; female superheroes refers to gender = 'Male';male superheroes refers to gender = 'Male'; female superheroes refers to gender = 'Female'; ratio = DIVIDE(COUNT(CASE WHEN gender = 'Male' THEN id END), COUNT(CASE WHEN gender = 'Female' THEN id END))", "code": "import pandas as pd\n\n# Load the necessary tables\ngender_df = pd.read_csv('gender.csv')\nsuperhero_df = pd.read_csv('superhero.csv')\n\n# Merge the superhero DataFrame with the gender DataFrame on gender_id\nmerged_df = pd.merge(superhero_df, gender_df, left_on='gender_id', right_on='id')\n\n# Calculate the count of male and female superheroes\nmale_count = merged_df[merged_df['gender'] == 'Male'].shape[0]\nfemale_count = merged_df[merged_df['gender'] == 'Female'].shape[0]\n\n# Calculate the ratio\nratio = male_count / female_count if female_count != 0 else float('inf')\n\n# Record the final result\nresult = ratio\n\n# Print the final result\nprint(result)", "sql": "SELECT CAST(COUNT(CASE WHEN T2.gender = 'Male' THEN T1.id ELSE NULL END) AS REAL) / COUNT(CASE WHEN T2.gender = 'Female' THEN T1.id ELSE NULL END) FROM superhero AS T1 INNER JOIN gender AS T2 ON T1.gender_id = T2.id", "difficulty": "moderate" }, { "question_id": 802, "question": "Who is the tallest superhero?", "db_id": "superhero", "evidence": "who refers to superhero_name; tallest superhero refers to MAX(height_cm);", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\n\nfiltered_df = df_superhero[df_superhero['height_cm'] > 0]\nsorted_df = filtered_df.sort_values(by='height_cm', ascending=False)\nresult_df = sorted_df[['superhero_name']].head(1)\nresult = result_df.reset_index(drop=True)", "sql": "SELECT superhero_name FROM superhero ORDER BY height_cm DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 803, "question": "What is the power ID of cryokinesis?", "db_id": "superhero", "evidence": "power ID refers to superpower.id; cryokinesis refers to power_name = 'cryokinesis';", "code": "import pandas as pd\n\ndf_superpower = pd.read_csv('superpower.csv')\n\nresult_df = df_superpower[df_superpower['power_name'] == 'Cryokinesis'][['id']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT id FROM superpower WHERE power_name = 'Cryokinesis'", "difficulty": "simple" }, { "question_id": 804, "question": "Provide the name of superhero with superhero ID 294.", "db_id": "superhero", "evidence": "name of superhero refers to superhero_name; superhero ID 294 refers to superhero.id = 294;", "code": "import pandas as pd\nresult = superhero[superhero['id'] == 294][['superhero_name']]", "sql": "SELECT superhero_name FROM superhero WHERE id = 294", "difficulty": "simple" }, { "question_id": 805, "question": "List the full names of superheroes with missing weight.", "db_id": "superhero", "evidence": "missing weight refers to weight_kg = 0 OR weight_kg = NULL;", "code": "import pandas as pd\nresult = superhero[(superhero['full_name'].notna()) & ((superhero['weight_kg'].isna()) | (superhero['weight_kg'] == 0))][['full_name']].drop_duplicates()", "sql": "SELECT DISTINCT full_name FROM superhero WHERE full_name IS NOT NULL AND (weight_kg IS NULL OR weight_kg = 0)", "difficulty": "simple" }, { "question_id": 806, "question": "Provide the eye colour of the superhero who has Karen Beecher-Duncan as their full name.", "db_id": "superhero", "evidence": "eye colour refers to colour.colour where eye_colour_id = colour.id; Karen Beecher-Duncan is the full name of superhero;", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['full_name'] == 'Karen Beecher-Duncan'][['eye_colour_id']], colour, left_on='eye_colour_id', right_on='id')[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.full_name = 'Karen Beecher-Duncan'", "difficulty": "simple" }, { "question_id": 807, "question": "What is the superpowers of the superhero has Helen Parr as their full name?", "db_id": "superhero", "evidence": "superpowers refers to power_name; Helen Parr is the full name of superhero;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_power = pd.read_csv('hero_power.csv')\ndf_superpower = pd.read_csv('superpower.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_power, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_superpower, left_on='power_id', right_on='id')\n\nresult_df = merged_df[merged_df['full_name'] == 'Helen Parr'][['power_name']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.full_name = 'Helen Parr'", "difficulty": "simple" }, { "question_id": 808, "question": "Find the race of the superhero who weighs 108kg and is 188cm tall.", "db_id": "superhero", "evidence": "weighs 108kg refers to weight_kg = 108; 188cm tall refers to height_cm = 188;", "code": "import pandas as pd\nfiltered_heroes = superhero[(superhero['weight_kg'] == 108) & (superhero['height_cm'] == 188)]\nmerged = pd.merge(filtered_heroes, race, left_on='race_id', right_on='id')\nresult = merged[['race']].drop_duplicates()", "sql": "SELECT DISTINCT T2.race FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.weight_kg = 108 AND T1.height_cm = 188", "difficulty": "simple" }, { "question_id": 809, "question": "What is the publisher name of the superhero ID 38?", "db_id": "superhero", "evidence": "superhero ID 38 refers to superhero.id = 38;", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['id'] == 38][['id', 'publisher_id']], publisher, left_on='publisher_id', right_on='id')[['publisher_name']]", "sql": "SELECT T2.publisher_name FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.id = 38", "difficulty": "simple" }, { "question_id": 810, "question": "What is the race of the superhero with maximum attribute value?", "db_id": "superhero", "evidence": "maximum attribute value refers to MAX(attribute_value);", "code": "import pandas as pd\nmerged = pd.merge(superhero, hero_attribute, left_on='id', right_on='hero_id')\nmerged = pd.merge(merged, race, left_on='race_id', right_on='id')\nresult = merged.sort_values('attribute_value', ascending=False).head(1)[['race']]", "sql": "SELECT T3.race FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN race AS T3 ON T1.race_id = T3.id WHERE T2.attribute_value = (SELECT MAX(attribute_value) FROM hero_attribute)", "difficulty": "simple" }, { "question_id": 811, "question": "Give the alignment and superpowers of the superhero named Atom IV.", "db_id": "superhero", "evidence": "superpowers refers to power_name;", "code": "import pandas as pd\n\n# Merge superhero with hero_power\nmerged1 = pd.merge(superhero[superhero['superhero_name'] == 'Atom IV'], hero_power, left_on='id', right_on='hero_id')\n\n# Merge with superpower\nmerged2 = pd.merge(merged1, superpower, left_on='power_id', right_on='id')\n\n# Merge with alignment\nmerged3 = pd.merge(merged2, alignment, left_on='alignment_id', right_on='id')\n\n# Select alignment and power_name columns\nresult = merged3[['alignment', 'power_name']]", "sql": "SELECT T4.alignment, T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T3.id = T2.power_id INNER JOIN alignment AS T4 ON T1.alignment_id = T4.id WHERE T1.superhero_name = 'Atom IV'", "difficulty": "simple" }, { "question_id": 812, "question": "List down at least five full names of superheroes with blue eyes.", "db_id": "superhero", "evidence": "blue eyes refers to colour.colour = 'Blue' WHERE eye_colour_id = colour.id; Name of superheroes refers to superhero_name;", "code": "import pandas as pd\nresult = superhero.merge(colour, left_on='eye_colour_id', right_on='id').query(\"colour == 'Blue'\").full_name.head(5)", "sql": "SELECT T1.full_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T2.colour = 'Blue' LIMIT 5", "difficulty": "simple" }, { "question_id": 813, "question": "Calculate the average attribute value of all neutral superheroes.", "db_id": "superhero", "evidence": "average = AVG(attribute_value); neutral superheroes refers to alignment_id = 3;", "code": "import pandas as pd\n\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\ndf_superhero = pd.read_csv('superhero.csv')\n\ndf_superhero_filtered = df_superhero[df_superhero['alignment_id'] == 3]\nmerged_df = pd.merge(df_hero_attribute, df_superhero_filtered, left_on='hero_id', right_on='id')\nresult = merged_df['attribute_value'].mean()", "sql": "SELECT AVG(T1.attribute_value) FROM hero_attribute AS T1 INNER JOIN superhero AS T2 ON T1.hero_id = T2.id WHERE T2.alignment_id = 3", "difficulty": "simple" }, { "question_id": 814, "question": "List the skin colour of the superheroes with 100 attribute value.", "db_id": "superhero", "evidence": "skin colour refers to colour.colour where skin_colour_id = colour.id; 100 attribute value refers to attribute_value = 100;", "code": "import pandas as pd\nmerged = pd.merge(hero_attribute[hero_attribute['attribute_value'] == 100], superhero, left_on='hero_id', right_on='id')\nmerged = pd.merge(merged, colour, left_on='skin_colour_id', right_on='id')\nresult = merged[['colour']].drop_duplicates()", "sql": "SELECT DISTINCT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.skin_colour_id = T2.id INNER JOIN hero_attribute AS T3 ON T1.id = T3.hero_id WHERE T3.attribute_value = 100", "difficulty": "moderate" }, { "question_id": 815, "question": "Count the good female superheroes.", "db_id": "superhero", "evidence": "good refers to alignment.id = 1; female refers to gender.id = 2;", "code": "import pandas as pd\n\n# Merge superhero with alignment and gender tables\nmerged = pd.merge(superhero, alignment, left_on='alignment_id', right_on='id')\nmerged = pd.merge(merged, gender, left_on='gender_id', right_on='id')\n\n# Filter for good female superheroes\nfiltered = merged[(merged['alignment'] == 'Good') & (merged['gender'] == 'Female')]\n\n# Count the results\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id INNER JOIN gender AS T3 ON T1.gender_id = T3.id WHERE T2.alignment = 'Good' AND T3.gender = 'Female'", "difficulty": "simple" }, { "question_id": 816, "question": "Provide the names of superheroes with attribute value between 75 to 80.", "db_id": "superhero", "evidence": "names of superheroes refers to superhero_name; attribute value between 75 to 80 refers to attribute_value BETWEEN 75 AND 80;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_attribute, left_on='id', right_on='hero_id')\nfiltered_df = merged_df[(merged_df['attribute_value'] >= 75) & (merged_df['attribute_value'] <= 80)]\nresult_df = filtered_df[['superhero_name']].drop_duplicates()\nresult = result_df.reset_index(drop=True)", "sql": "SELECT DISTINCT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id WHERE T2.attribute_value BETWEEN 75 AND 80", "difficulty": "simple" }, { "question_id": 817, "question": "Give the race of the blue-haired male superhero.", "db_id": "superhero", "evidence": "blue-haired refers to colour.colour = 'blue' WHERE hair_colour_id = colour.id; male refers to gender = 'male';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_colour = pd.read_csv('colour.csv')\ndf_race = pd.read_csv('race.csv')\ndf_gender = pd.read_csv('gender.csv')\n\nmerged_df = pd.merge(df_superhero, df_colour, left_on='hair_colour_id', right_on='id', suffixes=('', '_colour'))\nmerged_df = pd.merge(merged_df, df_race, left_on='race_id', right_on='id', suffixes=('', '_race'))\nmerged_df = pd.merge(merged_df, df_gender, left_on='gender_id', right_on='id', suffixes=('', '_gender'))\n\nresult_df = merged_df[(merged_df['colour'] == 'Blue') & (merged_df['gender'] == 'Male')][['race']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T3.race FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.hair_colour_id = T2.id INNER JOIN race AS T3 ON T1.race_id = T3.id INNER JOIN gender AS T4 ON T1.gender_id = T4.id WHERE T2.colour = 'Blue' AND T4.gender = 'Male'", "difficulty": "moderate" }, { "question_id": 818, "question": "Among the bad superheroes, what is the percentage of female superheroes?", "db_id": "superhero", "evidence": "bad superheroes refers to alignment.id = 2; percentage = MULTIPLY(DIVIDE(SUM(gender.id = 2 WHERE alignment.id = 2), COUNT(alignment.id = 2)), 100.0); female refers to gender.id = 2;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_alignment = pd.read_csv('alignment.csv')\ndf_gender = pd.read_csv('gender.csv')\n\nmerged_df = pd.merge(df_superhero, df_alignment, left_on='alignment_id', right_on='id')\nmerged_df = pd.merge(merged_df, df_gender, left_on='gender_id', right_on='id')\n\nbad_superheroes = merged_df[merged_df['alignment_id'] == 2]\ntotal_bad = len(bad_superheroes)\nfemale_bad = len(bad_superheroes[bad_superheroes['gender_id'] == 2])\n\nresult = (female_bad / total_bad) * 100.0 if total_bad > 0 else 0.0", "sql": "SELECT CAST(COUNT(CASE WHEN T3.id = 2 THEN T1.id END) AS REAL) * 100.0 / COUNT(T1.id) FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id INNER JOIN gender AS T3 ON T1.gender_id = T3.id WHERE T2.id = 2", "difficulty": "challenging" }, { "question_id": 819, "question": "In superheroes with missing weight data, calculate the difference between the number of superheroes with blue eyes and no eye color.", "db_id": "superhero", "evidence": "missing weight data refers to weight_kg = 0 OR T1.weight_kg = NULL; difference = SUBTRACT(SUM(colour.id = 7), SUM(colour.id = 1)); blue eyes refers to eye_colour_id WHERE colour.id = 7; no eye color refers to eye_colour_id WHERE colour.id = 1;", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_colour = pd.read_csv('colour.csv')\n\nmerged_df = pd.merge(df_superhero, df_colour, left_on='eye_colour_id', right_on='id')\nfiltered_df = merged_df[(merged_df['weight_kg'] == 0) | (merged_df['weight_kg'].isna())]\n\nblue_eyes_count = len(filtered_df[filtered_df['id_y'] == 7])\nno_eye_color_count = len(filtered_df[filtered_df['id_y'] == 1])\nresult = blue_eyes_count - no_eye_color_count", "sql": "SELECT SUM(CASE WHEN T2.id = 7 THEN 1 ELSE 0 END) - SUM(CASE WHEN T2.id = 1 THEN 1 ELSE 0 END) FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.weight_kg = 0 OR T1.weight_kg is NULL", "difficulty": "challenging" }, { "question_id": 820, "question": "How strong is the Hulk?", "db_id": "superhero", "evidence": "how strong refers to attribute_value WHERE attribute_name = 'Strength'; the Hulk refers to superhero_name = 'Hulk';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\ndf_attribute = pd.read_csv('attribute.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_attribute, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_attribute, left_on='attribute_id', right_on='id')\n\nresult_df = merged_df[(merged_df['superhero_name'] == 'Hulk') & (merged_df['attribute_name'] == 'Strength')][['attribute_value']]\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T2.attribute_value FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T1.superhero_name = 'Hulk' AND T3.attribute_name = 'Strength'", "difficulty": "moderate" }, { "question_id": 821, "question": "List down Ajax's superpowers.", "db_id": "superhero", "evidence": "Ajax refers to superhero_name = 'Ajax'; superpowers refers to power_name;", "code": "import pandas as pd\nmerged = pd.merge(superhero[superhero['superhero_name'] == 'Ajax'], hero_power, left_on='id', right_on='hero_id')\nmerged = pd.merge(merged, superpower, left_on='power_id', right_on='id')\nresult = merged[['power_name']]", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.superhero_name = 'Ajax'", "difficulty": "simple" }, { "question_id": 822, "question": "How many green-skinned villains are there in the superhero universe?", "db_id": "superhero", "evidence": "green-skinned refers to colour.colour = 'Green' WHERE skin_colour_id = colour.id; villains refers to alignment = 'Bad';", "code": "import pandas as pd\n\n# Merge superhero with alignment\nmerged = pd.merge(superhero, alignment, left_on='alignment_id', right_on='id', suffixes=('', '_align'))\n\n# Merge with colour for skin colour\nmerged = pd.merge(merged, colour, left_on='skin_colour_id', right_on='id', suffixes=('', '_skin'))\n\n# Filter for bad alignment and green skin\nfiltered = merged[(merged['alignment'] == 'Bad') & (merged['colour'] == 'Green')]\n\n# Count the number of green-skinned villains\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id INNER JOIN colour AS T3 ON T1.skin_colour_id = T3.id WHERE T2.alignment = 'Bad' AND T3.colour = 'Green'", "difficulty": "moderate" }, { "question_id": 823, "question": "How many female superheroes are in Marvel Comics?", "db_id": "superhero", "evidence": "female refers to gender = 'Female'; Marvel Comics refers to publisher_name = 'Marvel Comics';", "code": "import pandas as pd\nimport numpy as np\n\n# Merge superhero with publisher\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id', suffixes=('', '_pub'))\n\n# Merge with gender\nmerged = pd.merge(merged, gender, left_on='gender_id', right_on='id', suffixes=('', '_gen'))\n\n# Filter for Marvel Comics and Female\nfiltered = merged[(merged['publisher_name'] == 'Marvel Comics') & (merged['gender'] == 'Female')]\n\n# Count the number of female Marvel superheroes\nresult = len(filtered)", "sql": "SELECT COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN gender AS T3 ON T1.gender_id = T3.id WHERE T2.publisher_name = 'Marvel Comics' AND T3.gender = 'Female'", "difficulty": "moderate" }, { "question_id": 824, "question": "Identify superheroes who can control wind and list their names in alphabetical order.", "db_id": "superhero", "evidence": "superheroes refers to superhero_name; can control wind refers to power_name = 'Wind Control';", "code": "import pandas as pd\nimport numpy as np\n\n# Merge superhero with hero_power\nmerged1 = pd.merge(superhero, hero_power, left_on='id', right_on='hero_id')\n\n# Merge with superpower\nmerged2 = pd.merge(merged1, superpower, left_on='power_id', right_on='id')\n\n# Filter for Wind Control power\nwind_control = merged2[merged2['power_name'] == 'Wind Control']\n\n# Select superhero names and sort alphabetically\nresult = wind_control[['superhero_name']].drop_duplicates().sort_values('superhero_name').reset_index(drop=True)", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T3.power_name = 'Wind Control' ORDER BY T1.superhero_name", "difficulty": "moderate" }, { "question_id": 825, "question": "Identify the gender of the superhero who has the ability of Phoenix Force.", "db_id": "superhero", "evidence": "ability of Phoenix Force refers to power_name = 'Phoenix Force';", "code": "import pandas as pd\nmerged = pd.merge(superhero, hero_power, left_on='id', right_on='hero_id')\nmerged = pd.merge(merged, superpower, left_on='power_id', right_on='id')\nmerged = pd.merge(merged, gender, left_on='gender_id', right_on='id', suffixes=('', '_gender'))\nfiltered = merged[merged['power_name'] == 'Phoenix Force']\nresult = filtered[['gender']]", "sql": "SELECT T4.gender FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id INNER JOIN gender AS T4 ON T1.gender_id = T4.id WHERE T3.power_name = 'Phoenix Force'", "difficulty": "moderate" }, { "question_id": 826, "question": "Identify the heaviest superhero in DC Comics.", "db_id": "superhero", "evidence": "heaviest refers to MAX(weight_kg); DC Comics refers to publisher_name = 'DC Comics'; superhero refers to superhero_name;", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\ndc_heroes = merged[merged['publisher_name'] == 'DC Comics']\nresult = dc_heroes.sort_values('weight_kg', ascending=False).head(1)[['superhero_name']]", "sql": "SELECT T1.superhero_name FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T2.publisher_name = 'DC Comics' ORDER BY T1.weight_kg DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 827, "question": "What is the average height of a non-human superhero in Dark Horse Comics?", "db_id": "superhero", "evidence": "average = AVG(height_cm); non-human superhero refers to race <> 'Human'; Dark Horse Comics refers to publisher_name = 'Dark Horse Comics';", "code": "import pandas as pd\n\n# Merge superhero with publisher\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\n\n# Merge with race\nmerged = pd.merge(merged, race, left_on='race_id', right_on='id')\n\n# Filter for Dark Horse Comics and non-human\nfiltered = merged[(merged['publisher_name'] == 'Dark Horse Comics') & (merged['race'] != 'Human')]\n\n# Calculate average height\nresult = filtered['height_cm'].mean()", "sql": "SELECT AVG(T1.height_cm) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN race AS T3 ON T1.race_id = T3.id WHERE T2.publisher_name = 'Dark Horse Comics' AND T3.race != 'Human'", "difficulty": "moderate" }, { "question_id": 828, "question": "Count the fastest superheroes.", "db_id": "superhero", "evidence": "fastest refers to attribute_value = 100 WHERE attribute_name = 'Speed';", "code": "import pandas as pd\nmerged = pd.merge(hero_attribute, attribute, left_on='attribute_id', right_on='id')\nmerged = pd.merge(merged, superhero, left_on='hero_id', right_on='id')\nfiltered = merged[(merged['attribute_name'] == 'Speed') & (merged['attribute_value'] == 100)]\nresult = len(filtered['superhero_name'])", "sql": "SELECT COUNT(T3.superhero_name) FROM hero_attribute AS T1 INNER JOIN attribute AS T2 ON T1.attribute_id = T2.id INNER JOIN superhero AS T3 ON T1.hero_id = T3.id WHERE T2.attribute_name = 'Speed' AND T1.attribute_value = 100", "difficulty": "simple" }, { "question_id": 829, "question": "Which publisher created more superheroes: DC or Marvel Comics? Find the difference in the number of superheroes.", "db_id": "superhero", "evidence": "DC refers to publisher_name = 'DC Comics'; Marvel Comics refers to publisher_name = 'Marvel Comics'; difference = SUBTRACT(SUM(publisher_name = 'DC Comics'), SUM(publisher_name = 'Marvel Comics'));", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\ndc_count = len(merged[merged['publisher_name'] == 'DC Comics'])\nmarvel_count = len(merged[merged['publisher_name'] == 'Marvel Comics'])\nresult = dc_count - marvel_count", "sql": "SELECT SUM(CASE WHEN T2.publisher_name = 'DC Comics' THEN 1 ELSE 0 END) - SUM(CASE WHEN T2.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id", "difficulty": "challenging" }, { "question_id": 830, "question": "Identify the weakest attribute of the Black Panther.", "db_id": "superhero", "evidence": "weakest attribute refers to attribute_name WHERE MIN(attribute_value); Black Panther refers to superhero_name = 'Black Panther';", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\ndf_attribute = pd.read_csv('attribute.csv')\n\nmerged_df = pd.merge(df_superhero, df_hero_attribute, left_on='id', right_on='hero_id')\nmerged_df = pd.merge(merged_df, df_attribute, left_on='attribute_id', right_on='id')\n\nfiltered_df = merged_df[merged_df['superhero_name'] == 'Black Panther']\nsorted_df = filtered_df.sort_values(by='attribute_value', ascending=True)\nresult_df = sorted_df[['attribute_name']].head(1)\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T3.attribute_name FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id INNER JOIN attribute AS T3 ON T2.attribute_id = T3.id WHERE T1.superhero_name = 'Black Panther' ORDER BY T2.attribute_value ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 831, "question": "What is Abomination's eye colour?", "db_id": "superhero", "evidence": "Abomination refers to superhero_name = 'Abomination'; eye colour refers to colour.colour where eye_colour_id = colour.id;", "code": "import pandas as pd\nfiltered_superhero = superhero[superhero['superhero_name'] == 'Abomination']\nmerged = pd.merge(filtered_superhero, colour, left_on='eye_colour_id', right_on='id')\nresult = merged[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.superhero_name = 'Abomination'", "difficulty": "simple" }, { "question_id": 832, "question": "Name the tallest superhero.", "db_id": "superhero", "evidence": "tallest superhero refers to MAX(height_cm);", "code": "import pandas as pd\n\ndf_superhero = pd.read_csv('superhero.csv')\n\nfiltered_df = df_superhero[df_superhero['height_cm'] > 0]\nsorted_df = filtered_df.sort_values(by='height_cm', ascending=False)\nresult_df = sorted_df[['superhero_name']].head(1)\nresult = result_df.reset_index(drop=True)", "sql": "SELECT superhero_name FROM superhero ORDER BY height_cm DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 833, "question": "Name the superhero, otherwise known as Charles Chandler.", "db_id": "superhero", "evidence": "name the superhero refers to superhero_name; Charles Chandler is the full name of superhero;", "code": "import pandas as pd\nresult = superhero[superhero['full_name'] == 'Charles Chandler']['superhero_name']", "sql": "SELECT superhero_name FROM superhero WHERE full_name = 'Charles Chandler'", "difficulty": "simple" }, { "question_id": 834, "question": "Among all superheroes created by George Lucas, identify the percentage of female superheroes.", "db_id": "superhero", "evidence": "created by George Lucas refers to publisher_name = 'George Lucas'; percentage = MULTIPLY(DIVIDE(SUM(gender = 'Female' WHERE publisher_name = 'George Lucas'), COUNT(publisher_name = 'George Lucas')), 100.0); female refers to gender = 'Female';", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nmerged = pd.merge(merged, gender, left_on='gender_id', right_on='id')\ngeorge_lucas_heroes = merged[merged['publisher_name'] == 'George Lucas']\nfemale_count = len(george_lucas_heroes[george_lucas_heroes['gender'] == 'Female'])\ntotal_count = len(george_lucas_heroes)\nresult = (female_count / total_count) * 100 if total_count > 0 else 0", "sql": "SELECT CAST(COUNT(CASE WHEN T3.gender = 'Female' THEN 1 ELSE NULL END) AS REAL) * 100 / COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN gender AS T3 ON T1.gender_id = T3.id WHERE T2.publisher_name = 'George Lucas'", "difficulty": "challenging" }, { "question_id": 835, "question": "Among all superheroes in Marvel Comics, identify the percentage of 'good' superheroes.", "db_id": "superhero", "evidence": "Marvel Comics refers to publisher_name = 'Marvel Comics'; percentage = MULTIPLY(DIVIDE(SUM(alignment = 'Good' WHERE publisher_name = 'Marvel Comics'), COUNT(publisher_name = 'Marvel Comics')), 100.0); good superheroes refers to alignment = 'Good';", "code": "import pandas as pd\nmerged = pd.merge(superhero, publisher, left_on='publisher_id', right_on='id')\nmerged = pd.merge(merged, alignment, left_on='alignment_id', right_on='id')\nmarvel_heroes = merged[merged['publisher_name'] == 'Marvel Comics']\ngood_heroes_count = len(marvel_heroes[marvel_heroes['alignment'] == 'Good'])\ntotal_marvel_count = len(marvel_heroes)\nresult = (good_heroes_count / total_marvel_count) * 100", "sql": "SELECT CAST(COUNT(CASE WHEN T3.alignment = 'Good' THEN T1.id ELSE NULL END) AS REAL) * 100 / COUNT(T1.id) FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id INNER JOIN alignment AS T3 ON T1.alignment_id = T3.id WHERE T2.publisher_name = 'Marvel Comics'", "difficulty": "challenging" }, { "question_id": 836, "question": "What is the total number of superheroes that have John as their first name?", "db_id": "superhero", "evidence": "have John as their first name refers to full_name LIKE 'John%';", "code": "import pandas as pd\nresult = superhero[superhero['full_name'].str.startswith('John', na=False)]['id'].count()", "sql": "SELECT COUNT(id) FROM superhero WHERE full_name LIKE 'John%'", "difficulty": "simple" }, { "question_id": 837, "question": "Give the hero ID of superhero with the lowest attribute value.", "db_id": "superhero", "evidence": "lowest attribute value refers to MIN(attribute_value);", "code": "import pandas as pd\n\ndf_hero_attribute = pd.read_csv('hero_attribute.csv')\n\nmin_attribute_value = df_hero_attribute['attribute_value'].min()\nresult_df = df_hero_attribute[df_hero_attribute['attribute_value'] == min_attribute_value][['hero_id']].drop_duplicates()\nresult = result_df.reset_index(drop=True)", "sql": "SELECT hero_id FROM hero_attribute WHERE attribute_value = (SELECT MIN(attribute_value) FROM hero_attribute)", "difficulty": "simple" }, { "question_id": 838, "question": "Provide the full name of the superhero named Alien.", "db_id": "superhero", "evidence": "", "code": "import pandas as pd\nresult = superhero[superhero['superhero_name'] == 'Alien'][['full_name']]", "sql": "SELECT full_name FROM superhero WHERE superhero_name = 'Alien'", "difficulty": "simple" }, { "question_id": 839, "question": "In superheroes with weight less than 100, list the full name of the superheroes with brown eyes.", "db_id": "superhero", "evidence": "weight_kg is less than 100 in the database;", "code": "import pandas as pd\nfiltered_heroes = superhero[superhero['weight_kg'] < 100]\nmerged = pd.merge(filtered_heroes, colour, left_on='eye_colour_id', right_on='id')\nresult = merged[merged['colour'] == 'Brown'][['full_name']]", "sql": "SELECT T1.full_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.weight_kg < 100 AND T2.colour = 'Brown'", "difficulty": "simple" }, { "question_id": 840, "question": "List the attribute value of the superhero named Aquababy.", "db_id": "superhero", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(superhero[superhero['superhero_name'] == 'Aquababy'], hero_attribute, left_on='id', right_on='hero_id')\nresult = merged['attribute_value']", "sql": "SELECT T2.attribute_value FROM superhero AS T1 INNER JOIN hero_attribute AS T2 ON T1.id = T2.hero_id WHERE T1.superhero_name = 'Aquababy'", "difficulty": "simple" }, { "question_id": 841, "question": "Provide the weight and race of the superhero with superhero ID 40.", "db_id": "superhero", "evidence": "weight refers to weight_kg; superhero ID 40 refers to superhero.id = 40;", "code": "import pandas as pd\nfiltered_superhero = superhero[superhero['id'] == 40]\nmerged = pd.merge(filtered_superhero, race, left_on='race_id', right_on='id')\nresult = merged[['weight_kg', 'race']]", "sql": "SELECT T1.weight_kg, T2.race FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.id = 40", "difficulty": "simple" }, { "question_id": 842, "question": "Calculate the average height of all neutral superheroes.", "db_id": "superhero", "evidence": "", "code": "import pandas as pd\nimport numpy as np\nmerged = pd.merge(superhero, alignment, left_on='alignment_id', right_on='id')\nneutral_heroes = merged[merged['alignment'] == 'Neutral']\nresult = neutral_heroes['height_cm'].mean()", "sql": "SELECT AVG(T1.height_cm) FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id WHERE T2.alignment = 'Neutral'", "difficulty": "simple" }, { "question_id": 843, "question": "List the hero ID of superheroes have intellegence as their power.", "db_id": "superhero", "evidence": "hero ID refers to superhero.id; have intelligence as their power refers to power_name = 'Intelligence';", "code": "import pandas as pd\nresult = pd.merge(hero_power, superpower, left_on='power_id', right_on='id')[lambda x: x['power_name'] == 'Intelligence'][['hero_id']]", "sql": "SELECT T1.hero_id FROM hero_power AS T1 INNER JOIN superpower AS T2 ON T1.power_id = T2.id WHERE T2.power_name = 'Intelligence'", "difficulty": "simple" }, { "question_id": 844, "question": "Give the eye colour of Blackwulf.", "db_id": "superhero", "evidence": "eye colour refers to colour.colour where eye_colour_id = colour.id; Blackwulf refers to superhero_name = 'Blackwulf';", "code": "import pandas as pd\nresult = pd.merge(superhero[superhero['superhero_name'] == 'Blackwulf'], colour, left_on='eye_colour_id', right_on='id')[['colour']]", "sql": "SELECT T2.colour FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.superhero_name = 'Blackwulf'", "difficulty": "simple" }, { "question_id": 845, "question": "List the power of superheroes with height greater than 80% of the average height of all superheroes.", "db_id": "superhero", "evidence": "power of superheroes refers to power_name; height greater than 80% of the average height of all superheroes = height_cm > MULTIPLY(AVG(height_cm), 0.8);", "code": "import pandas as pd\\n\\ndf_superhero = pd.read_csv('superhero.csv')\\ndf_hero_power = pd.read_csv('hero_power.csv')\\ndf_superpower = pd.read_csv('superpower.csv')\\n\\navg_height = df_superhero['height_cm'].mean()\\nthreshold = avg_height * 0.8\\n\\nfiltered_heroes = df_superhero[df_superhero['height_cm'] > threshold]\\n\\nmerged_1 = pd.merge(filtered_heroes, df_hero_power, left_on='id', right_on='hero_id')\\nmerged_2 = pd.merge(merged_1, df_superpower, left_on='power_id', right_on='id')\\n\\nresult = merged_2[['power_name']].dropna().reset_index(drop=True)", "sql": "SELECT T3.power_name FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T1.height_cm > ( SELECT AVG(height_cm) FROM superhero ) * 0.8", "difficulty": "moderate" }, { "question_id": 846, "question": "Please list the reference names of the drivers who are eliminated in the first period in race number 20.", "db_id": "formula_1", "evidence": "driver reference name refers to driverRef; first qualifying period refers to q1; drivers who are eliminated in the first qualifying period refers to 5 drivers with MAX(q1); race number refers to raceId;", "code": "import pandas as pd\n\ndf_qualifying = pd.read_csv('qualifying.csv')\ndf_drivers = pd.read_csv('drivers.csv')\n\nmerged_df = pd.merge(df_qualifying, df_drivers, on='driverId')\nfiltered_df = merged_df[merged_df['raceId'] == 20]\nsorted_df = filtered_df.sort_values(by='q1', ascending=False)\nresult_df = sorted_df[['driverRef']].head(5)\nresult = result_df.reset_index(drop=True)", "sql": "SELECT T2.driverRef FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 20 ORDER BY T1.q1 DESC LIMIT 5", "difficulty": "moderate" }, { "question_id": 847, "question": "What is the surname of the driver with the best lap time in race number 19 in the second qualifying period?", "db_id": "formula_1", "evidence": "race number refers to raceId; second qualifying period refers to q2; best lap time refers to MIN(q2);", "code": "import pandas as pd\nmerged = pd.merge(qualifying[qualifying['raceId'] == 19], drivers, left_on='driverId', right_on='driverId')\nmerged = merged.dropna(subset=['q2'])\nmerged = merged.sort_values('q2')\nresult = merged.iloc[0]['surname']", "sql": "SELECT T2.surname FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 19 ORDER BY T1.q2 ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 848, "question": "Please list the year during which the race is held on circuits in Shanghai.", "db_id": "formula_1", "evidence": "Shanghai is a name of location;", "code": "import pandas as pd\nmerged = pd.merge(races, circuits, left_on='circuitId', right_on='circuitId')\nfiltered = merged[merged['location'] == 'Shanghai']\nresult = filtered[['year']]", "sql": "SELECT T2.year FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitID = T1.circuitId WHERE T1.location = 'Shanghai'", "difficulty": "simple" }, { "question_id": 849, "question": "Where can the introduction of the races held on Circuit de Barcelona-Catalunya be found?", "db_id": "formula_1", "evidence": "introduction of races refers to url; Circuit de Barcelona-Catalunya is a name of circuit;", "code": "import pandas as pd\\n# 读取数据\\ncircuits = pd.read_csv('circuits.csv')\\nraces = pd.read_csv('races.csv')\\n# 过滤出名为 'Circuit de Barcelona-Catalunya' 的赛道记录\\ncircuits_filtered = circuits[circuits['name'] == 'Circuit de Barcelona-Catalunya']\\n# 获取与这些赛道相关的比赛URL并去重\\nresult = races[races['circuitId'].isin(circuits_filtered['circuitId'])][['url']].drop_duplicates()\\n# 输出结果\\nprint(result)", "sql": "SELECT DISTINCT T2.url FROM circuits AS T1 INNER JOIN races AS T2 ON T1.circuitId = T2.circuitId WHERE T1.name = 'Circuit de Barcelona-Catalunya'", "difficulty": "simple" }, { "question_id": 850, "question": "Please give the name of the race held on the circuits in Germany.", "db_id": "formula_1", "evidence": "Germany is a name of country;", "code": "import pandas as pd\nmerged = pd.merge(circuits, races, on='circuitId')\nfiltered = merged[merged['country'] == 'Germany']\nresult = filtered[['name_y']].drop_duplicates().rename(columns={'name_y': 'name'})", "sql": "SELECT DISTINCT races.name FROM circuits INNER JOIN races ON circuits.circuitId = races.circuitId WHERE circuits.country = 'Germany'", "difficulty": "simple" }, { "question_id": 851, "question": "Please list the positions of the circuits built by the constructor Renault.", "db_id": "formula_1", "evidence": "Renault is a name of constructor;", "code": "import pandas as pd\n\nconstructorStandings_df = pd.read_csv('constructorStandings.csv')\nconstructors_df = pd.read_csv('constructors.csv')\n\nmerged_df = pd.merge(constructorStandings_df, constructors_df, on='constructorId')\nfiltered_df = merged_df[merged_df['name'] == 'Renault']\n\nresult = filtered_df[['position']].drop_duplicates().reset_index(drop=True)", "sql": "SELECT DISTINCT T1.position FROM constructorStandings AS T1 INNER JOIN constructors AS T2 ON T2.constructorId = T1.constructorId WHERE T2.name = 'Renault'", "difficulty": "simple" }, { "question_id": 852, "question": "How many races in the year 2010 are held on grand prixs outside Asia and Europe?", "db_id": "formula_1", "evidence": "country in the circuits table refers to the geographical continent classification; 'Bahrain', 'China', 'Singapore', 'Japan', 'Korea', 'Turkey', 'UAE', 'Malaysia' refer to Asian countries; 'Spain', 'Monaco', 'Azerbaijan', 'Austria', 'Belgium', 'France', 'Germany', 'Hungary', 'Italy', 'UK' refer to European countries", "code": "import pandas as pd\nmerged = pd.merge(circuits, races, on='circuitId')\nasia_eu_countries = ['Bahrain','China','Singapore','Japan','Korea','Turkey','UAE','Malaysia','Spain','Monaco','Azerbaijan','Austria','Belgium','France','Germany','Hungary','Italy','UK']\nfiltered = merged[(merged['year'] == 2010) & (~merged['country'].isin(asia_eu_countries))]\nresult = len(filtered)", "sql": "SELECT COUNT(races.raceId) FROM circuits INNER JOIN races ON circuits.circuitId = races.circuitId WHERE races.year = 2010 AND circuits.country NOT IN ('Bahrain','China','Singapore','Japan','Korea','Turkey','UAE','Malaysia','Spain','Monaco','Azerbaijan','Austria','Belgium','France','Germany','Hungary','Italy','UK')", "difficulty": "moderate" }, { "question_id": 853, "question": "Please give the names of the races held on the circuits in Spain.", "db_id": "formula_1", "evidence": "Spain is a name of country;", "code": "import pandas as pd\nmerged = pd.merge(circuits, races, on='circuitId')\nfiltered = merged[merged['country'] == 'Spain']\nresult = filtered[['name_y']].drop_duplicates().rename(columns={'name_y': 'name'})", "sql": "SELECT DISTINCT races.name FROM circuits INNER JOIN races ON circuits.circuitId = races.circuitId WHERE circuits.country = 'Spain'", "difficulty": "simple" }, { "question_id": 854, "question": "What is the coordinates location of the circuits for Australian grand prix?", "db_id": "formula_1", "evidence": "coordinate position/location refers to lat, lng; circuits for Australian grand prix refers to races.name = 'Australian Grand Prix'", "code": "import pandas as pd\nraces_australian = races[races['name'] == 'Australian Grand Prix']\nmerged = pd.merge(races_australian, circuits, on='circuitId')\nresult = merged[['lat', 'lng']].drop_duplicates()", "sql": "SELECT DISTINCT T1.lat, T1.lng FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T2.name = 'Australian Grand Prix';", "difficulty": "simple" }, { "question_id": 855, "question": "Where can I find the information about the races held on Sepang International Circuit?", "db_id": "formula_1", "evidence": "information about races refers to url;", "code": "import pandas as pd\nmerged = pd.merge(circuits, races, left_on='circuitId', right_on='circuitId')\nfiltered = merged[merged['name_x'] == 'Sepang International Circuit']\nresult = filtered['url_y'].drop_duplicates()", "sql": "SELECT DISTINCT T2.url FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.name = 'Sepang International Circuit'", "difficulty": "simple" }, { "question_id": 856, "question": "Please list the time of the races held on Sepang International Circuit.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\ncircuits = pd.read_csv('circuits.csv')\nraces = pd.read_csv('races.csv')\nmerged_df = pd.merge(races, circuits, left_on='circuitId', right_on='circuitId')\nfiltered_df = merged_df[merged_df['name_y'] == 'Sepang International Circuit'][['time']]\nresult = filtered_df.drop_duplicates().reset_index(drop=True)\nprint(result)", "sql": "SELECT DISTINCT T2.time FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.name = 'Sepang International Circuit'", "difficulty": "simple" }, { "question_id": 857, "question": "Give the coordinate position for Abu Dhabi Grand Prix.", "db_id": "formula_1", "evidence": "coordinate position/location refers to lat, lng; Abu Dhabi Grand Prix refers to races.name = 'Abu Dhabi Grand Prix'", "code": "import pandas as pd\nimport numpy as np\n\n# 筛选Abu Dhabi Grand Prix的比赛\nabu_dhabi_races = races[races['name'] == 'Abu Dhabi Grand Prix']\n\n# 将races和circuits表连接\nmerged = pd.merge(abu_dhabi_races, circuits, on='circuitId')\n\n# 选择坐标位置并去重\nresult = merged[['lat', 'lng']].drop_duplicates()", "sql": "SELECT DISTINCT circuits.lat, circuits.lng FROM circuits INNER JOIN races ON races.circuitId = circuits.circuitId WHERE races.name = 'Abu Dhabi Grand Prix'", "difficulty": "simple" }, { "question_id": 858, "question": "Which country is the constructor which got 1 point in the race No. 24 from?", "db_id": "formula_1", "evidence": "race number refers to raceId;", "code": "import pandas as pd\nmerged = pd.merge(constructorResults[constructorResults['raceId'] == 24], constructors, on='constructorId')\nresult = merged[merged['points'] == 1][['nationality']]", "sql": "SELECT T2.nationality FROM constructorResults AS T1 INNER JOIN constructors AS T2 ON T2.constructorId = T1.constructorId WHERE T1.raceId = 24 AND T1.points = 1;", "difficulty": "simple" }, { "question_id": 859, "question": "What's Bruno Senna's Q1 result in the qualifying race No. 354?", "db_id": "formula_1", "evidence": "race number refers to raceId; Bruno Senna refers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname;", "code": "import pandas as pd\nmerged = pd.merge(qualifying, drivers, on='driverId')\nfiltered = merged[(merged['raceId'] == 354) & (merged['forename'] == 'Bruno') & (merged['surname'] == 'Senna')]\nresult = filtered['q1'].values[0] if len(filtered) > 0 else None", "sql": "SELECT T1.q1 FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 354 AND T2.forename = 'Bruno' AND T2.surname = 'Senna'", "difficulty": "simple" }, { "question_id": 860, "question": "For the driver who had the Q2 time as 0:01:40 in the qualifying race No. 355, what is his nationality?", "db_id": "formula_1", "evidence": "race number refers to raceId;", "code": "import pandas as pd\\n\\n# 读取数据表为 DataFrame\\nqualifying = pd.read_csv('qualifying.csv')\\ndrivers = pd.read_csv('drivers.csv')\\n\\n# 筛选出 raceId 为 355 且 Q2 时间以 '1:40' 开头的记录\\nfiltered_qualifying = qualifying[qualifying['raceId'] == 355]\\nfiltered_qualifying = filtered_qualifying[filtered_qualifying['q2'].astype(str).str.startswith('1:40')]\\n\\n# 使用 driverId 进行 JOIN 操作\\nmerged_data = pd.merge(filtered_qualifying, drivers, on='driverId')\\n\\n# 选择所需的列:nationality\\nresult = merged_data[['nationality']].drop_duplicates()\\n\\n# 输出结果\\nprint(result)", "sql": "SELECT DISTINCT T2.nationality FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 355 AND T1.q2 LIKE '1:40%'", "difficulty": "simple" }, { "question_id": 861, "question": "What is his number of the driver who finished 0:01:54 in the Q3 of qualifying race No.903?", "db_id": "formula_1", "evidence": "race number refers to raceId; finished 0:0M:SS in the Q3 refers to q3 LIKE 'M:SS%'", "code": "import pandas as pd\\n\\n# 读取数据\\nqualifying_df = pd.read_csv('qualifying.csv')\\ndrivers_df = pd.read_csv('drivers.csv')\\n\\n# 筛选raceId为903且q3时间匹配的数据\\nfiltered_qualifying = qualifying_df.query('raceId == 903 and q3.str.startswith(\"1:54\")')\\n\\n# 合并筛选后的数据与司机信息\\nmerged_df = pd.merge(filtered_qualifying, drivers_df, left_on='driverId', right_on='driverId')\\n\\n# 获取符合条件的司机号码\\nresult = merged_df[['number_y']]\\n", "sql": "SELECT T2.number FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 903 AND T1.q3 LIKE '1:54%'", "difficulty": "simple" }, { "question_id": 862, "question": "For the Bahrain Grand Prix in 2007, how many drivers not finished the game?", "db_id": "formula_1", "evidence": "Bahrain Grand Prix refers to races.name = 'Bahrain Grand Prix'; drivers who finished the race refers to time is not empty (i.e. time IS NOT NULL);", "code": "import pandas as pd\n\n# Load the necessary tables\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# Filter for the Bahrain Grand Prix in 2007\nbahrain_2007_race = races[(races['name'] == 'Bahrain Grand Prix') & (races['year'] == 2007)]\n\n# Get the raceId for Bahrain Grand Prix in 2007\nrace_id = bahrain_2007_race['raceId'].values[0]\n\n# Filter results for the specific race\nrace_results = results[results['raceId'] == race_id]\n\n# Count drivers who did not finish the race (time is empty)\ndrivers_not_finished = race_results[race_results['time'].isnull()]\n\n# Count the number of such drivers\nresult = len(drivers_not_finished)\n\nprint(result)", "sql": "SELECT COUNT(T3.driverId) FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T1.year = 2007 AND T1.name = 'Bahrain Grand Prix' AND T2.time IS NULL", "difficulty": "simple" }, { "question_id": 863, "question": "Show me the season page of year when the race No. 901 took place.", "db_id": "formula_1", "evidence": "race number refers to raceId;", "code": "import pandas as pd\n\nraces = pd.read_csv('races.csv')\nseasons = pd.read_csv('seasons.csv')\n\n# 合并表\n# 注意:两个表都有 'url' 列,合并后 races 的变为 url_x,seasons 的变为 url_y\nmerged = pd.merge(races, seasons, on='year')\n\n# 筛选 raceId 为 901 的行 (SQL: WHERE T1.raceId = 901)\nfiltered = merged[merged['raceId'] == 901]\n\n# 选择 seasons 表的 url (SQL: SELECT T2.url)\n# 对应 merged 中的 url_y,将其重命名为 url 以匹配输出\nresult = filtered[['url_y']].rename(columns={'url_y': 'url'})\n\nprint(result)", "sql": "SELECT T2.url FROM races AS T1 INNER JOIN seasons AS T2 ON T2.year = T1.year WHERE T1.raceId = 901", "difficulty": "simple" }, { "question_id": 864, "question": "For the race happened on 2015/11/29, how many drivers finished the game?", "db_id": "formula_1", "evidence": "game and race are synonyms; drivers who finished the race should have record in time;", "code": "import pandas as pd\n\n# Read necessary tables\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# Filter races for the specific date\nrace_2015_11_29 = races[races['date'] == '2015-11-29']\n\n# Get the raceId for the specific race\nrace_id = race_2015_11_29['raceId'].values[0]\n\n# Filter results for the specific race where drivers finished the race (time is not NaN)\nfinished_drivers = results[(results['raceId'] == race_id) & results['time'].notna()]\n\n# Count the number of unique drivers who finished the race\nresult = finished_drivers['driverId'].nunique()\n\nprint(result)", "sql": "SELECT COUNT(T2.driverId) FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId WHERE T1.date = '2015-11-29' AND T2.time IS NOT NULL", "difficulty": "simple" }, { "question_id": 865, "question": "For all the drivers who finished the game in race No. 592, who is the oldest?", "db_id": "formula_1", "evidence": "drivers who finished the race refers to time is not empty (i.e. time IS NOT NULL); race number refers to raceId; date of birth refers to drivers.dob; The larger the birthday value, the younger the person is, and vice versa;", "code": "import pandas as pd\n\n# Merge drivers and results tables\nmerged = pd.merge(results[results['raceId'] == 592], drivers, on='driverId')\n\n# Filter for drivers who finished (time is not null) and have dob\nfinished = merged[(merged['time'].notna()) & (merged['dob'].notna())]\n\n# Sort by dob ascending (oldest first) and get the first row\noldest = finished.sort_values('dob').iloc[0]\n\n# Get forename and surname\nresult = pd.DataFrame([{'forename': oldest['forename'], 'surname': oldest['surname']}])", "sql": "SELECT T1.forename, T1.surname FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T2.raceId = 592 AND T2.time IS NOT NULL AND T1.dob IS NOT NULL ORDER BY T1.dob ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 866, "question": "Who was the player that got the lap time of 0:01:27 in the race No. 161? Show his introduction website.", "db_id": "formula_1", "evidence": "player and driver are synonyms; the lap time of 0:0M:SS refers to lapTime.time LIKE 'M:SS%';race number refers to raceId; introduction website of the drivers refers to url;", "code": "import pandas as pd\\n\\n# 假设lapTimes和drivers数据已经加载为DataFrame\\n# lapTimes = pd.read_csv('path_to_lapTimes.csv')\\n# drivers = pd.read_csv('path_to_drivers.csv')\\n\\n# 使用pandas进行数据处理,实现与参考SQL等效的操作\\n# 1. 筛选raceId为161且time为'1:27%'的记录\\ndf_lap_times_filtered = lapTimes.query('raceId == 161 & time.str.startswith(\"1:27\")')\\n\\n# 2. 通过driverId将lapTimes表和drivers表连接起来\\ndf_joined = pd.merge(df_lap_times_filtered, drivers, left_on='driverId', right_on='driverId')\\n\\n# 3. 选择需要的列:forename, surname, url\\nresult = df_joined[['forename', 'surname', 'url']].drop_duplicates()\\n\\n# 输出结果\\nprint(result)", "sql": "SELECT DISTINCT T2.forename, T2.surname, T2.url FROM lapTimes AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 161 AND T1.time LIKE '1:27%'", "difficulty": "moderate" }, { "question_id": 867, "question": "For the driver who set the fastest lap speed in race No.933, where does he come from?", "db_id": "formula_1", "evidence": "fastest lap speed refers to MAX(fastestLapSpeed);", "code": "import pandas as pd\nmerged = pd.merge(results[results['raceId'] == 933], drivers, left_on='driverId', right_on='driverId')\nfiltered = merged[merged['fastestLapTime'].notna()]\nresult = filtered.sort_values('fastestLapSpeed', ascending=False).head(1)[['nationality']]", "sql": "SELECT T1.nationality FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T2.raceId = 933 AND T2.fastestLapTime IS NOT NULL ORDER BY T2.fastestLapSpeed DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 868, "question": "Where is Malaysian Grand Prix held? Give the location coordinates.", "db_id": "formula_1", "evidence": "location coordinates refers to (lat, lng); Malaysian Grand Prix refers to races.name = 'Malaysian Grand Prix'", "code": "import pandas as pd\nmalaysia_races = races[races['name'] == 'Malaysian Grand Prix']\njoined = pd.merge(malaysia_races, circuits, on='circuitId')\nresult = joined[['lat', 'lng']].drop_duplicates()", "sql": "SELECT DISTINCT T1.lat, T1.lng FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T2.name = 'Malaysian Grand Prix';", "difficulty": "simple" }, { "question_id": 869, "question": "For the constructor which got the highest point in the race No. 9 , what is its introduction website?", "db_id": "formula_1", "evidence": "race number refers to raceId; constructor which got the highest point refers to MAX(constructorResults.points); introduction website of the constructor refers to url;", "code": "import pandas as pd\nmerged = pd.merge(constructorResults[constructorResults['raceId'] == 9], constructors, on='constructorId')\nresult = merged.nlargest(1, 'points')[['url']]", "sql": "SELECT T2.url FROM constructorResults AS T1 INNER JOIN constructors AS T2 ON T2.constructorId = T1.constructorId WHERE T1.raceId = 9 ORDER BY T1.points DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 870, "question": "What's Lucas di Grassi's Q1 result in the race No. 345?", "db_id": "formula_1", "evidence": "race number refers to raceId;", "code": "import pandas as pd\nmerged = pd.merge(qualifying, drivers, on='driverId')\nfiltered = merged[(merged['raceId'] == 345) & (merged['forename'] == 'Lucas') & (merged['surname'] == 'di Grassi')]\nresult = filtered[['q1']]", "sql": "SELECT T1.q1 FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 345 AND T2.forename = 'Lucas' AND T2.surname = 'di Grassi'", "difficulty": "simple" }, { "question_id": 871, "question": "For the driver who had the Q2 time as 0:01:15 in race No. 347, where is he from?", "db_id": "formula_1", "evidence": "race number refers to raceId;", "code": "import pandas as pd\nfiltered_quali = qualifying[(qualifying['raceId'] == 347) & (qualifying['q2'].str.startswith('1:15'))]\nmerged = pd.merge(filtered_quali, drivers, on='driverId')\nresult = merged[['nationality']].drop_duplicates()", "sql": "SELECT DISTINCT T2.nationality FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 347 AND T1.q2 LIKE '1:15%'", "difficulty": "simple" }, { "question_id": 872, "question": "In the race No. 45, for the driver who had the Q3 time as 0:01:33, what is his abbreviated code?", "db_id": "formula_1", "evidence": "race number refers to raceId; had the Q3 time as 0:0M:SS refers to q3 LIKE 'M:SS%'", "code": "import pandas as pd\n\ndef solve_query(qualifying_data, drivers_data):\n # Check if required columns exist\n if not {'raceId', 'driverId', 'q3'}.issubset(qualifying_data.columns):\n return pd.DataFrame(columns=['code'])\n if not {'driverId', 'code'}.issubset(drivers_data.columns):\n return pd.DataFrame(columns=['code'])\n\n try:\n # Filter qualifying data for raceId = 45 and q3 starts with '1:33'\n filtered_qualifying = qualifying_data[(qualifying_data['raceId'] == 45) & \n (qualifying_data['q3'].str.startswith('1:33'))]\n\n # Merge with drivers data to get the driver code\n result = pd.merge(filtered_qualifying, drivers_data, on='driverId', how='inner')[['code']]\n\n return result\n\n except Exception as e:\n print(f\"Error occurred: {e}\")\n return pd.DataFrame(columns=['code'])\n\n# Example usage\nqualifying_df = pd.DataFrame({\n 'raceId': [45, 45, 46],\n 'driverId': [1, 2, 3],\n 'q3': ['1:33.567', '1:34.000', '1:33.123']\n})\ndrivers_df = pd.DataFrame({\n 'driverId': [1, 2, 3],\n 'code': ['DRIVER1', 'DRIVER2', 'DRIVER3']\n})\n\nresult = solve_query(qualifying_df, drivers_df)\nprint(result)", "sql": "SELECT T2.code FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 45 AND T1.q3 LIKE '1:33%'", "difficulty": "simple" }, { "question_id": 873, "question": "What is the actual finish time for Bruce McLaren in the race No.743?", "db_id": "formula_1", "evidence": "race number refers to raceId;", "code": "import pandas as pd\nmerged = pd.merge(drivers, results, on='driverId')\nfiltered = merged[(merged['raceId'] == 743) & (merged['forename'] == 'Bruce') & (merged['surname'] == 'McLaren')]\nresult = filtered[['time']]", "sql": "SELECT T2.time FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T2.raceId = 743 AND T1.forename = 'Bruce' AND T1.surname = 'McLaren'", "difficulty": "simple" }, { "question_id": 874, "question": "Who finished second in the San Marino Grand Prix in 2006?", "db_id": "formula_1", "evidence": "finished second refers to position = 2;", "code": "import pandas as pd\n\n# Merge races with results\nmerged = pd.merge(races, results, on='raceId')\n\n# Merge with drivers\nmerged = pd.merge(merged, drivers, on='driverId')\n\n# Filter for 2006 San Marino Grand Prix and position 2\nfiltered = merged[(merged['year'] == 2006) & (merged['name'] == 'San Marino Grand Prix') & (merged['position'] == 2)]\n\n# Select forename and surname\nresult = filtered[['forename', 'surname']]", "sql": "SELECT T3.forename, T3.surname FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T1.year = 2006 AND T1.name = 'San Marino Grand Prix' AND T2.position = 2", "difficulty": "simple" }, { "question_id": 875, "question": "Show me the season page of year when the race No. 901 took place.", "db_id": "formula_1", "evidence": "the season page refers to url; race number refers to raceId;", "code": "import pandas as pd\nmerged = pd.merge(races[races['raceId'] == 901], seasons, left_on='year', right_on='year')\nresult = merged[['url_y']].rename(columns={'url_y': 'url'})", "sql": "SELECT T2.url FROM races AS T1 INNER JOIN seasons AS T2 ON T2.year = T1.year WHERE T1.raceId = 901", "difficulty": "simple" }, { "question_id": 876, "question": "For the race happened in 2015/11/29, how many drivers did not finish the game?", "db_id": "formula_1", "evidence": "game and race are synonyms; drivers who didn't finish the race should have record in time;", "code": "import pandas as pd\n\ndef solve_query(races_df, results_df):\n try:\n # Ensure 'date' column is in datetime format\n races_df['date'] = pd.to_datetime(races_df['date'], errors='coerce')\n\n # Filter races for the specified date\n target_race = races_df[races_df['date'] == '2015-11-29']\n\n if target_race.empty:\n return 0\n\n # Merge races and results on raceId\n merged_df = pd.merge(target_race, results_df, left_on='raceId', right_on='raceId', how='inner')\n\n # Filter drivers with NULL time\n if 'time' not in merged_df.columns:\n return 0\n\n drivers_not_finished = merged_df[merged_df['time'].isnull()]\n\n # Count the number of such drivers\n return len(drivers_not_finished)\n\n except Exception as e:\n return 0\n\n# Example function call\nresult = solve_query(races, results)\nprint(result)", "sql": "SELECT COUNT(T2.driverId) FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId WHERE T1.date = '2015-11-29' AND T2.time IS NULL", "difficulty": "simple" }, { "question_id": 877, "question": "For all the drivers who finished the game in race No. 872, who is the youngest?", "db_id": "formula_1", "evidence": "race number refers to raceId; drivers who finished the race refers to time has value; the youngest is a driver where MAX(dob);", "code": "import pandas as pd\n\ndrivers = pd.read_csv('drivers.csv')\nresults = pd.read_csv('results.csv')\n\n# 合并表 (SQL: FROM drivers JOIN results ON driverId)\nmerged = pd.merge(drivers, results, on='driverId')\n\n# 筛选: raceId 为 872 且 完成比赛(time 不为空)\n# SQL: WHERE raceId = 872 AND time IS NOT NULL\nfiltered = merged[(merged['raceId'] == 872) & (merged['time'].notna())]\n\n# 排序: dob 降序 (出生日期越晚越年轻)\n# SQL: ORDER BY dob DESC LIMIT 1\nsorted_df = filtered.sort_values('dob', ascending=False)\n\n# 选取前 1 名的姓名\nresult = sorted_df[['forename', 'surname']].head(1)\n\nprint(result)", "sql": "SELECT T1.forename, T1.surname FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T2.raceId = 872 AND T2.time IS NOT NULL ORDER BY T1.dob DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 878, "question": "Who was the driver that got the best lap time in the race No. 348? Give his full name.", "db_id": "formula_1", "evidence": "race number refers to raceId; the best lap time refers to MIN(time)", "code": "import pandas as pd\n\n# Read necessary tables\nlaps = pd.read_csv('lapTimes.csv')\ndrivers = pd.read_csv('drivers.csv')\n\n# Filter lap times for race No. 348\nrace_348_laps = laps[laps['raceId'] == 348]\n\n# Find the best lap time (minimum time) in race No. 348\nbest_lap_time = race_348_laps['time'].min()\n\n# Get the driver who achieved the best lap time\nbest_driver = race_348_laps[race_348_laps['time'] == best_lap_time]['driverId'].iloc[0]\n\n# Get the full name of the driver\ndriver_info = drivers[drivers['driverId'] == best_driver]\ndriver_full_name = f\"{driver_info['forename'].values[0]} {driver_info['surname'].values[0]}\"\n\nresult = driver_full_name\nprint(result)", "sql": "SELECT T2.forename, T2.surname FROM lapTimes AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = 348 ORDER BY T1.time ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 879, "question": "For the driver who set the fastest lap speed, what is his nationality?", "db_id": "formula_1", "evidence": "the fastest lap speed refers to (MAX) fastestLapSpeed;results refers to constructorResults", "code": "import pandas as pd\nmerged = pd.merge(results, drivers, on='driverId')\nfastest_speed = merged['fastestLapSpeed'].astype(float).max()\nresult = merged[merged['fastestLapSpeed'].astype(float) == fastest_speed]['nationality'].iloc[0]", "sql": "SELECT T1.nationality FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId ORDER BY CAST(T2.fastestLapSpeed AS REAL) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 880, "question": "Paul di Resta was in the No. 853 race, what percent faster did he finish in the 853rd race than the next race for the fastest lap speed?", "db_id": "formula_1", "evidence": "Paul di Resta refers to the full name of the driver; Full name of the driver refers to drivers.forename ='Paul' and drivers.surname = 'di Resta'; race number refers to raceId; percentage = DIVIDE(SUBTRACT(fastestLapSpeed(raceId = 853), (fastestLapSpeed (raceId = 854)) * 100 , (fastestLapSpeed(raceId = 853))fastestLapSpeed refers to constructorResults.fastestLapSpeed; race number refers to raceId; percentage = DIVIDE(SUBTRACT(fastestLapSpeed(raceId = 853), fastestLapSpeed(raceId = 854)) * 100, fastestLapSpeed(raceId = 853))", "code": "import pandas as pd\n# Find Paul di Resta's driverId\ndriver = drivers[(drivers['forename'] == 'Paul') & (drivers['surname'] == 'di Resta')].iloc[0]\ndriver_id = driver['driverId']\n# Extract fastest lap speeds for races 853 and 854\nr853_speed = results[(results['raceId'] == 853) & (results['driverId'] == driver_id) & results['fastestLapSpeed'].notnull()]['fastestLapSpeed'].values[0]\nr854_speed = results[(results['raceId'] == 854) & (results['driverId'] == driver_id) & results['fastestLapSpeed'].notnull()]['fastestLapSpeed'].values[0]\n# Calculate percentage difference\npercentage_faster = ((float(r853_speed) - float(r854_speed)) / float(r853_speed)) * 100\n# Store result in DataFrame\nresult = pd.DataFrame({'percentage_faster': [percentage_faster]})", "sql": "SELECT (T2_853.fastestLapSpeed - T2_854.fastestLapSpeed) * 100 / T2_853.fastestLapSpeed AS percentage_faster FROM drivers AS T1 INNER JOIN results AS T2_853 ON T2_853.driverId = T1.driverId AND T2_853.raceId = 853 INNER JOIN results AS T2_854 ON T2_854.driverId = T1.driverId AND T2_854.raceId = 854 WHERE T1.forename = 'Paul' AND T1.surname = 'di Resta' AND T2_853.fastestLapSpeed IS NOT NULL AND T2_854.fastestLapSpeed IS NOT NULL;", "difficulty": "challenging" }, { "question_id": 881, "question": "For the drivers who took part in the race in 1983/7/16, what's their race completion rate?", "db_id": "formula_1", "evidence": "DIVIDE(COUNT(driverid when time has value ), (COUNT(driverid )) as percentage; in 1983/7/16 refers to when date = '1983-07-16'", "code": "import pandas as pd\n\n# Load the necessary tables\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# Filter the races for the specific date\nrace_1983_07_16 = races[races['date'] == '1983-07-16']\n\n# Get the race IDs for the specific date\nrace_ids_1983_07_16 = race_1983_07_16['raceId']\n\n# Filter the results for the specific race IDs\nresults_1983_07_16 = results[results['raceId'].isin(race_ids_1983_07_16)]\n\n# Count the number of drivers who completed the race (time is not NaN)\ncompleted_races = results_1983_07_16[results_1983_07_16['time'].notna()]\n\n# Calculate the race completion rate\ntotal_drivers = len(results_1983_07_16)\ncompleted_drivers = len(completed_races)\ncompletion_rate = completed_drivers / total_drivers * 100\n\n# Record the final result\nresult = completion_rate\n\n# Print the final result\nprint(result)", "sql": "SELECT CAST(COUNT(CASE WHEN T2.time IS NOT NULL THEN T2.driverId END) AS REAL) * 100 / COUNT(T2.driverId) FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId WHERE T1.date = '1983-07-16'", "difficulty": "moderate" }, { "question_id": 882, "question": "Which year was the first Singapore Grand Prix?", "db_id": "formula_1", "evidence": "the first race refers to race happened in min(year);", "code": "import pandas as pd\nresult = races[races['name'] == 'Singapore Grand Prix']['year'].min()", "sql": "SELECT year FROM races WHERE name = 'Singapore Grand Prix' ORDER BY year ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 883, "question": "How many races were there in 2005? Name all the races in descending order.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nraces_2005 = races[races['year'] == 2005]\nraces_2005_sorted = races_2005.sort_values('name', ascending=False)\nresult = races_2005_sorted[['name']]", "sql": "SELECT name FROM races WHERE year = 2005 ORDER BY name DESC", "difficulty": "simple" }, { "question_id": 884, "question": "List the names of all races that occurred in the earliest recorded year and month.", "db_id": "formula_1", "evidence": "earliest recorded year and month refers to year = year(min(date)) and month = month(min(date));", "code": "import pandas as pd\nraces['date'] = pd.to_datetime(races['date'])\nearliest_date = races['date'].min()\nearliest_year = earliest_date.year\nearliest_month = earliest_date.month\nresult = races[(races['date'].dt.year == earliest_year) & (races['date'].dt.month == earliest_month)][['name']]", "sql": "SELECT name FROM races WHERE STRFTIME('%Y', date) = ( SELECT STRFTIME('%Y', date) FROM races ORDER BY date ASC LIMIT 1 ) AND STRFTIME('%m', date) = ( SELECT STRFTIME('%m', date) FROM races ORDER BY date ASC LIMIT 1 )", "difficulty": "moderate" }, { "question_id": 885, "question": "State the name and date of the last round of race in year 1999.", "db_id": "formula_1", "evidence": "the last round refers to max(round);", "code": "import pandas as pd\nfiltered_races = races[races['year'] == 1999]\nresult = filtered_races.nlargest(1, 'round')[['name', 'date']]", "sql": "SELECT name, date FROM races WHERE year = 1999 ORDER BY round DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 886, "question": "Which year has the most number of races?", "db_id": "formula_1", "evidence": "the most number of races refers to max(round);", "code": "import pandas as pd\nrace_counts = races.groupby('year').size()\nmax_year = race_counts.idxmax()\nresult = pd.DataFrame({'year': [max_year]})", "sql": "SELECT year FROM races GROUP BY year ORDER BY COUNT(round) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 887, "question": "Name the races in year 2017 that are not hosted in year 2000.", "db_id": "formula_1", "evidence": "not hosted means not in;", "code": "import pandas as pd\nraces_2017 = races[races['year'] == 2017]\nraces_2000 = races[races['year'] == 2000]\nresult = races_2017[~races_2017['name'].isin(races_2000['name'])][['name']]", "sql": "SELECT name FROM races WHERE year = 2017 AND name NOT IN ( SELECT name FROM races WHERE year = 2000 )", "difficulty": "simple" }, { "question_id": 888, "question": "In which country was the first European Grand Prix hosted? Name the circuit and location.", "db_id": "formula_1", "evidence": "the first refers to min(year);European Grand Prix refers to name in races; join races and circuits on circuitId to get country and location", "code": "import pandas as pd\nmerged = pd.merge(races, circuits, on='circuitId')\nfiltered = merged[merged['name_x'] == 'European Grand Prix']\nsorted_df = filtered.sort_values('year')\nresult = sorted_df.head(1)[['country', 'name_y', 'location']].rename(columns={'name_y': 'circuit'})", "sql": "SELECT T1.country, T1.name AS circuit, T1.location FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T2.name = 'European Grand Prix' ORDER BY T2.year ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 889, "question": "When was the last f1 season whereby Brands Hatch hosted the British Grand Prix?", "db_id": "formula_1", "evidence": "the last refers to max(year);", "code": "import pandas as pd\nmerged = pd.merge(circuits, races, on='circuitId')\nfiltered = merged[(merged['name_x'] == 'Brands Hatch') & (merged['name_y'] == 'British Grand Prix')]\nresult = filtered.sort_values('year', ascending=False).head(1)[['date']]", "sql": "SELECT T2.date FROM circuits AS T1 JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.name = 'Brands Hatch' AND T2.name = 'British Grand Prix' ORDER BY T2.year DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 890, "question": "How many seasons has Silverstone Circuit hosted the United Kindom grand prix?", "db_id": "formula_1", "evidence": "British Grand Prix is the name of race; British refers to the United Kindom", "code": "import pandas as pd\nmerged = pd.merge(circuits[circuits['name'] == 'Silverstone Circuit'], races[races['name'] == 'British Grand Prix'], left_on='circuitId', right_on='circuitId')\nresult = merged['year'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.year) FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.name = 'Silverstone Circuit' AND T2.name = 'British Grand Prix'", "difficulty": "simple" }, { "question_id": 891, "question": "Name all drivers in the 2010 Singapore Grand Prix order by their position stands.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\\n\\n# 假设数据已经加载到DataFrame中,这里使用races、results和drivers三个DataFrame作为示例\\nraces = pd.read_csv('races.csv') # 请替换为实际的数据源\\nresults = pd.read_csv('results.csv') # 请替换为实际的数据源\\ndrivers = pd.read_csv('drivers.csv') # 请替换为实际的数据源\\n\\n# 过滤出2010年的新加坡大奖赛\\nraces_filtered = races[(races['year'] == 2010) & (races['name'] == 'Singapore Grand Prix')]\\n\\n# 使用raceId进行JOIN操作\\nmerged_df = pd.merge(races_filtered, results, left_on='raceId', right_on='raceId')\\nmerged_df = pd.merge(merged_df, drivers, left_on='driverId', right_on='driverId')\\n\\n# 按positionOrder排序\\nsorted_df = merged_df.sort_values(by='positionOrder')\\n\\n# 选择需要的列\\nresult = sorted_df[['forename', 'surname']]\\n\\n# 输出结果\\nprint(result)", "sql": "SELECT T3.forename, T3.surname FROM races AS T1 JOIN results AS T2 ON T1.raceId = T2.raceId JOIN drivers AS T3 ON T2.driverId = T3.driverId WHERE T1.year = 2010 AND T1.name = 'Singapore Grand Prix' ORDER BY T2.positionOrder ASC", "difficulty": "simple" }, { "question_id": 892, "question": "State the driver with the most points scored. Find his full name with that points.", "db_id": "formula_1", "evidence": "the most points scored refers to max(points); Full name of the driver refers to drivers.forename and drivers.surname;", "code": "import pandas as pd\nmerged = pd.merge(driverStandings, drivers, on='driverId')\ngrouped = merged.groupby('driverId').agg(total_points=('points', 'sum'), forename=('forename', 'first'), surname=('surname', 'first'))\nsorted_df = grouped.sort_values('total_points', ascending=False)\nresult = sorted_df.head(1)", "sql": "SELECT d.forename, d.surname, SUM(ds.points) AS total_points\nFROM driverStandings ds\nJOIN drivers d ON ds.driverId = d.driverId\nGROUP BY ds.driverId\nORDER BY total_points DESC\nLIMIT 1", "difficulty": "moderate" }, { "question_id": 893, "question": "Name the top 3 drivers and the points they scored in the 2017 Chinese Grand Prix.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nresult = (\n pd.merge(races, results, on='raceId')\n .query(\"name == 'Chinese Grand Prix' and year == 2017\")\n .merge(drivers, on='driverId')\n [['forename', 'surname', 'points']]\n .sort_values('points', ascending=False)\n .head(3)\n)", "sql": "SELECT T3.forename, T3.surname, T4.points FROM races AS T1 INNER JOIN results AS T4 ON T4.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T4.driverId WHERE T1.name = 'Chinese Grand Prix' AND T1.year = 2017 ORDER BY T4.points DESC LIMIT 3", "difficulty": "simple" }, { "question_id": 894, "question": "What is the best lap time recorded? List the driver and race with such recorded lap time.", "db_id": "formula_1", "evidence": "the best lap time refers to min(milliseconds); List the driver refers to drivers.forename and drivers.surname; List the race refers to races.name", "code": "import pandas as pd\n\n# Merge drivers with lapTimes\nmerged = pd.merge(drivers, lapTimes, on='driverId')\n\n# Merge with races\nmerged = pd.merge(merged, races, on='raceId')\n\n# Sort by milliseconds and get the record with minimum lap time\nresult = merged.nsmallest(1, 'milliseconds')[['milliseconds', 'forename', 'surname', 'name']]", "sql": "SELECT T2.milliseconds, T1.forename, T1.surname, T3.name FROM drivers AS T1 INNER JOIN lapTimes AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T2.raceId = T3.raceId ORDER BY T2.milliseconds ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 895, "question": "What is the average lap time for Lewis Hamilton in the 2009 Malaysian Grand Prix?", "db_id": "formula_1", "evidence": "average lap time = AVG(milliseconds); 'Lewis Hamilton' refers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname; 'Malaysian Grand Prix' refers to races.name = 'Malaysian Grand Prix'", "code": "import pandas as pd\n\n# Filter races for 2009 Malaysian Grand Prix\nmalaysian_race = races[(races['year'] == 2009) & (races['name'] == 'Malaysian Grand Prix')]\n\n# Filter drivers for Lewis Hamilton\nlewis = drivers[(drivers['forename'] == 'Lewis') & (drivers['surname'] == 'Hamilton')]\n\n# Merge to get lap times for Lewis Hamilton in the specific race\nmerged = pd.merge(malaysian_race[['raceId']], lapTimes, on='raceId')\nmerged = pd.merge(merged, lewis[['driverId']], on='driverId')\n\n# Calculate average lap time\nresult = merged['milliseconds'].mean()", "sql": "SELECT AVG(T2.milliseconds) FROM races AS T1 INNER JOIN lapTimes AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Lewis' AND T3.surname = 'Hamilton' AND T1.year = 2009 AND T1.name = 'Malaysian Grand Prix'", "difficulty": "moderate" }, { "question_id": 896, "question": "Calculate the percentage whereby Hamilton was not at the 1st track of the the f1 circuit since 2010.", "db_id": "formula_1", "evidence": "percentage = DIVIDE(COUNT(raceId) where surname = 'Hamilton' and position>1), (COUNT(raceId) where surname = 'Hamilton'); since 2010 refers to year >= 2010", "code": "import pandas as pd\nmerged = pd.merge(races, results, on='raceId').merge(drivers, on='driverId')\nfiltered = merged[(merged['surname'] == 'Hamilton') & (merged['year'] >= 2010)]\nnot_first = (filtered['position'] > 1).sum()\ntotal = len(filtered)\npercentage = not_first / total * 100\nresult = percentage", "sql": "SELECT CAST(COUNT(CASE WHEN T2.position > 1 THEN 1 END) AS REAL) * 100 / COUNT(T2.resultId) FROM races AS T1 INNER JOIN results AS T2 ON T1.raceId = T2.raceId INNER JOIN drivers AS T3 ON T2.driverId = T3.driverId WHERE T3.surname = 'Hamilton' AND T1.year >= 2010", "difficulty": "challenging" }, { "question_id": 897, "question": "Name the driver with the most winning. Mention his nationality and what is his maximum point scores.", "db_id": "formula_1", "evidence": "Full name of the driver refers to drivers.forename and drivers.surname; the most winning refers to MAX(COUNT(wins)); average point scores refers to MAX(points);", "code": "import pandas as pd\\n\\n# 读取数据\\ndrivers = pd.read_csv('drivers.csv')\\ndriver_standings = pd.read_csv('driverStandings.csv')\\n\\n# 连接表\\nmerged_df = pd.merge(drivers, driver_standings, left_on='driverId', right_on='driverId')\\n\\n# 筛选出有胜利记录的行\\nwinning_drivers = merged_df[merged_df['wins'] >= 1]\\n\\n# 按照司机的名字、姓氏和国籍分组,并计算胜利次数\\ngrouped_df = winning_drivers.groupby(['forename', 'surname', 'nationality']).agg({'wins': 'count', 'points': 'max'}).reset_index()\\n\\n# 找出胜利次数最多的司机\\ntop_driver = grouped_df.sort_values(by='wins', ascending=False).head(1)\\n\\n# 输出结果\\nresult = top_driver[['forename', 'surname', 'nationality', 'points']]\\nprint(result)", "sql": "SELECT T1.forename, T1.surname, T1.nationality, MAX(T2.points) FROM drivers AS T1 INNER JOIN driverStandings AS T2 ON T2.driverId = T1.driverId WHERE T2.wins >= 1 GROUP BY T1.forename, T1.surname, T1.nationality ORDER BY COUNT(T2.wins) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 898, "question": "How old is the youngest Japanese driver? What is his name?", "db_id": "formula_1", "evidence": "date of birth refers to drivers.dob; The larger the birthday value, the younger the person is, and vice versa; Japanese refers to nationality = 'Japanese'; age = YEAR(CURRENT_TIMESTAMP) - YEAR(dob);", "code": "import pandas as pd\nfrom datetime import datetime\n\n# Filter Japanese drivers\njapanese_drivers = drivers[drivers['nationality'] == 'Japanese']\n\n# Sort by dob in descending order to get the youngest first\nyoungest = japanese_drivers.sort_values('dob', ascending=False).iloc[0]\n\n# Calculate age\ncurrent_year = datetime.now().year\nbirth_year = pd.to_datetime(youngest['dob']).year\nage = current_year - birth_year\n\n# Create result with age and name\nresult = pd.DataFrame({\n 'age': [age],\n 'forename': [youngest['forename']],\n 'surname': [youngest['surname']]\n})", "sql": "SELECT STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', dob) AS age, forename, surname FROM drivers WHERE nationality = 'Japanese' ORDER BY dob DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 899, "question": "List circuits which host 4 f1 races from year 1990 to 2000.", "db_id": "formula_1", "evidence": "from year 1990 to 2000 refers to year(date) between 1990 and 2000;", "code": "import pandas as pd\nfiltered_races = races[(races['year'] >= 1990) & (races['year'] <= 2000)]\nrace_counts = filtered_races.groupby('circuitId').size()\ncircuits_with_4_races = race_counts[race_counts == 4].index\nresult = circuits[circuits['circuitId'].isin(circuits_with_4_races)][['name']]", "sql": "SELECT T1.name FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE STRFTIME('%Y', T2.date) BETWEEN '1990' AND '2000' GROUP BY T1.circuitId HAVING COUNT(T2.raceId) = 4", "difficulty": "moderate" }, { "question_id": 900, "question": "List circuits in USA which hosted f1 races in 2006. State the name and location of circuit and the name of the race it hosted.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\n\ncircuits = pd.read_csv('circuits.csv')\nraces = pd.read_csv('races.csv')\n\n# Filter circuits in USA\nusa_circuits = circuits[circuits['country'] == 'USA']\n\n# Filter races in 2006\nraces_2006 = races[races['year'] == 2006]\n\n# Merge circuits and races on circuitId\nresult = pd.merge(usa_circuits, races_2006, on='circuitId')[['name_x', 'location', 'name_y']]\n\n# Rename columns for clarity\nresult.columns = ['Circuit Name', 'Location', 'Race Name']\n\nprint(result)", "sql": "SELECT T1.name, T1.location, T2.name FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.country = 'USA' AND T2.year = 2006", "difficulty": "simple" }, { "question_id": 901, "question": "Name the races along with its circuit name and location for f1 races hosted in September 2005.", "db_id": "formula_1", "evidence": "in September 2005 refers to MONTH(date) = 9 and YEAR(date) = 2005", "code": "import pandas as pd\nraces['date'] = pd.to_datetime(races['date'])\nfiltered_races = races[(races['year'] == 2005) & (races['date'].dt.month == 9)]\nmerged = pd.merge(filtered_races, circuits, left_on='circuitId', right_on='circuitId')\nresult = merged[['name_y', 'name_x', 'location']].drop_duplicates()", "sql": "SELECT DISTINCT T2.name, T1.name, T1.location FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitID = T1.circuitId WHERE T2.year = 2005 AND STRFTIME('%m', T2.date) = '09'", "difficulty": "simple" }, { "question_id": 902, "question": "Which race was Alex Yoong in when he was in track number less than 20?", "db_id": "formula_1", "evidence": "Alex Yoong refers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname;track number less than 10 refers to position < 20track number less than 20 refers to position < 20", "code": "import pandas as pd\n# Filter drivers table for Alex Yoong\ndriver = drivers[(drivers['forename'] == 'Alex') & (drivers['surname'] == 'Yoong')]\n# Filter results with grid < 20 for this driver\nfiltered = results[(results['driverId'] == driver['driverId'].iloc[0]) & (results['grid'] < 20)]\n# Join with races to get race names\nresult = pd.merge(filtered, races, on='raceId')[['name']]", "sql": "SELECT T1.name FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Alex' AND T3.surname = 'Yoong' AND T2.grid < 20", "difficulty": "simple" }, { "question_id": 903, "question": "How many times did Michael Schumacher won from races hosted in Sepang International Circuit?", "db_id": "formula_1", "evidence": "win from races refers to max(points)wins in driverStandings refers to count of race victories", "code": "import pandas as pd\n# 合并races和circuits获取赛道名称\nrace_circuits = pd.merge(races[['raceId', 'circuitId']], circuits[['circuitId', 'name']], on='circuitId')\n# 合并results和drivers\nresults_drivers = pd.merge(results, drivers, on='driverId')\n# 合并得到最终数据\nmerged = pd.merge(results_drivers, race_circuits, on='raceId')\n# 筛选条件\nfiltered = merged[(merged['forename'] == 'Michael') & (merged['surname'] == 'Schumacher') & (merged['name'] == 'Sepang International Circuit') & (merged['positionOrder'] == 1)]\nresult = len(filtered)", "sql": "SELECT COUNT(*) FROM results AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T1.raceId = T3.raceId INNER JOIN circuits AS T4 ON T3.circuitId = T4.circuitId WHERE T2.forename = 'Michael' AND T2.surname = 'Schumacher' AND T4.name = 'Sepang International Circuit' AND T1.positionOrder = 1", "difficulty": "moderate" }, { "question_id": 904, "question": "State the race and year of race in which Michael Schumacher had his fastest lap.", "db_id": "formula_1", "evidence": "fastest lap refers to min(milliseconds); Alex Yoong refers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname;", "code": "import pandas as pd\\n\\n# 读取数据表为DataFrame\\nraces = pd.read_csv('races.csv')\\nlap_times = pd.read_csv('lapTimes.csv')\\ndrivers = pd.read_csv('drivers.csv')\\n\\n# 合并三个表格,基于raceId和driverId字段进行连接\\nmerged_data = pd.merge(races, lap_times, on='raceId')\\nmerged_data = pd.merge(merged_data, drivers, on='driverId')\\n\\n# 筛选出Michael Schumacher的记录\\nschumacher_laps = merged_data[(merged_data['forename'] == 'Michael') & (merged_data['surname'] == 'Schumacher')]\\n\\n# 按照milliseconds排序,并选择最快的一圈\\nfastest_lap = schumacher_laps.sort_values(by='milliseconds').head(1)\\n\\n# 提取结果中的race名称和年份\\nresult = fastest_lap[['name', 'year']]\\nprint(result)", "sql": "SELECT T1.name, T1.year FROM races AS T1 INNER JOIN lapTimes AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Michael' AND T3.surname = 'Schumacher' ORDER BY T2.milliseconds ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 905, "question": "What is Eddie Irvine's average points scored in year 2000?", "db_id": "formula_1", "evidence": "year equals 2000 in the database; average of points where year = 2000;", "code": "import pandas as pd\n# Merge drivers with results\ndriver_results = pd.merge(drivers, results, on='driverId')\n# Merge with races\nall_data = pd.merge(driver_results, races, on='raceId')\n# Filter for Eddie Irvine and year 2000\nfiltered = all_data[(all_data['forename'] == 'Eddie') & (all_data['surname'] == 'Irvine') & (all_data['year'] == 2000)]\n# Calculate average points\navg_points = filtered['points'].mean()\n# Convert scalar to DataFrame\nresult = pd.DataFrame({'average_points': [avg_points]})", "sql": "SELECT AVG(T2.points) FROM drivers AS T1 INNER JOIN results AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T3.raceId = T2.raceId WHERE T1.forename = 'Eddie' AND T1.surname = 'Irvine' AND T3.year = 2000", "difficulty": "simple" }, { "question_id": 906, "question": "Which was Lewis Hamilton first race? What was his points recorded for his first race event?", "db_id": "formula_1", "evidence": "first race refers to min(Year); Lewis Hamiltonrefers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname;", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\nraces_df = pd.read_csv('races.csv')\ndriver_standings_df = pd.read_csv('driverStandings.csv')\ndrivers_df = pd.read_csv('drivers.csv')\n\n# 连接表\nmerged_df = pd.merge(races_df, driver_standings_df, left_on='raceId', right_on='raceId')\nmerged_df = pd.merge(merged_df, drivers_df, left_on='driverId', right_on='driverId')\n\n# 筛选Lewis Hamilton的数据\nhamilton_df = merged_df[(merged_df['forename'] == 'Lewis') & (merged_df['surname'] == 'Hamilton')]\n\n# 按年份排序并获取第一条记录\nfirst_race = hamilton_df.sort_values(by='year').head(1)\n\n# 输出结果\nresult = first_race[['name', 'points']]\nprint(result.to_json(orient='records'))", "sql": "SELECT T1.name, T2.points FROM races AS T1 INNER JOIN driverStandings AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Lewis' AND T3.surname = 'Hamilton' ORDER BY T1.year ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 907, "question": "List all races in 2017 and the hosting country order by date of the event.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\\n\\n# 读取数据\\ncircuits_df = pd.read_csv('circuits.csv')\\nraces_df = pd.read_csv('races.csv')\\n\\n# 连接两个DataFrame\\nmerged_df = pd.merge(races_df, circuits_df, left_on='circuitId', right_on='circuitId')\\n\\n# 筛选出2017年的比赛\\nfiltered_df = merged_df[merged_df['year'] == 2017]\\n\\n# 按日期排序并选择需要的列\\nsorted_df = filtered_df.sort_values(by='date')\\nresult = sorted_df[['name_x', 'country']]\\n\\n# 输出结果\\nprint(result)", "sql": "SELECT T2.name, T1.country FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T2.year = 2017 ORDER BY T2.date ASC", "difficulty": "simple" }, { "question_id": 908, "question": "What is the most laps f1 races had? Name the race, year and circuit location where the races with most laps was hosted.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\\n\\n# 读取数据\\ncircuits = pd.read_csv('circuits.csv')\\nraces = pd.read_csv('races.csv')\\nlap_times = pd.read_csv('lapTimes.csv')\\n\\n# 连接表\\nrace_circuit = pd.merge(races, circuits, left_on='circuitId', right_on='circuitId')\\nrace_laps = pd.merge(race_circuit, lap_times, left_on='raceId', right_on='raceId')\\n\\n# 计算每场比赛的最大圈数\\nmax_laps_per_race = race_laps.groupby('raceId')['lap'].max().reset_index()\\nmax_laps_per_race.columns = ['raceId', 'max_laps']\\n\\n# 找到最大圈数的比赛信息\\nresult = pd.merge(max_laps_per_race, race_circuit, on='raceId')[['max_laps', 'name_x', 'year', 'location']]\\nresult = result.sort_values(by='max_laps', ascending=False).head(1)\\n\\nprint(result)", "sql": "SELECT max_laps, race_name, year, location FROM (SELECT MAX(T3.lap) AS max_laps, T2.name AS race_name, T2.year, T1.location FROM circuits AS T1 JOIN races AS T2 ON T1.circuitId = T2.circuitId JOIN lapTimes AS T3 ON T2.raceId = T3.raceId GROUP BY T2.raceId) ORDER BY max_laps DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 909, "question": "Among all European Grand Prix races, what is the percentage of the races were hosted in Germany?", "db_id": "formula_1", "evidence": "European Grand Prix races refers to races.name = 'European Grand Prix';percentage = divide(COUNT(races where country = Germany and name = 'Europearn Grand Prix'),COUNT(races where name = 'Europearn Grand Prix'))*100", "code": "import pandas as pd\n\n# 读取数据\ncircuits = pd.read_csv('circuits.csv')\nraces = pd.read_csv('races.csv')\n\n# 内连接两个DataFrame,基于circuitID列\nmerged_df = pd.merge(circuits, races, left_on='circuitId', right_on='circuitId')\n\n# 筛选出名称为'European Grand Prix'的比赛\neuropean_gp = merged_df[merged_df['name_y'] == 'European Grand Prix']\n\n# 计算在德国举办的欧洲大奖赛数量\ngermany_count = european_gp[european_gp['country'] == 'Germany'].shape[0]\n\n# 总的欧洲大奖赛数量\ntotal_count = european_gp.shape[0]\n\n# 计算百分比\npercentage = (germany_count / total_count) * 100 if total_count > 0 else 0\n\n# 输出结果\nresult = {'percentage': percentage}\nprint(result)", "sql": "SELECT CAST(COUNT(CASE WHEN T1.country = 'Germany' THEN T2.circuitID END) AS REAL) * 100 / COUNT(T2.circuitId) FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitID = T1.circuitId WHERE T2.name = 'European Grand Prix'", "difficulty": "moderate" }, { "question_id": 910, "question": "What's the location coordinates of Silverstone Circuit?", "db_id": "formula_1", "evidence": "location coordinates refers to (lat, lng); Silverstone Circuit refers to circuits.name = 'Silverstone Circuit'", "code": "import pandas as pd\nresult = circuits[circuits['name'] == 'Silverstone Circuit'][['lat', 'lng']]", "sql": "SELECT lat, lng FROM circuits WHERE name = 'Silverstone Circuit'", "difficulty": "simple" }, { "question_id": 911, "question": "Which of these circuits is located at a higher latitude, Silverstone Circuit, Hockenheimring or Hungaroring?", "db_id": "formula_1", "evidence": "higher latitude refers to max(lat)", "code": "import pandas as pd\nfiltered_circuits = circuits[circuits['name'].isin(['Silverstone Circuit', 'Hockenheimring', 'Hungaroring'])]\nresult = filtered_circuits.nlargest(1, 'lat')[['name']]", "sql": "SELECT name FROM circuits WHERE name IN ('Silverstone Circuit', 'Hockenheimring', 'Hungaroring') ORDER BY lat DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 912, "question": "What's the reference name of Marina Bay Street Circuit?", "db_id": "formula_1", "evidence": "reference name refers to circuitRef; Marina Bay Street Circuit refers to circuits.name = 'Marina Bay Street Circuit'", "code": "import pandas as pd\nresult = circuits[circuits['name'] == 'Marina Bay Street Circuit']['circuitRef']", "sql": "SELECT circuitRef FROM circuits WHERE name = 'Marina Bay Street Circuit'", "difficulty": "simple" }, { "question_id": 913, "question": "In which country can I find the circuit with the highest altitude?", "db_id": "formula_1", "evidence": "highest altitude refers to max(alt)", "code": "import pandas as pd\\n\\n# 读取circuits表到DataFrame\\ndf_circuits = pd.read_csv('circuits.csv') # 假设数据存储在CSV文件中,实际应用时请替换为正确的数据源路径或数据库连接方式\\n\\n# 按照alt列降序排序并取第一行\\nresult = df_circuits.sort_values(by='alt', ascending=False).head(1)[['country']]\\n\\n# 输出结果\\nprint(result.to_json(orient='records'))", "sql": "SELECT country FROM circuits ORDER BY alt DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 914, "question": "How many drivers don't have a code?", "db_id": "formula_1", "evidence": "don't have a code refers to code is null", "code": "import pandas as pd\nimport numpy as np\n\nresult = drivers['code'].isna().sum()", "sql": "SELECT COUNT(driverId) - COUNT(CASE WHEN code IS NOT NULL THEN code END) FROM drivers", "difficulty": "simple" }, { "question_id": 915, "question": "Which country is the oldest driver from?", "db_id": "formula_1", "evidence": "date of birth refers to drivers.dob; The larger the birthday value, the younger the person is, and vice versa;", "code": "import pandas as pd\nfiltered_drivers = drivers[drivers['dob'].notna()]\nsorted_drivers = filtered_drivers.sort_values('dob', ascending=True)\noldest_driver = sorted_drivers.iloc[0]\nresult = oldest_driver['nationality']", "sql": "SELECT nationality FROM drivers WHERE dob IS NOT NULL ORDER BY dob ASC LIMIT 1;", "difficulty": "simple" }, { "question_id": 916, "question": "Please list the surnames of all the Italian drivers.", "db_id": "formula_1", "evidence": "nationality equals 'italian' in the database;", "code": "import pandas as pd\nresult = drivers[drivers['nationality'] == 'Italian']['surname']", "sql": "SELECT surname FROM drivers WHERE nationality = 'Italian'", "difficulty": "simple" }, { "question_id": 917, "question": "Which website should I go to if I want to know more about Anthony Davidson?", "db_id": "formula_1", "evidence": "website refers to url", "code": "import pandas as pd\ndf = pd.read_csv('drivers.csv')\nresult = df[(df['forename'] == 'Anthony') & (df['surname'] == 'Davidson')]['url']\nprint(result.to_json(orient='records'))", "sql": "SELECT url FROM drivers WHERE forename = 'Anthony' AND surname = 'Davidson'", "difficulty": "simple" }, { "question_id": 918, "question": "What's Lewis Hamilton's reference name?", "db_id": "formula_1", "evidence": "reference name refers to driverRef", "code": "import pandas as pd\nresult = drivers[(drivers['forename'] == 'Lewis') & (drivers['surname'] == 'Hamilton')]['driverRef'].iloc[0]", "sql": "SELECT driverRef FROM drivers WHERE forename = 'Lewis' AND surname = 'Hamilton'", "difficulty": "simple" }, { "question_id": 919, "question": "Which circuit did the 2009 Spanish Grand Prix use?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(races[races['year'] == 2009][races['name'] == 'Spanish Grand Prix'], circuits, left_on='circuitId', right_on='circuitId')\nresult = merged[['name_y']].rename(columns={'name_y': 'name'})", "sql": "SELECT T1.name FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitID = T1.circuitId WHERE T2.year = 2009 AND T2.name = 'Spanish Grand Prix'", "difficulty": "simple" }, { "question_id": 920, "question": "Please list all the years that Silverstone Circuit was used in a Formula_1 race.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(circuits[circuits['name'] == 'Silverstone Circuit'], races, left_on='circuitId', right_on='circuitId')\nresult = merged[['year']].drop_duplicates().sort_values('year')", "sql": "SELECT DISTINCT T2.year FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitID = T1.circuitId WHERE T1.name = 'Silverstone Circuit'", "difficulty": "simple" }, { "question_id": 921, "question": "Please give more information about the Formula_1 races that used the Silverstone Circuit.", "db_id": "formula_1", "evidence": "more information refers to url", "code": "import pandas as pd\\nimport json\\n\\n# 读取数据为DataFrame\\ncircuits_df = pd.read_csv('circuits.csv')\\nraces_df = pd.read_csv('races.csv')\\n\\n# 筛选出Silverstone Circuit的记录\\nsilverstone_circuit = circuits_df[circuits_df['name'] == 'Silverstone Circuit']\\n\\n# 通过circuitId进行内连接\\nmerged_df = pd.merge(silverstone_circuit, races_df, left_on='circuitId', right_on='circuitId')\\n\\n# 选择url列并去重\\nresult = merged_df['url_y'].drop_duplicates()\\n\\n# 将结果转换为JSON格式,确保不转义斜杠\\nresult_json = json.dumps(result.tolist(), ensure_ascii=False)\\n\\n# 输出结果\\nprint(result_json)", "sql": "SELECT DISTINCT T2.url FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.name = 'Silverstone Circuit'", "difficulty": "simple" }, { "question_id": 922, "question": "What time did the the 2010's Formula_1 race took place on the Abu Dhabi Circuit?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(races[races['year'] == 2010], circuits, left_on='circuitId', right_on='circuitId')\nfiltered = merged[merged['name_x'] == 'Abu Dhabi Grand Prix']\nresult = filtered[['date', 'time']]", "sql": "SELECT T2.date, T2.time FROM circuits AS T1 INNER JOIN races AS T2 ON T1.circuitId = T2.circuitId WHERE T1.name = 'Abu Dhabi Circuit' AND T2.year = 2010", "difficulty": "simple" }, { "question_id": 923, "question": "How many Formula_1 races took place on the circuits in Italy?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\n\n# 假设已经从数据库中读取了数据到DataFrame中\ncircuits = pd.read_csv('circuits.csv') # circuits表的数据\nraces = pd.read_csv('races.csv') # races表的数据\n\n# 使用pandas的merge方法实现SQL中的JOIN操作\nmerged_df = pd.merge(races, circuits, left_on='circuitId', right_on='circuitId')\n\n# 筛选出国家为Italy的数据行,相当于SQL中的WHERE T1.country = 'Italy'\nfiltered_df = merged_df[merged_df['country'] == 'Italy']\n\n# 计算符合条件的比赛数量,即COUNT(T2.circuitId)的结果\nresult = filtered_df['circuitId'].count()\n\nprint(result)", "sql": "SELECT COUNT(T2.circuitId) FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitId = T1.circuitId WHERE T1.country = 'Italy'", "difficulty": "simple" }, { "question_id": 924, "question": "Please list the exact dates on which a Formula_1 race took place on the Barcelona-Catalunya circuit.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\n\n# 读取数据到DataFrame中\ncircuits = pd.read_csv('circuits.csv') # circuits表的数据\nraces = pd.read_csv('races.csv') # races表的数据\n\n# 使用pandas的merge方法实现SQL中的JOIN操作\nmerged_df = pd.merge(races, circuits, left_on='circuitId', right_on='circuitId')\n\n# 筛选出赛道名为'Circuit de Barcelona-Catalunya'的数据行,相当于SQL中的WHERE circuits.name = 'Circuit de Barcelona-Catalunya'\nfiltered_df = merged_df[merged_df['name_y'] == 'Circuit de Barcelona-Catalunya']\n\n# 选择日期列作为结果,相当于SQL中的SELECT races.date\nresult = filtered_df['date'].tolist()\n\nprint(result)", "sql": "SELECT races.date FROM circuits INNER JOIN races ON races.circuitId = circuits.circuitId WHERE circuits.name = 'Circuit de Barcelona-Catalunya'", "difficulty": "simple" }, { "question_id": 925, "question": "Please give the link of the website that shows more information about the circuits the Spanish Grand Prix used in 2009.", "db_id": "formula_1", "evidence": "link of the website refers to url", "code": "import pandas as pd\nmerged = pd.merge(races[races['year'] == 2009][races['name'] == 'Spanish Grand Prix'], circuits, left_on='circuitId', right_on='circuitId')\nresult = merged[['url_y']].rename(columns={'url_y': 'url'})", "sql": "SELECT T1.url FROM circuits AS T1 INNER JOIN races AS T2 ON T2.circuitID = T1.circuitId WHERE T2.year = 2009 AND T2.name = 'Spanish Grand Prix'", "difficulty": "simple" }, { "question_id": 926, "question": "What's the fastest lap time ever in a race for Lewis Hamilton?", "db_id": "formula_1", "evidence": "fastest lap time ever refers to min(fastestLapTime)", "code": "import pandas as pd\n\ndef solve_query(drivers_df, results_df):\n # Filter drivers for Lewis Hamilton\n lewis_hamilton = drivers_df[(drivers_df['forename'] == 'Lewis') & (drivers_df['surname'] == 'Hamilton')]\n\n if lewis_hamilton.empty:\n return None\n\n lewis_driver_id = lewis_hamilton['driverId'].iloc[0]\n\n # Filter results for the driver and non-NULL fastestLapTime\n results_filtered = results_df[(results_df['driverId'] == lewis_driver_id) & results_df['fastestLapTime'].notna()]\n\n if 'fastestLapTime' not in results_filtered.columns or results_filtered.empty:\n return None\n\n try:\n # Convert fastestLapTime to timedelta for comparison\n results_filtered['fastestLapTime'] = pd.to_timedelta(results_filtered['fastestLapTime'])\n\n # Find the fastest lap time\n fastest_lap_time = results_filtered.loc[results_filtered['fastestLapTime'].idxmin()]['fastestLapTime']\n return fastest_lap_time\n except Exception as e:\n return None\n\n# Example usage\ndata_drivers = {\n 'driverId': [1, 2],\n 'forename': ['Lewis', 'Max'],\n 'surname': ['Hamilton', 'Verstappen']\n}\ndata_results = {\n 'resultId': [101, 102],\n 'driverId': [1, 1],\n 'fastestLapTime': ['00:01:10.000', '00:01:09.500']\n}\n\ndrivers_df = pd.DataFrame(data_drivers)\nresults_df = pd.DataFrame(data_results)\n\nresult = solve_query(drivers_df, results_df)\nprint(result)", "sql": "SELECT T2.fastestLapTime FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T1.forename = 'Lewis' AND T1.surname = 'Hamilton' AND T2.fastestLapTime IS NOT NULL ORDER BY T2.fastestLapTime ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 927, "question": "Which driver created the fastest lap speed in a Formula_1 race? Please give both his forename and surname.", "db_id": "formula_1", "evidence": "results refers to constructorResults", "code": "import pandas as pd\n\ndrivers = pd.read_csv('drivers.csv')\nresults = pd.read_csv('results.csv')\n\n# 1. 合并表 (SQL: FROM drivers JOIN results ON driverId)\nmerged = pd.merge(drivers, results, on='driverId')\n\n# 2. 类型转换 (SQL: CAST(fastestLapSpeed AS REAL))\n# 将字符串类型的 fastestLapSpeed 转换为数值型,无法转换的变为 NaN\nmerged['fastestLapSpeed_num'] = pd.to_numeric(merged['fastestLapSpeed'], errors='coerce')\n\n# 3. 筛选 (SQL: WHERE fastestLapSpeed IS NOT NULL)\nfiltered = merged[merged['fastestLapSpeed_num'].notna()]\n\n# 4. 排序 (SQL: ORDER BY ... DESC LIMIT 1)\n# 传入转换后的列名 'fastestLapSpeed_num'\nsorted_df = filtered.sort_values('fastestLapSpeed_num', ascending=False)\n\n# 5. 选择结果\nresult = sorted_df[['forename', 'surname']].head(1)\n\nprint(result)", "sql": "SELECT T1.forename, T1.surname FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T2.fastestLapSpeed IS NOT NULL ORDER BY CAST(T2.fastestLapSpeed AS REAL) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 928, "question": "Which driver ranked the first in the Canadian Grand Prix in 2007? Please give his reference name.", "db_id": "formula_1", "evidence": "reference name refers to driverRef; Canadian Grand Prix refers to races.name = 'Canadian Grand Prix';rank refers to results.rank", "code": "import pandas as pd\n# Find raceIds for 2007 Canadian GP\nrace_ids = races[(races['name'] == 'Canadian Grand Prix') & (races['year'] == 2007)]['raceId']\n# Get driverId of winner (positionOrder=1)\ndriver_id = results[(results['raceId'].isin(race_ids)) & (results['positionOrder'] == 1)]['driverId'].iloc[0]\n# Get driverRef from drivers table\nresult = drivers[drivers['driverId'] == driver_id]['driverRef'].iloc[0]", "sql": "SELECT T3.driverRef FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T1.name = 'Canadian Grand Prix' AND T2.positionOrder = 1 AND T1.year = 2007", "difficulty": "moderate" }, { "question_id": 929, "question": "Please list the Formula_1 races that Lewis Hamilton participated.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged1 = pd.merge(results, races, on='raceId')\nmerged2 = pd.merge(merged1, drivers, on='driverId')\nfiltered = merged2[(merged2['forename'] == 'Lewis') & (merged2['surname'] == 'Hamilton')]\nresult = filtered[['name']].drop_duplicates()", "sql": "SELECT T1.name FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Lewis' AND T3.surname = 'Hamilton'", "difficulty": "simple" }, { "question_id": 930, "question": "In which Formula_1 race did Lewis Hamilton rank the highest?", "db_id": "formula_1", "evidence": "rank the highest refers to min(rank); Lewis Hamilton refers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname;results refers to constructorResults table", "code": "import pandas as pd\nhamilton_id = drivers[(drivers['forename'] == 'Lewis') & (drivers['surname'] == 'Hamilton')]['driverId'].iloc[0]\nfiltered_race_ids = results[(results['driverId'] == hamilton_id) & (results['positionOrder'] == 1)]['raceId']\nresult = races[races['raceId'].isin(filtered_race_ids)][['name']]", "sql": "SELECT name FROM races WHERE raceId IN ( SELECT raceId FROM results WHERE positionOrder = 1 AND driverId = ( SELECT driverId FROM drivers WHERE forename = 'Lewis' AND surname = 'Hamilton' ) )", "difficulty": "simple" }, { "question_id": 931, "question": "What was the fastest lap speed among all drivers in the 2009 Spanish Grand Prix?", "db_id": "formula_1", "evidence": "the fastest lap speed among all refers to max(fastestLapSpeed); Spanish Grand Prix refers to races.name = 'Spanish Grand Prix';", "code": "import pandas as pd\n\n# Merge races and results tables\nmerged_df = pd.merge(races, results, on='raceId')\n\n# Filter for Spanish Grand Prix 2009 and non-null fastest lap speed\nfiltered_df = merged_df[\n (merged_df['name'] == 'Spanish Grand Prix') & \n (merged_df['year'] == 2009) & \n (merged_df['fastestLapSpeed'].notna())\n]\n\n# Convert fastestLapSpeed to numeric and get maximum\nfiltered_df['fastestLapSpeed'] = pd.to_numeric(filtered_df['fastestLapSpeed'], errors='coerce')\nresult = filtered_df.nlargest(1, 'fastestLapSpeed')[['fastestLapSpeed']]", "sql": "SELECT T2.fastestLapSpeed FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId WHERE T1.name = 'Spanish Grand Prix' AND T1.year = 2009 AND T2.fastestLapSpeed IS NOT NULL ORDER BY CAST(T2.fastestLapSpeed AS REAL) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 932, "question": "In which years did Lewis Hamilton participate in a Formula_1 race?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(results, races, on='raceId')\nmerged = pd.merge(merged, drivers, on='driverId')\nfiltered = merged[(merged['forename'] == 'Lewis') & (merged['surname'] == 'Hamilton')]\nresult = filtered[['year']].drop_duplicates().sort_values('year')", "sql": "SELECT DISTINCT T1.year FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Lewis' AND T3.surname = 'Hamilton'", "difficulty": "simple" }, { "question_id": 933, "question": "What was Lewis Hamilton's final rank in the 2008 Chinese Grand Prix?", "db_id": "formula_1", "evidence": "Lewis Hamilton refers to the full name of the driver; Full name of the driver refers to drivers.forename and drivers.surname; final rank refers to positionOrder; Chinese Grand Prix refers to races.name = 'Chinese Grand Prix';", "code": "import pandas as pd\nmerged = pd.merge(races, results, on='raceId')\nmerged = pd.merge(merged, drivers, on='driverId')\nfiltered = merged[(merged['forename'] == 'Lewis') & (merged['surname'] == 'Hamilton') & (merged['name'] == 'Chinese Grand Prix') & (merged['year'] == 2008)]\nresult = filtered['positionOrder'].iloc[0]", "sql": "SELECT T2.positionOrder FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T3.forename = 'Lewis' AND T3.surname = 'Hamilton' AND T1.name = 'Chinese Grand Prix' AND T1.year = 2008", "difficulty": "moderate" }, { "question_id": 934, "question": "Which driver was in the no. 4 grid formation when starting the race in 1989's Australian Grand Prix? Please give his forename and surname.", "db_id": "formula_1", "evidence": "grid equals 4 in the database;", "code": "import pandas as pd\n\n# Merge races with results\nmerged = pd.merge(results, races, on='raceId')\n\n# Merge with drivers\nmerged = pd.merge(merged, drivers, on='driverId')\n\n# Filter for grid position 4, Australian Grand Prix in 1989\nfiltered = merged[(merged['grid'] == 4) & (merged['name'] == 'Australian Grand Prix') & (merged['year'] == 1989)]\n\n# Select forename and surname\nresult = filtered[['forename', 'surname']]", "sql": "SELECT T3.forename, T3.surname FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId INNER JOIN drivers AS T3 ON T3.driverId = T2.driverId WHERE T2.grid = 4 AND T1.name = 'Australian Grand Prix' AND T1.year = 1989", "difficulty": "moderate" }, { "question_id": 935, "question": "How many drivers managed to finish the race in the 2008 Australian Grand Prix?", "db_id": "formula_1", "evidence": "managed to finish the race refers to time is not null", "code": "import pandas as pd\n\n# 读取races和results表到DataFrame中\nraces_df = pd.read_csv('races.csv')\nresults_df = pd.read_csv('results.csv')\n\n# 筛选出2008年澳大利亚大奖赛的数据\nrace_2008_aus_gp = races_df.query('name == \"Australian Grand Prix\" and year == 2008')\n\n# 通过raceId进行内连接\nmerged_df = pd.merge(results_df, race_2008_aus_gp, left_on='raceId', right_on='raceId')\n\n# 筛选time非空的记录并统计driverId数量\nfinished_drivers_count = merged_df[merged_df['time_x'].notna()]['driverId'].count()\n\n# 输出结果\nprint(finished_drivers_count)", "sql": "SELECT COUNT(T2.driverId) FROM races AS T1 INNER JOIN results AS T2 ON T2.raceId = T1.raceId WHERE T1.name = 'Australian Grand Prix' AND T1.year = 2008 AND T2.time IS NOT NULL", "difficulty": "simple" }, { "question_id": 936, "question": "Which was the fastest lap for Lewis Hamilton in the 2008 Australian Grand Prix?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(results, races, on='raceId')\nmerged = pd.merge(merged, drivers, on='driverId')\nfiltered = merged[(merged['name'] == 'Australian Grand Prix') & (merged['year'] == 2008) & (merged['forename'] == 'Lewis') & (merged['surname'] == 'Hamilton')]\nresult = filtered[['fastestLap']]", "sql": "SELECT T1.fastestLap FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN drivers AS T3 ON T1.driverId = T3.driverId WHERE T2.name = 'Australian Grand Prix' AND T2.year = 2008 AND T3.forename = 'Lewis' AND T3.surname = 'Hamilton';", "difficulty": "simple" }, { "question_id": 937, "question": "", "db_id": "formula_1", "evidence": "finish time refers to time; Chinese Grand Prix refers to races.name = 'Chinese Grand Prix';", "code": "import pandas as pd\nmerged = pd.merge(results, races, on='raceId', suffixes=('_result', '_race'))\nfiltered = merged[(merged['positionOrder'] == 2) & (merged['name'] == 'Chinese Grand Prix') & (merged['year'] == 2008)]\nresult = filtered[['time_result']]", "sql": "SELECT T1.time FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T1.positionOrder = 2 AND T2.name = 'Chinese Grand Prix' AND T2.year = 2008", "difficulty": "simple" }, { "question_id": 938, "question": "Who was the champion of 2008's Australian Grand Prix and where can I know more about him?", "db_id": "formula_1", "evidence": "only champion's finished time is represented by 'HH:MM:SS.mmm'; where can I know more refers to url", "code": "import pandas as pd\n\n# Merge results with races to get race information\nmerged_results_races = pd.merge(results, races, on='raceId')\n\n# Filter for 2008 Australian Grand Prix winners (positionOrder = 1)\nwinners = merged_results_races[(merged_results_races['name'] == 'Australian Grand Prix') & \n (merged_results_races['positionOrder'] == 1) & \n (merged_results_races['year'] == 2008)]\n\n# Merge with drivers to get driver information\nresult = pd.merge(winners[['driverId']], drivers[['driverId', 'forename', 'surname', 'url']], on='driverId')\n\n# Select only the required columns\nresult = result[['forename', 'surname', 'url']]", "sql": "SELECT T1.forename, T1.surname, T1.url FROM drivers AS T1 INNER JOIN results AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T3.raceId = T2.raceId WHERE T3.name = 'Australian Grand Prix' AND T2.positionOrder = 1 AND T3.year = 2008", "difficulty": "moderate" }, { "question_id": 939, "question": "How many drivers from the UN participated in the 2008 Australian Grand Prix?", "db_id": "formula_1", "evidence": "nationality equals 'British' in the database;", "code": "import pandas as pd\n\ndef solve_query(drivers, results, races):\n # Ensure the necessary columns exist\n if not all(col in drivers.columns for col in ['driverId', 'nationality']):\n return pd.DataFrame({'count': [0]})\n if not all(col in results.columns for col in ['driverId', 'raceId']):\n return pd.DataFrame({'count': [0]})\n if not all(col in races.columns for col in ['raceId', 'name', 'year']):\n return pd.DataFrame({'count': [0]})\n\n # Filter races for 'Australian Grand Prix' in 2008\n filtered_races = races[(races['name'] == 'Australian Grand Prix') & (races['year'] == 2008)]\n\n if filtered_races.empty:\n return pd.DataFrame({'count': [0]})\n\n # Merge races with results on raceId\n merged_results = pd.merge(filtered_races, results, left_on='raceId', right_on='raceId')\n\n # Merge the above result with drivers on driverId\n final_merge = pd.merge(merged_results, drivers, left_on='driverId', right_on='driverId')\n\n # Filter drivers with nationality 'British'\n british_drivers = final_merge[final_merge['nationality'] == 'British']\n\n # Count the number of unique drivers\n count = british_drivers['driverId'].nunique()\n\n return pd.DataFrame({'count': [count]})\n\n# Example function call\ndrivers_data = pd.DataFrame({\n 'driverId': [1, 2, 3],\n 'nationality': ['British', 'American', 'British']\n})\nresults_data = pd.DataFrame({\n 'resultId': [101, 102, 103],\n 'raceId': [201, 202, 201],\n 'driverId': [1, 2, 3]\n})\nraces_data = pd.DataFrame({\n 'raceId': [201, 202],\n 'name': ['Australian Grand Prix', 'Some Other Race'],\n 'year': [2008, 2009]\n})\n\nresult = solve_query(drivers_data, results_data, races_data)\nprint(result)", "sql": "SELECT COUNT(*) FROM drivers AS T1 INNER JOIN results AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T3.raceId = T2.raceId WHERE T3.name = 'Australian Grand Prix' AND T1.nationality = 'British' AND T3.year = 2008", "difficulty": "moderate" }, { "question_id": 940, "question": "Among the drivers that finished the race in the 2008 Chinese Grand Prix, how many of them have participated in Formula_1 races?", "db_id": "formula_1", "evidence": "COUNT(raceID) > 0 reveals that this driver participated in races; drivers who finished the race refers to time has value.", "code": "import pandas as pd\nresults = pd.read_csv('results.csv')\nraces = pd.read_csv('races.csv')\nmerged_df = pd.merge(results, races, on='raceId')\nfilter_df = merged_df.query('name == \"Chinese Grand Prix\" and year == 2008')\nresult = filter_df[filter_df['time_x'].notna()]['driverId'].nunique()\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.driverId) FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.name = 'Chinese Grand Prix' AND T2.year = 2008 AND T1.time IS NOT NULL", "difficulty": "moderate" }, { "question_id": 941, "question": "How many points did Lewis Hamilton get in total in all the Formula_1 races he participated?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\n\ndrivers_df = pd.read_csv('drivers.csv')\nresults_df = pd.read_csv('results.csv')\n\nlewis_hamilton = drivers_df[(drivers_df['forename'] == 'Lewis') & (drivers_df['surname'] == 'Hamilton')]\n\nif not lewis_hamilton.empty:\n lewis_hamilton_id = lewis_hamilton.iloc[0]['driverId']\n hamilton_results = results_df[results_df['driverId'] == lewis_hamilton_id]\n total_points = hamilton_results['points'].sum()\nelse:\n total_points = 0\n\nresult = pd.DataFrame({'SUM(points)': [total_points]})", "sql": "SELECT SUM(T2.points) FROM drivers AS T1 INNER JOIN results AS T2 ON T1.driverId = T2.driverId WHERE T1.forename = 'Lewis' AND T1.surname = 'Hamilton'", "difficulty": "simple" }, { "question_id": 942, "question": "What is the average fastest lap time in seconds for Lewis Hamilton in all the Formula_1 races?", "db_id": "formula_1", "evidence": "average of fastestLapTime;", "code": "import pandas as pd\nmerged = pd.merge(drivers, results, on='driverId')\nlewis_data = merged[(merged['surname'] == 'Hamilton') & (merged['forename'] == 'Lewis')]\naverage_seconds = lewis_data['milliseconds'].mean() / 1000\nresult = pd.DataFrame({'average_fastest_lap_seconds': [average_seconds]})", "sql": "SELECT AVG(T2.milliseconds/1000.0) \nFROM drivers AS T1 \nINNER JOIN results AS T2 ON T1.driverId = T2.driverId \nWHERE T1.surname = 'Hamilton' AND T1.forename = 'Lewis'", "difficulty": "moderate" }, { "question_id": 943, "question": "What is the rate of drivers completing all the laps in the 2008 Australian Grand Prix?", "db_id": "formula_1", "evidence": "completing all the laps refers to time is not null; rate = divide(COUNT(raceID where time is not null), COUNT(raceID))", "code": "import pandas as pd\n\n# Read the necessary tables\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# Filter races for 2008 Australian Grand Prix\ntarget_race = races[(races['year'] == 2008) & (races['name'] == 'Australian Grand Prix')]\n\nif not target_race.empty:\n race_id = target_race['raceId'].iloc[0]\n \n # Filter results for the target race\n race_results = results[results['raceId'] == race_id]\n \n # Calculate the completion rate based on 'time' column\n total_drivers = len(race_results)\n completed_drivers = race_results['time'].notna().sum()\n completion_rate = (completed_drivers / total_drivers) * 100 if total_drivers > 0 else 0.0\n \n # Create result DataFrame\n result = pd.DataFrame({'completion_rate': [completion_rate]})\nelse:\n # If no race found, return 0 completion rate\n result = pd.DataFrame({'completion_rate': [0.0]})", "sql": "SELECT CAST(SUM(IIF(T1.time IS NOT NULL, 1, 0)) AS REAL) * 100 / COUNT(T1.resultId) FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.name = 'Australian Grand Prix' AND T2.year = 2008", "difficulty": "moderate" }, { "question_id": 944, "question": "How much faster in percentage is the champion than the driver who finished the race last in the 2008 Australian Grand Prix?", "db_id": "formula_1", "evidence": "how much faster in percentage = divide(subtract(incremental time, champion time), last_driver time) * 100; last driver finished time = incremental time + champion time; only champion's finished time is represented by 'HH:MM:SS.mmm'; finished the game refers to time is not null", "code": "import pandas as pd\n\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# 1. 筛选 2008 年 Australian Grand Prix 的比赛 (SQL: WHERE T2.name = 'Australian Grand Prix' AND T2.year = 2008)\ntarget_race = races[(races['year'] == 2008) & (races['name'] == 'Australian Grand Prix')]\nrace_id = target_race['raceId'].iloc[0]\n\n# 2. 筛选该场比赛且时间不为空的成绩 (SQL: WHERE T1.raceId = ... AND T1.time IS NOT NULL)\nrace_results = results[(results['raceId'] == race_id) & (results['time'].notna())]\n\n# 3. 获取冠军的时间 (SQL: positionOrder = 1)\n# 冠军时间格式通常为 \"H:MM:SS.mmm\",对应 SQL: (SUBSTR(1,1)*3600 + SUBSTR(3,2)*60 + SUBSTR(6))\nchampion_row = race_results[race_results['positionOrder'] == 1].iloc[0]\nc_time_str = champion_row['time']\n# 解析 \"1:34:50.616\" -> h, m, s\nc_parts = c_time_str.split(':')\nchampion_seconds = float(c_parts[0]) * 3600 + float(c_parts[1]) * 60 + float(c_parts[2])\n\n# 4. 获取最后一名完赛者的时间 (SQL: MAX(positionOrder))\n# 非冠军的时间通常为增量格式 \"+12.345\",对应 SQL: CAST(SUBSTR(T1.time, 2) AS REAL)\nlast_driver_row = race_results[race_results['positionOrder'] == race_results['positionOrder'].max()].iloc[0]\nl_time_str = last_driver_row['time']\n# 去掉开头的 '+' 号并转为浮点数\ngap_seconds = float(l_time_str.replace('+', ''))\n\n# 5. 计算百分比\n# SQL: (Gap * 100) / (ChampionTime + Gap)\n# 最后一名总时间 = 冠军时间 + 差距时间\ntotal_last_seconds = champion_seconds + gap_seconds\nper = (gap_seconds * 100.0) / total_last_seconds\n\nresult = pd.DataFrame({'per': [per]})\n\nprint(result)", "sql": "WITH time_in_seconds AS ( SELECT T1.positionOrder, CASE WHEN T1.positionOrder = 1 THEN (CAST(SUBSTR(T1.time, 1, 1) AS REAL) * 3600) + (CAST(SUBSTR(T1.time, 3, 2) AS REAL) * 60) + CAST(SUBSTR(T1.time, 6) AS REAL) ELSE CAST(SUBSTR(T1.time, 2) AS REAL) END AS time_seconds FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.name = 'Australian Grand Prix' AND T1.time IS NOT NULL AND T2.year = 2008 ), champion_time AS ( SELECT time_seconds FROM time_in_seconds WHERE positionOrder = 1), last_driver_incremental AS ( SELECT time_seconds FROM time_in_seconds WHERE positionOrder = (SELECT MAX(positionOrder) FROM time_in_seconds) ) SELECT (CAST((SELECT time_seconds FROM last_driver_incremental) AS REAL) * 100) / (SELECT time_seconds + (SELECT time_seconds FROM last_driver_incremental) FROM champion_time)", "difficulty": "challenging" }, { "question_id": 945, "question": "How many circuits are there in Adelaide, Australia?", "db_id": "formula_1", "evidence": "Australia is the country; Melbourne is the location of circuit;", "code": "import pandas as pd\nresult = circuits[(circuits['location'] == 'Adelaide') & (circuits['country'] == 'Australia')].shape[0]", "sql": "SELECT COUNT(circuitId) FROM circuits WHERE location = 'Adelaide' AND country = 'Australia'", "difficulty": "simple" }, { "question_id": 946, "question": "Please list the location coordinates of the US circuits.", "db_id": "formula_1", "evidence": "location coordinates refers to (lat, lng); the US refers to country = 'USA';", "code": "import pandas as pd\nresult = circuits[circuits['country'] == 'USA'][['lat', 'lng']]", "sql": "SELECT lat, lng FROM circuits WHERE country = 'USA'", "difficulty": "simple" }, { "question_id": 947, "question": "How many British drivers were born after 1980?", "db_id": "formula_1", "evidence": "born after 1980 refers to year (dob) >1980;", "code": "import pandas as pd\n\n# Filter British drivers born after 1980\nbritish_drivers = drivers[drivers['nationality'] == 'British']\nbritish_drivers['birth_year'] = pd.to_datetime(british_drivers['dob']).dt.year\nfiltered_drivers = british_drivers[british_drivers['birth_year'] > 1980]\n\n# Count the number of drivers\nresult = len(filtered_drivers)", "sql": "SELECT COUNT(driverId) FROM drivers WHERE nationality = 'British' AND CAST(STRFTIME('%Y', dob) AS INTEGER) > 1980", "difficulty": "simple" }, { "question_id": 948, "question": "What are the maximum points of British constructors?", "db_id": "formula_1", "evidence": "maximum points = MAX(points); British is a nationality", "code": "import pandas as pd\n\n# Read the necessary tables\nconstructor_standings = pd.read_csv('constructorStandings.csv')\nconstructors = pd.read_csv('constructors.csv')\n\n# Join constructorStandings with constructors on constructorId\nmerged_data = pd.merge(constructor_standings, constructors, on='constructorId')\n\n# Filter for British constructors\nbritish_constructors = merged_data[merged_data['nationality'] == 'British']\n\n# Find maximum points\nif not british_constructors.empty:\n max_points = british_constructors['points'].max()\n result = pd.DataFrame({'max_points': [max_points]})\nelse:\n result = pd.DataFrame({'max_points': [0.0]})", "sql": "SELECT MAX(T1.points) FROM constructorStandings AS T1 INNER JOIN constructors AS T2 on T1.constructorId = T2.constructorId WHERE T2.nationality = 'British'", "difficulty": "simple" }, { "question_id": 949, "question": "Which constructor has the highest point?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(constructorStandings, constructors, on='constructorId')\ngrouped = merged.groupby('name')['points'].sum().reset_index()\nresult = grouped.loc[grouped['points'].idxmax()]", "sql": "SELECT T2.name, SUM(T1.points) AS total_points FROM constructorStandings AS T1 INNER JOIN constructors AS T2 ON T1.constructorId = T2.constructorId GROUP BY T2.constructorId ORDER BY total_points DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 950, "question": "Please list the constructor names with 0 points at race 291.", "db_id": "formula_1", "evidence": "race at 291 refers to raceID = 291;", "code": "import pandas as pd\n\n# Read the necessary tables\nconstructor_standings = pd.read_csv('constructorStandings.csv')\nconstructors = pd.read_csv('constructors.csv')\n\n# Filter constructorStandings for raceId = 291 and points = 0\nfiltered_standings = constructor_standings[(constructor_standings['raceId'] == 291) & (constructor_standings['points'] == 0)]\n\n# Join with constructors to get constructor names\nresult_data = pd.merge(filtered_standings, constructors, on='constructorId')\n\n# Select only the constructor names\nresult = result_data[['name']]\n\n# If no results found, return empty DataFrame with correct column name\nif result.empty:\n result = pd.DataFrame(columns=['name'])", "sql": "SELECT T2.name FROM constructorStandings AS T1 INNER JOIN constructors AS T2 ON T1.constructorId = T2.constructorId WHERE T1.points = 0 AND T1.raceId = 291", "difficulty": "simple" }, { "question_id": 951, "question": "How many Japanese constructors have 0 points in 2 races?", "db_id": "formula_1", "evidence": "2 races refers to COUNT(raceID) = 2; Japanese refers to constructors.nationality = 'Japanese';2 races refers to COUNT(raceId) = 2 in HAVING clause; Japanese refers to constructors.nationality = 'Japanese'; final count refers to COUNT(*) of qualifying constructors", "code": "import pandas as pd\nmerged = pd.merge(constructorStandings, constructors, on='constructorId')\nfiltered = merged[(merged['points'] == 0) & (merged['nationality'] == 'Japanese')]\ngrouped = filtered.groupby('constructorId').size().reset_index(name='count')\nresult = len(grouped[grouped['count'] == 2])", "sql": "SELECT COUNT(*) FROM (SELECT T1.constructorId FROM constructorStandings AS T1 INNER JOIN constructors AS T2 ON T1.constructorId = T2.constructorId WHERE T1.points = 0 AND T2.nationality = 'Japanese' GROUP BY T1.constructorId HAVING COUNT(T1.raceId) = 2)", "difficulty": "simple" }, { "question_id": 952, "question": "Which constructors have been ranked 1?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(results, constructors, on='constructorId')\nfiltered = merged[merged['rank'] == 1]\nresult = filtered[['name']].drop_duplicates()", "sql": "SELECT DISTINCT T2.name FROM constructorStandings AS T1 INNER JOIN constructors AS T2 ON T1.constructorId = T2.constructorId WHERE T1.position = 1", "difficulty": "simple" }, { "question_id": 953, "question": "How many French constructors have a lap number of over 50?", "db_id": "formula_1", "evidence": "lap numbers of over 50 refers to laps > 50;", "code": "import pandas as pd\nmerged = pd.merge(results[results['laps'] > 50], constructors[constructors['nationality'] == 'French'], on='constructorId')\nresult = merged['constructorId'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.constructorId) FROM results AS T1 INNER JOIN constructors AS T2 on T1.constructorId = T2.constructorId WHERE T1.laps > 50 AND T2.nationality = 'French'", "difficulty": "simple" }, { "question_id": 954, "question": "Please calculate the race completion percentage of Japanese drivers from 2007 to 2009.", "db_id": "formula_1", "evidence": "from 2007 to 2009 refers to year between 2007 and 2009; race completion refers to time is not null; percentage = Divide(COUNT(DriverID where time is not null and year between 2007 and 2009),Count (DriverID where year between 2007 and 2009))*100; ", "code": "import pandas as pd\n\n# Assuming the DataFrames are already loaded as drivers, constructorResults, and races\ndrivers_japanese = drivers[drivers['nationality'] == 'Japanese'][['driverId']]\nraces_filtered = races[(races['year'] >= 2007) & (races['year'] <= 2009)][['raceId']]\n\n# Merge the data\nmerged_data = results.merge(races_filtered, on='raceId').merge(drivers_japanese, on='driverId')\n\n# Calculate the race completion percentage\ncompleted_races = merged_data['time'].notna().sum()\ntotal_races = len(merged_data)\nrace_completion_percentage = (completed_races / total_races) * 100 if total_races > 0 else 0\n\nresult = race_completion_percentage", "sql": "SELECT CAST(SUM(IIF(T1.time IS NOT NULL, 1, 0)) AS REAL) * 100 / COUNT(T1.raceId) FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN drivers AS T3 ON T1.driverId = T3.driverId WHERE T3.nationality = 'Japanese' AND T2.year BETWEEN 2007 AND 2009", "difficulty": "challenging" }, { "question_id": 955, "question": "What is the average time in seconds of champion for each year, before year 1975?", "db_id": "formula_1", "evidence": "only champion's finished time is represented by 'HH:MM:SS.mmm'; finished the game refers to time is not null; before year 1975 refers to year < 1975;", "code": "import pandas as pd\n\n# 读取数据\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# 合并表 (SQL: FROM results JOIN races)\n# 注意:两个表都有 'time' 列。合并后 results 的变为 time_x,races 的变为 time_y\nmerged = pd.merge(results, races, on='raceId')\n\n# 筛选条件 (SQL: WHERE T1.time IS NOT NULL AND positionOrder = 1 AND year < 1975)\n# T1 是 results 表,对应 time_x\nfiltered = merged[\n (merged['time_x'].notna()) & \n (merged['positionOrder'] == 1) & \n (merged['year'] < 1975)\n].copy()\n\n# 时间转换 (SQL logic: H:MM:SS format)\n# 使用 time_x 进行分割\ntime_split = filtered['time_x'].str.split(':', expand=True)\n\n# 确保分割后有 3 列 (H, M, S)\nif time_split.shape[1] >= 3:\n hours = pd.to_numeric(time_split[0], errors='coerce')\n minutes = pd.to_numeric(time_split[1], errors='coerce')\n seconds = pd.to_numeric(time_split[2], errors='coerce')\n \n # 计算总秒数\n filtered['time_seconds'] = (hours * 3600) + (minutes * 60) + seconds\nelse:\n filtered['time_seconds'] = pd.NA\n\n# 移除转换失败的行\nfiltered = filtered.dropna(subset=['time_seconds'])\n\n# 分组计算平均值 (SQL: GROUP BY year, AVG(time_seconds))\nresult = filtered.groupby('year')['time_seconds'].mean().reset_index()\n\n# 重命名列以匹配语义\nresult = result.rename(columns={'time_seconds': 'avg_champion_time'})\n\nprint(result)", "sql": "WITH time_in_seconds AS ( SELECT T2.year, T1.positionOrder, CASE WHEN T1.positionOrder = 1 THEN (CAST(SUBSTR(T1.time, 1, 1) AS REAL) * 3600) + (CAST(SUBSTR(T1.time, 3, 2) AS REAL) * 60) + CAST(SUBSTR(T1.time, 6) AS REAL) ELSE 0 END AS time_seconds FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T1.time IS NOT NULL ), champion_time AS ( SELECT year, time_seconds FROM time_in_seconds WHERE positionOrder = 1 AND time_seconds > 0 ) SELECT year, AVG(time_seconds) AS avg_champion_time FROM champion_time WHERE year < 1975 GROUP BY year", "difficulty": "challenging" }, { "question_id": 956, "question": "Which drivers born after 1975 have been ranked 2? Please give their forenames and surnames.", "db_id": "formula_1", "evidence": "born after 1975 refers to year(dob) >1975;", "code": "import pandas as pd\n\n# 读取数据\nresults = pd.read_csv('results.csv')\ndrivers = pd.read_csv('drivers.csv')\n\n# 1. 转换 dob 为日期格式 (SQL: STRFTIME('%Y', T2.dob) > '1975')\ndrivers['dob'] = pd.to_datetime(drivers['dob'], errors='coerce')\n\n# 2. 筛选 1975 年以后出生的司机\n# SQL: WHERE STRFTIME('%Y', dob) > '1975'\nfiltered_drivers = drivers[drivers['dob'].dt.year > 1975]\n\n# 3. 合并 drivers 和 results (SQL: FROM results JOIN drivers ON driverId)\nmerged = pd.merge(results, filtered_drivers, on='driverId')\n\n# 4. 筛选排名为 2 的记录 (SQL: AND positionOrder = 2)\nfinal_data = merged[merged['positionOrder'] == 2]\n\n# 5. 选择 forename 和 surname (SQL: SELECT T2.forename, T2.surname)\nresult = final_data[['forename', 'surname']]\n\nprint(result)", "sql": "SELECT T2.forename, T2.surname FROM results AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId WHERE STRFTIME('%Y', T2.dob) > '1975' AND T1.positionOrder = 2", "difficulty": "simple" }, { "question_id": 957, "question": "How many Italian drivers haven't finished the race?", "db_id": "formula_1", "evidence": "haven't finished the race refers to time is null;", "code": "import pandas as pd\nmerged = pd.merge(results, drivers, on='driverId')\nitalian_not_finished = merged[(merged['nationality'] == 'Italian') & (merged['time'].isna())]\nresult = len(italian_not_finished)", "sql": "SELECT COUNT(T1.driverId) FROM results AS T1 INNER JOIN drivers AS T2 on T1.driverId = T2.driverId WHERE T2.nationality = 'Italian' AND T1.time IS NULL", "difficulty": "simple" }, { "question_id": 958, "question": "Which driver has the fastest lap time? Please give their forenames and surnames.", "db_id": "formula_1", "evidence": "results table contains fastestLapTime column; results.driverId refers to drivers.driverId", "code": "import pandas as pd\nvalid_results = results[results['milliseconds'].notnull()]\ngrouped = valid_results.groupby('driverId', as_index=False)['milliseconds'].min()\nmerged = pd.merge(grouped, drivers[['driverId','forename','surname']], on='driverId')\nresult = merged[merged['milliseconds'] == merged['milliseconds'].min()][['forename','surname']].iloc[[0]]", "sql": "SELECT T2.forename, T2.surname, MIN(T1.milliseconds) as fastest_ms FROM results AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T1.raceId = T3.raceId WHERE T1.milliseconds IS NOT NULL GROUP BY T1.driverId ORDER BY fastest_ms ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 959, "question": "What is the fastest lap number of the champion in 2009?", "db_id": "formula_1", "evidence": "in 2009 refers to year = 2009; Only the time of the champion shows in the format of \"hour: minutes: seconds.millionsecond\"", "code": "import pandas as pd\n\n# 加载数据(请根据实际情况修改文件路径)\nraces = pd.read_csv('races.csv')\ndriverStandings = pd.read_csv('driverStandings.csv')\nresults = pd.read_csv('results.csv') # 注意:使用 results 表而非 constructorResults\n\n# 筛选2009年的比赛\nraces_2009 = races[races['year'] == 2009][['raceId']]\n\n# 筛选出2009年每场比赛的冠军车手\nchampions_2009 = driverStandings[\n (driverStandings['position'] == 1) &\n (driverStandings['raceId'].isin(races_2009['raceId']))\n][['raceId', 'driverId']]\n\n# 与 results 表合并以获取最快圈速(修正:使用 results 表)\nmerged_data = champions_2009.merge(results, on=['raceId', 'driverId'])\n\n# 获取最快圈速(如果有数据)\nresult = merged_data['fastestLap'] if not merged_data.empty else None\n\nprint(result)", "sql": "SELECT T1.fastestLap FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN driverStandings AS T3 ON T1.driverId = T3.driverId AND T1.raceId = T3.raceId WHERE T2.year = 2009 AND T3.position = 1;", "difficulty": "simple" }, { "question_id": 960, "question": "What is the average of fastest lap speed in the 2009 Spanish Grand Prix race?", "db_id": "formula_1", "evidence": "Spanish Grand Prix is the name of race refers to name = 'Spanish Grand Prix'; average fastest lap speed refers to avg(fastestLapSpeed);", "code": "import pandas as pd\n\nmerged_data = pd.merge(races, results, on='raceId')\nfiltered_data = merged_data[(merged_data['year'] == 2009) & \n (merged_data['name'] == 'Spanish Grand Prix')]\nresult = filtered_data['fastestLapSpeed'].astype(float).mean()", "sql": "SELECT AVG(T1.fastestLapSpeed) FROM results AS T1 INNER JOIN races AS T2 on T1.raceId = T2.raceId WHERE T2.year = 2009 AND T2.name = 'Spanish Grand Prix'", "difficulty": "moderate" }, { "question_id": 961, "question": "Which race has the shortest actual finishing time? Please give the name and year.", "db_id": "formula_1", "evidence": "shortest actual finishing time refers to Min(milliseconds) except milliseconds = null;", "code": "import pandas as pd\nmerged = pd.merge(races, results, on='raceId')\nfiltered = merged[merged['milliseconds'].notna()]\nshortest = filtered.loc[filtered['milliseconds'].idxmin()]\nresult = pd.DataFrame([{'name': shortest['name'], 'year': shortest['year']}])", "sql": "SELECT T1.name, T1.year FROM races AS T1 INNER JOIN results AS T2 on T1.raceId = T2.raceId WHERE T2.milliseconds IS NOT NULL ORDER BY T2.milliseconds LIMIT 1", "difficulty": "simple" }, { "question_id": 962, "question": "From 2000 to 2005, what percentage of drivers who were born before 1985 and the lap numbers were over 50?", "db_id": "formula_1", "evidence": "born before 1985 refers to year(dob)<1985; in 2000 to 2005 refers to year between 2000 and 2005; percentage = Divide(COUNT(driverId where year (dob) <1985 and laps >50),COUNT(DriverID where year between 2000 and 2005) *100;", "code": "import pandas as pd\nmerged = pd.merge(results, races, on='raceId').merge(drivers, on='driverId')\nfiltered = merged[merged['year'].between(2000, 2005)]\ncondition = (pd.to_datetime(filtered['dob']).dt.year < 1985) & (filtered['laps'] > 50)\ncount_case = filtered[condition]['driverId'].nunique()\ntotal = filtered['driverId'].nunique()\nresult = pd.DataFrame({'percentage': [count_case / total * 100]})", "sql": "SELECT (CAST(COUNT(DISTINCT CASE WHEN STRFTIME('%Y', T3.dob) < '1985' AND T1.laps > 50 THEN T3.driverId END) AS REAL) * 100) / COUNT(DISTINCT T3.driverId) FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN drivers AS T3 ON T1.driverId = T3.driverId WHERE T2.year BETWEEN 2000 AND 2005", "difficulty": "challenging" }, { "question_id": 963, "question": "How many French drivers who obtain the laptime less than 02:00.00?", "db_id": "formula_1", "evidence": "lap time less than 02:00.00 refers to seconds < 120;", "code": "import pandas as pd\nparts = lapTimes['time'].str.split(':')\nminutes = parts.str[0].astype(int) * 60\nseconds_parts = parts.str[1].str.split('.')\nsec = seconds_parts.str[0].astype(int)\nmsec = seconds_parts.str[1].fillna('0').astype(int) / 1000.0\ntotal_seconds = minutes + sec + msec\nmerged = pd.merge(drivers, lapTimes[total_seconds < 120], on='driverId')\nfrench_drivers = merged[merged['nationality'].str.lower() == 'french']\nresult = len(french_drivers)", "sql": "SELECT COUNT(T1.driverId) FROM drivers AS T1 INNER JOIN lapTimes AS T2 ON T1.driverId = T2.driverId WHERE LOWER(T1.nationality) = 'french' AND (CAST(SUBSTR(T2.time, 1, INSTR(T2.time, ':') - 1) AS INTEGER) * 60 + CAST(SUBSTR(T2.time, INSTR(T2.time, ':') + 1, 2) AS INTEGER) + COALESCE(CAST(SUBSTR(T2.time, INSTR(T2.time, '.') + 1) AS REAL), 0) / 1000) < 120;", "difficulty": "moderate" }, { "question_id": 964, "question": "List out the code for drivers who have nationality in America.", "db_id": "formula_1", "evidence": "nationality equals 'America' in the database;", "code": "import pandas as pd\nresult = drivers[drivers['nationality'] == 'America']['code']", "sql": "SELECT code FROM drivers WHERE nationality = 'America'", "difficulty": "simple" }, { "question_id": 965, "question": "List out the Id number of races which were hold in 2009.", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nresult = races[races['year'] == 2009][['raceId']]", "sql": "SELECT raceId FROM races WHERE year = 2009", "difficulty": "simple" }, { "question_id": 966, "question": "How many driver participated in race ID number 18?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nfiltered = results[results['raceId'] == 18]\nresult = filtered['driverId'].nunique()", "sql": "SELECT COUNT(DISTINCT driverId) FROM results WHERE raceId = 18", "difficulty": "simple" }, { "question_id": 967, "question": "State code numbers of top 3 yougest drivers. How many Netherlandic drivers among them?", "db_id": "formula_1", "evidence": "youngest driver refers to Max (year(dob)); Netherlandic and Dutch refer to the same country", "code": "import pandas as pd\n# 假设drivers DataFrame已存在且dob为datetime类型\nyoungest_three = drivers.sort_values('dob', ascending=False).head(3)\nresult = youngest_three[youngest_three['nationality'].isin(['Dutch', 'Netherlandic'])].shape[0]", "sql": "SELECT COUNT(*) FROM ( SELECT nationality FROM drivers ORDER BY CAST(strftime('%Y', dob) AS INTEGER) DESC, dob DESC LIMIT 3 ) WHERE nationality = 'Dutch'", "difficulty": "simple" }, { "question_id": 968, "question": "What is reference name of Robert Kubica?", "db_id": "formula_1", "evidence": "reference name refers to driverRef;", "code": "import pandas as pd\nresult = drivers[(drivers['forename'] == 'Robert') & (drivers['surname'] == 'Kubica')]['driverRef']", "sql": "SELECT driverRef FROM drivers WHERE forename = 'Robert' AND surname = 'Kubica'", "difficulty": "simple" }, { "question_id": 969, "question": "How many British drivers who were born in 1980?", "db_id": "formula_1", "evidence": "born in 1980 refers to year(dob) = 1980;", "code": "import pandas as pd\nresult = drivers[(drivers['nationality'] == 'British') & (pd.to_datetime(drivers['dob']).dt.year == 1980)].shape[0]", "sql": "SELECT COUNT(driverId) FROM drivers WHERE nationality = 'British' AND STRFTIME('%Y', dob) = '1980'", "difficulty": "simple" }, { "question_id": 970, "question": "List out top 3 German drivers who were born from 1980-1990 and have the earliest lap time.", "db_id": "formula_1", "evidence": "born from 1980-1990 refers to year(dob) between 1980 and 1990; earliest lap time refers to Min(time);", "code": "import pandas as pd\nfastest_laps = lapTimes.groupby('driverId')['milliseconds'].min().reset_index()\nmerged = pd.merge(fastest_laps, drivers, on='driverId')\nfiltered = merged[(merged['nationality'] == 'German') & (pd.to_datetime(merged['dob']).dt.year.between(1980, 1990))]\nresult = filtered.sort_values('milliseconds').head(3)", "sql": "SELECT T1.driverId FROM (SELECT driverId, MIN(lapTimes.milliseconds) AS fastest_lap FROM lapTimes GROUP BY driverId) AS T1 INNER JOIN drivers ON T1.driverId = drivers.driverId WHERE drivers.nationality = 'German' AND STRFTIME('%Y', drivers.dob) BETWEEN '1980' AND '1990' ORDER BY T1.fastest_lap LIMIT 3", "difficulty": "moderate" }, { "question_id": 971, "question": "Please state the reference name of the oldest German driver.", "db_id": "formula_1", "evidence": "oldest refers to MIN(year(dob)); reference names appear in drverRef.", "code": "import pandas as pd\ngerman_drivers = drivers[drivers['nationality'] == 'German']\noldest_german = german_drivers.sort_values('dob').iloc[0]\nresult = oldest_german['driverRef']", "sql": "SELECT driverRef FROM drivers WHERE nationality = 'German' ORDER BY dob ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 972, "question": "Which drivers who were born in 1971 and has the fastest lap time on the race? Give id and code of these drivers.", "db_id": "formula_1", "evidence": "born in 1971 refers to year(dob) = 1971; has the fastest lap time refers to fastestLapTime has values", "code": "import pandas as pd\n\n# Convert dob to datetime and extract year\ndrivers['dob'] = pd.to_datetime(drivers['dob'])\ndrivers['dob_year'] = drivers['dob'].dt.year\n\n# Filter drivers born in 1971\ndrivers_1971 = drivers[drivers['dob_year'] == 1971][['driverId', 'code']]\n\n# Filter results for records with fastestLapTime not null\nresults_with_fastest_lap = results[results['fastestLapTime'].notna()][['driverId', 'raceId', 'fastestLapTime']]\n\n# Find the fastest lap time for each race\nfastest_laps_per_race = results_with_fastest_lap.groupby('raceId')['fastestLapTime'].min().reset_index()\n\n# Filter results to include only the fastest lap times\nfastest_results = results_with_fastest_lap.merge(\n fastest_laps_per_race, \n on=['raceId', 'fastestLapTime']\n)\n\n# Merge to find drivers born in 1971 who have the fastest lap times\nresult = drivers_1971.merge(\n fastest_results, \n on='driverId'\n)[['driverId', 'code']].drop_duplicates().sort_values(['driverId'])\n\nprint(result)", "sql": "SELECT T2.driverId, T2.code FROM results AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId WHERE STRFTIME('%Y', T2.dob) = '1971' AND T1.fastestLapTime = (SELECT MIN(fastestLapTime) FROM results AS T3 WHERE T3.raceId = T1.raceId) AND T1.fastestLapTime IS NOT NULL", "difficulty": "moderate" }, { "question_id": 973, "question": "List out top 10 Spanish drivers who were born before 1982 and have the latest lap time.", "db_id": "formula_1", "evidence": "born before 1982 refers to year(dob) < 1982; latest lap time refers to Max(time);latest lap time refers to time from lapTimes table; 'latest' refers to most recent lap", "code": "import pandas as pd\nfiltered_drivers = drivers[(drivers['nationality'] == 'Spanish') & (pd.to_datetime(drivers['dob']).dt.year < 1982)]\nvalid_drivers = filtered_drivers['driverId']\nfiltered_laptimes = lapTimes[lapTimes['driverId'].isin(valid_drivers)]\ngrouped = filtered_laptimes.groupby('driverId')['time'].max().reset_index()\ntop_10 = grouped.sort_values('time', ascending=False).head(10)\nresult = top_10[['driverId']]", "sql": "SELECT T2.driverId FROM lapTimes AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId WHERE T2.nationality = 'Spanish' AND STRFTIME('%Y', T2.dob) < '1982' GROUP BY T2.driverId ORDER BY MAX(T1.time) DESC LIMIT 10", "difficulty": "moderate" }, { "question_id": 974, "question": "State the racing year which has the fastest lap time?", "db_id": "formula_1", "evidence": "'has the fastest lap time?' refers to fastestLapTime has values", "code": "import pandas as pd\n\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# 1. 合并表 (SQL: FROM results JOIN races ON raceId)\nmerged = pd.merge(results, races, on='raceId')\n\n# 2. 筛选 fastestLapTime 不为空的记录 (SQL: WHERE fastestLapTime IS NOT NULL)\nfiltered = merged[merged['fastestLapTime'].notna()]\n\n# 3. 按 milliseconds 升序排序并取第一条 (SQL: ORDER BY milliseconds ASC LIMIT 1)\n# 毫秒数越小,单圈速度越快\nfastest_record = filtered.sort_values('milliseconds', ascending=True).head(1)\n\n# 4. 获取对应的年份 (SQL: SELECT year)\nresult = fastest_record['year']\n\nprint(result)", "sql": "SELECT T2.year FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T1.fastestLapTime IS NOT NULL ORDER BY T1.milliseconds ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 975, "question": "Which year has the lowest speed of lap time?", "db_id": "formula_1", "evidence": "lowest speed of lap time refers to Max(time);", "code": "import pandas as pd\nmerged = pd.merge(lapTimes, races, on='raceId')\ngrouped = merged.groupby('year').agg(max_lap_time=('milliseconds', 'max')).reset_index()\nresult = grouped.sort_values(by='max_lap_time', ascending=False).head(1)", "sql": "SELECT T2.year, MAX(T1.milliseconds) AS max_lap_time FROM lapTimes AS T1 JOIN races AS T2 ON T1.raceId = T2.raceId GROUP BY T2.year ORDER BY max_lap_time DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 976, "question": "List the driver's ID of the top five driver, by descending order, the fastest time during the first lap of the race.", "db_id": "formula_1", "evidence": "fastest time refers to Min(time);", "code": "import pandas as pd\n\n# 加载 lapTimes 数据(请根据实际情况修改文件路径)\nlapTimes = pd.read_csv('lapTimes.csv')\n\n# 筛选第一圈数据并按毫秒升序排序(更快的时间在前)\nfirst_lap_times = lapTimes[lapTimes['lap'] == 1][['driverId', 'milliseconds']]\nsorted_times = first_lap_times.sort_values('milliseconds', ascending=True) # 升序排列\n\n# 获取前5名车手ID\nresult = sorted_times.head(5)['driverId'].reset_index(drop=True)\n\nprint(result)", "sql": "SELECT driverId FROM lapTimes WHERE lap = 1 ORDER BY time LIMIT 5", "difficulty": "simple" }, { "question_id": 977, "question": "From race no. 50 to 100, how many finishers have been disqualified?", "db_id": "formula_1", "evidence": "disqualified refers to statusID = 2, finisher refers to time! = null; race no. refers to raceId; raceId > 50 and raceId < 100;", "code": "import pandas as pd\nfiltered_results = results[(results['statusId'] == 2) & (results['raceId'] > 50) & (results['raceId'] < 100)]\nresult = filtered_results[filtered_results['time'].notna()].shape[0]", "sql": "SELECT SUM(IIF(time IS NOT NULL, 1, 0)) FROM results WHERE statusId = 2 AND raceID < 100 AND raceId > 50", "difficulty": "simple" }, { "question_id": 978, "question": "How many times the circuits were held in Austria? Please give their location and coordinates.", "db_id": "formula_1", "evidence": "location coordinates refers to (lat,lng); Austria refers to country = 'Austria';", "code": "import pandas as pd\nresult = circuits[circuits['country'] == 'Austria'][['location', 'lat', 'lng']].drop_duplicates()", "sql": "SELECT c.location, c.lat, c.lng, COUNT(r.raceId) AS times_held FROM circuits c JOIN races r ON c.circuitId = r.circuitId WHERE c.country = 'Austria' GROUP BY c.circuitId, c.location, c.lat, c.lng", "difficulty": "simple" }, { "question_id": 979, "question": "What race number has the most finishers?", "db_id": "formula_1", "evidence": "finisher refers to time is not null;", "code": "import pandas as pd\nvalid_results = results[results['time'].notnull()]['raceId']\nrace_counts = valid_results.value_counts()\nresult = race_counts.idxmax()", "sql": "SELECT raceId FROM results WHERE time IS NOT NULL GROUP BY raceId ORDER BY COUNT(*) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 980, "question": "List the reference name of the drivers who passed the second qualifying lap during race no. 23. Indicate their nationality and birthday.", "db_id": "formula_1", "evidence": "passed the second qualifying lap refers to q2 is not null; birthday refers to dob; reference name of drivers refers to driverRef; race no. refers to raceId;", "code": "import pandas as pd\nfiltered_qualifying = qualifying[qualifying['raceId'] == 23]\nfiltered_qualifying = filtered_qualifying[filtered_qualifying['q2'].notna()]\nmerged = pd.merge(filtered_qualifying, drivers, on='driverId')\nresult = merged[['driverRef', 'nationality', 'dob']]", "sql": "SELECT T2.driverRef, T2.nationality, T2.dob FROM qualifying AS T1 INNER JOIN drivers AS T2 on T1.driverId = T2.driverId WHERE T1.raceId = 23 AND T1.q2 IS NOT NULL", "difficulty": "moderate" }, { "question_id": 981, "question": "On what year did the youngest driver had his first qualifying race? Also state the name, date and time of the race.", "db_id": "formula_1", "evidence": "date of birth refers to drivers.dob; The larger the birthday value, the younger the person is, and vice versa; first qualifying race refers to MIN(races.date);", "code": "import pandas as pd\n\n# Find the youngest driver (largest dob)\nyoungest_driver = drivers.sort_values('dob', ascending=False).iloc[0]\nyoungest_driver_id = youngest_driver['driverId']\n\n# Get qualifying records for the youngest driver\nyoungest_qualifying = qualifying[qualifying['driverId'] == youngest_driver_id]\n\n# Join with races to get race details\nmerged = pd.merge(youngest_qualifying, races, on='raceId')\n\n# Sort by date to get the first qualifying race\nfirst_qualifying = merged.sort_values('date').iloc[0]\n\n# Create result with required columns\nresult = pd.DataFrame([{\n 'year': first_qualifying['year'],\n 'name': first_qualifying['name'],\n 'date': first_qualifying['date'],\n 'time': first_qualifying['time']\n}])", "sql": "SELECT T3.year, T3.name, T3.date, T3.time FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T1.raceId = T3.raceId WHERE T1.driverId = (SELECT driverId FROM drivers ORDER BY dob DESC LIMIT 1) ORDER BY T3.date ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 982, "question": "How many American drivers have puncture status.", "db_id": "formula_1", "evidence": "puncture status refers to status = Puncture;", "code": "import pandas as pd\n\n# Merge drivers with results\ndf1 = pd.merge(drivers, results, on='driverId')\n\n# Merge with status\ndf2 = pd.merge(df1, status, on='statusId')\n\n# Filter for American drivers with Puncture status\nfiltered = df2[(df2['nationality'] == 'American') & (df2['status'] == 'Puncture')]\n\n# Count unique drivers\nresult = filtered['driverId'].nunique()", "sql": "SELECT COUNT(T1.driverId) FROM drivers AS T1 INNER JOIN results AS T2 on T1.driverId = T2.driverId INNER JOIN status AS T3 on T2.statusId = T3.statusId WHERE T3.status = 'Puncture' AND T1.nationality = 'American'", "difficulty": "simple" }, { "question_id": 983, "question": "Which of the Italian constructor got the highest point to date? Give its introduction website?", "db_id": "formula_1", "evidence": "introduction website refers to url; Italian is a nationality", "code": "import pandas as pd\n\n# Merge constructors with constructorStandings\nmerged = pd.merge(constructors, constructorStandings, on='constructorId')\n\n# Filter for Italian constructors\nitalian = merged[merged['nationality'] == 'Italian']\n\n# Sort by points in descending order and get the top one\nresult = italian.sort_values('points', ascending=False).head(1)[['url']]", "sql": "SELECT T1.url FROM constructors AS T1 INNER JOIN constructorStandings AS T2 on T1.constructorId = T2.constructorId WHERE T1.nationality = 'Italian' ORDER BY T2.points DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 984, "question": "What is the website of the constructor who tallied the most total wins.", "db_id": "formula_1", "evidence": "introduction website refers to url;constructorStandings.wins refers to total wins", "code": "import pandas as pd\nsum_wins = constructorStandings.groupby('constructorId', as_index=False)['wins'].sum()\nmerged = pd.merge(constructors, sum_wins, on='constructorId')\nresult = merged.loc[merged['wins'].idxmax()]['url']", "sql": "SELECT T1.url FROM constructors AS T1 INNER JOIN constructorStandings AS T2 ON T1.constructorId = T2.constructorId GROUP BY T1.constructorId ORDER BY SUM(T2.wins) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 985, "question": "Among the drivers who participated in the French Grand Prix, who has the slowest time in the 3rd lap.", "db_id": "formula_1", "evidence": "slowest time refers to Max(time);", "code": "import pandas as pd\n\n# Filter races for French Grand Prix\nfrench_gp_races = races[races['name'] == 'French Grand Prix'][['raceId']]\n\n# Filter lapTimes for 3rd lap and French Grand Prix races\nlap_times_3rd = lapTimes[\n (lapTimes['lap'] == 3) & \n (lapTimes['raceId'].isin(french_gp_races['raceId']))\n][['driverId', 'time', 'milliseconds']]\n\n# Sort by milliseconds (descending) to get the slowest time\nsorted_times = lap_times_3rd.sort_values('milliseconds', ascending=False)\n\n# Get the driver with the slowest time\nresult = sorted_times.head(1)['driverId'].reset_index(drop=True)", "sql": "SELECT T1.driverId FROM lapTimes AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.name = 'French Grand Prix' AND T1.lap = 3 ORDER BY T1.time DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 986, "question": "In which race did the fastest 1st lap time was recorded? Please indicate the time in milliseconds.", "db_id": "formula_1", "evidence": "fastest refers to Min(time);", "code": "import pandas as pd\nlap_times_filtered = lapTimes[lapTimes['lap'] == 1]\nmerged_data = pd.merge(lap_times_filtered, races, on='raceId')\nresult = merged_data.sort_values('milliseconds').iloc[0][['raceId', 'year', 'name', 'milliseconds']].to_frame().T", "sql": "SELECT T2.raceId, T2.year, T2.name, T1.milliseconds FROM lapTimes AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T1.lap = 1 ORDER BY T1.milliseconds ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 987, "question": "What is the average fastest lap time of the top 10 drivers in the 2006 United States Grand Prix?", "db_id": "formula_1", "evidence": "top 10 refers to rank <11; AVG(fastestLapTime);", "code": "import pandas as pd\n\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\n\n# 1. 筛选 2006 年 United States Grand Prix 的比赛ID\n# SQL: WHERE T2.year = 2006 AND T2.name = 'United States Grand Prix'\nrace_id_df = races[(races['year'] == 2006) & (races['name'] == 'United States Grand Prix')]\nrace_id = race_id_df['raceId'].iloc[0]\n\n# 2. 筛选该比赛且 fastestLapTime 不为空的记录\n# SQL: FROM results AS T1 ... WHERE T1.fastestLapTime IS NOT NULL\nfiltered_results = results[(results['raceId'] == race_id) & (results['fastestLapTime'].notna())].copy()\n\n# 3. 将 fastestLapTime 转换为秒 (格式通常为 MM:SS.mmm 或 M:SS.mmm)\n# 使用向量化字符串操作,不定义函数\n# split 结果列数可能为 2 (M, S) 或 3 (H, M, S),F1 单圈时间通常是 M:SS.mmm\ntime_split = filtered_results['fastestLapTime'].str.split(':', expand=True)\n\n# 处理只有 分:秒 的情况 (绝大多数单圈时间)\nif time_split.shape[1] == 2:\n minutes = pd.to_numeric(time_split[0])\n seconds = pd.to_numeric(time_split[1])\n filtered_results['seconds_total'] = minutes * 60 + seconds\nelif time_split.shape[1] == 3:\n # 极少数情况可能有小时,或者 split 逻辑需要更鲁棒\n hours = pd.to_numeric(time_split[0])\n minutes = pd.to_numeric(time_split[1])\n seconds = pd.to_numeric(time_split[2])\n filtered_results['seconds_total'] = hours * 3600 + minutes * 60 + seconds\nelse:\n # 兜底,假设直接是秒数或者格式不对\n filtered_results['seconds_total'] = pd.to_numeric(filtered_results['fastestLapTime'], errors='coerce')\n\n# 4. 排序并取前 10 名 (SQL: ORDER BY T1.fastestLapTime LIMIT 10)\ntop_10 = filtered_results.sort_values('seconds_total', ascending=True).head(10)\n\n# 5. 计算平均值 (SQL: AVG(fastestLapTime))\nresult = top_10['seconds_total'].mean()\n\nprint(result)", "sql": "SELECT AVG(time_in_seconds) FROM (SELECT (CAST(substr(T1.fastestLapTime, 1, instr(T1.fastestLapTime, ':') - 1) AS REAL) * 60) + CAST(substr(T1.fastestLapTime, instr(T1.fastestLapTime, ':') + 1) AS REAL) AS time_in_seconds FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.year = 2006 AND T2.name = 'United States Grand Prix' AND T1.fastestLapTime IS NOT NULL ORDER BY time_in_seconds ASC LIMIT 10)", "difficulty": "simple" }, { "question_id": 988, "question": "List down top 3 German drivers who has the shortest average pit stop duration and were born between 1980-1985.", "db_id": "formula_1", "evidence": "Full name of the driver refers to drivers.forename and drivers.surname; born between 1980-1985 refers to 1980< year(dob)>1985; Average pitstop duration refers to Divide(SUM(duration),COUNT(duration)); shortest average refers to Min(avg(duration));", "code": "import pandas as pd\npit_stops = pd.read_csv('pitStops.csv')\ndrivers = pd.read_csv('drivers.csv')\nfiltered_drivers = drivers[(drivers['nationality'] == 'German') & (pd.to_datetime(drivers['dob']).dt.year.between(1980, 1985))]\nmerged_data = pd.merge(pit_stops, filtered_drivers, on='driverId')\n# 将duration列转换为数值类型\nmerged_data['duration'] = pd.to_numeric(merged_data['duration'], errors='coerce')\n# 去除duration列中的NaN值\nmerged_data = merged_data.dropna(subset=['duration'])\navg_duration = merged_data.groupby(['driverId', 'forename', 'surname'])['duration'].mean().reset_index()\nresult = avg_duration.sort_values(by='duration', ascending=True).head(3)[['forename', 'surname']]\nprint(result)", "sql": "SELECT T2.forename, T2.surname FROM pitStops AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId WHERE T2.nationality = 'German' AND CAST(STRFTIME('%Y', T2.dob) AS INTEGER) BETWEEN 1980 AND 1985 GROUP BY T2.driverId ORDER BY AVG(CAST(T1.duration AS REAL)) ASC LIMIT 3", "difficulty": "challenging" }, { "question_id": 989, "question": "Who is the champion of the Canadian Grand Prix in 2008? Indicate his finish time.", "db_id": "formula_1", "evidence": "Only the time of the champion shows in the format of \"hour: minutes: seconds.millionsecond\";", "code": "import pandas as pd\n\n# Read the necessary CSV files\ncircuits = pd.read_csv('circuits.csv')\nraces = pd.read_csv('races.csv')\nresults = pd.read_csv('results.csv')\ndrivers = pd.read_csv('drivers.csv')\n\n# Filter the Canadian Grand Prix in 2008\ncanadian_gpk_2008 = races[(races['name'] == 'Canadian Grand Prix') & (races['year'] == 2008)]\n\n# Get the race ID for the Canadian Grand Prix in 2008\nrace_id = canadian_gpk_2008['raceId'].values[0]\n\n# Filter the results for the Canadian Grand Prix in 2008\nrace_results = results[results['raceId'] == race_id]\n\n# Find the champion (position 1) and get his driver ID\nchampion_driver_id = race_results[race_results['position'] == 1]['driverId'].values[0]\n\n# Get the champion's details\nchampion = drivers[drivers['driverId'] == champion_driver_id]\n\n# Get the champion's finish time\nchampion_finish_time = race_results[race_results['driverId'] == champion_driver_id]['time'].values[0]\n\n# Prepare the result\nresult = f\"Champion: {champion['forename'].values[0]} {champion['surname'].values[0]}, Finish Time: {champion_finish_time}\"\n\nprint(result)", "sql": "SELECT T1.time FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.name = 'Canadian Grand Prix' AND T2.year = 2008 AND T1.positionOrder = 1 AND T1.time LIKE '_:%:__.___'", "difficulty": "moderate" }, { "question_id": 990, "question": "What is the constructor reference name of the champion in the 2009 Singapore Grand Prix? Please give its website.", "db_id": "formula_1", "evidence": "the time of the champion shows in the format of \"minutes: seconds.millionsecond\" in which Max(time); constructor reference name refers to constructorRef; website refers to url", "code": "import pandas as pd\n\n# 读取数据\nresults = pd.read_csv('results.csv')\nraces = pd.read_csv('races.csv')\nconstructors = pd.read_csv('constructors.csv')\n\n\n# 执行多表合并,保留原始列名\nmerged_data = pd.merge(\n pd.merge(results, races, on='raceId', suffixes=('_res', '_race')),\n constructors, \n on='constructorId',\n suffixes=('', '_const')\n)\n\n\n# 检查合并后是否存在 'name' 列(通常来自 races 表)\nif 'name_race' in merged_data.columns:\n name_col = 'name_race'\nelif 'name' in merged_data.columns:\n name_col = 'name'\n\n\n# 过滤数据\nfiltered_data = merged_data[\n (merged_data[name_col] == 'Singapore Grand Prix') &\n (merged_data['year'] == 2009) &\n (merged_data['positionOrder'] == 1)\n]\n\n# 获取结果\nresult = filtered_data[['constructorRef', 'url']]\n\nprint(result)", "sql": "SELECT T3.constructorRef, T3.url FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN constructors AS T3 ON T1.constructorId = T3.constructorId WHERE T2.name = 'Singapore Grand Prix' AND T2.year = 2009 AND T1.positionOrder = 1", "difficulty": "challenging" }, { "question_id": 991, "question": "What is the full name and date of birth of Austrian drivers born between 1981 and 1991?", "db_id": "formula_1", "evidence": "Full name refers to forname, surname; Date of birth refers to dob; year(dob) BETWEEN '1981' AND '1991'; Austrian is a nationality", "code": "import pandas as pd\n\n# Filter Austrian drivers born between 1981 and 1991\nresult = drivers[(drivers['nationality'] == 'Austrian') & \n (pd.to_datetime(drivers['dob']).dt.year >= 1981) & \n (pd.to_datetime(drivers['dob']).dt.year <= 1991)][['forename', 'surname', 'dob']]", "sql": "SELECT forename, surname, dob FROM drivers WHERE nationality = 'Austrian' AND STRFTIME('%Y', dob) BETWEEN '1981' AND '1991'", "difficulty": "simple" }, { "question_id": 992, "question": "Find the full name, Wiki Pedia page link, and date of birth of German drivers born between 1971 and 1985. List it in descending order of date of birth.", "db_id": "formula_1", "evidence": "FFull name refers to forname+surname; Nationality refers to German; Date of birth refers to dob; year(dob) BETWEEN '1971' AND '1985'url refers to Wikipedia page link", "code": "import pandas as pd\ndrivers['dob'] = pd.to_datetime(drivers['dob'])\nfiltered = drivers[(drivers['nationality'] == 'German') & (drivers['dob'].dt.year.between(1971, 1985))]\nresult = filtered.assign(full_name=filtered['forename'] + ' ' + filtered['surname']).loc[:, ['full_name', 'url', 'dob']].sort_values('dob', ascending=False)", "sql": "SELECT forename || ' ' || surname AS full_name, url, dob FROM drivers WHERE nationality = 'German' AND CAST(STRFTIME('%Y', dob) AS INTEGER) BETWEEN 1971 AND 1985 ORDER BY dob DESC", "difficulty": "moderate" }, { "question_id": 993, "question": "In which location does the Hungaroring circuit located? Also, find the country and coordinates of this circuit?", "db_id": "formula_1", "evidence": "coordinates expressed in latitude and longitude refers to (lat, lng)[\"Hungaroring circuit name_in_table 'Hungaroring'\"]", "code": "import pandas as pd\nresult = circuits.loc[circuits['name'] == 'Hungaroring', ['location', 'country', 'lat', 'lng']]", "sql": "SELECT location, country, lat, lng FROM circuits WHERE name = 'Hungaroring'", "difficulty": "simple" }, { "question_id": 994, "question": "Which constructor scored most points from Monaco Grand Prix between 1980 and 2010? List the score, name and nationality of this team.", "db_id": "formula_1", "evidence": "Monaco Grand Priz refers to the race; race in year between 1980 and 2010", "code": "import pandas as pd\nimport numpy as np\n\n# Filter races for Monaco Grand Prix between 1980 and 2010\nmonaco_races = races[(races['name'].str.contains('Monaco Grand Prix', case=False, na=False)) & (races['year'] >= 1980) & (races['year'] <= 2010)]\n\n# Join constructorResults with filtered races\nmerged = pd.merge(constructorResults, monaco_races[['raceId']], on='raceId')\n\n# Join with constructors to get name and nationality\nmerged = pd.merge(merged, constructors[['constructorId', 'name', 'nationality']], on='constructorId')\n\n# Group by constructor and sum points\ngrouped = merged.groupby(['constructorId', 'name', 'nationality'])['points'].sum().reset_index()\ngrouped.columns = ['constructorId', 'name', 'nationality', 'total_points']\n\n# Sort by total points descending and get top 1\nresult = grouped.sort_values('total_points', ascending=False).head(1)[['total_points', 'name', 'nationality']]", "sql": "SELECT SUM(T1.points) AS total_points, T2.name, T2.nationality FROM constructorResults AS T1 JOIN constructors AS T2 ON T1.constructorId = T2.constructorId JOIN races AS T3 ON T1.raceId = T3.raceId WHERE T3.name LIKE '%Monaco Grand Prix%' AND T3.year BETWEEN 1980 AND 2010 GROUP BY T2.constructorId ORDER BY total_points DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 995, "question": "What is the average score of Lewis Hamilton among all the Turkish Grand Prix?", "db_id": "formula_1", "evidence": "average of points;", "code": "import pandas as pd\nhamilton = drivers[(drivers['forename'] == 'Lewis') & (drivers['surname'] == 'Hamilton')]\nmerged_results = pd.merge(hamilton, results, on='driverId')\nmerged_races = pd.merge(merged_results, races, on='raceId')\nturkey_results = merged_races[merged_races['name'] == 'Turkish Grand Prix']\naverage_points = turkey_results['points'].mean()\nresult = average_points", "sql": "SELECT AVG(T3.points) FROM drivers AS T1 INNER JOIN results AS T3 ON T1.driverId = T3.driverId INNER JOIN races AS T2 ON T2.raceId = T3.raceId WHERE T1.forename = 'Lewis' AND T1.surname = 'Hamilton' AND T2.name = 'Turkish Grand Prix'", "difficulty": "moderate" }, { "question_id": 996, "question": "What is the annual average number of races held during the first 10 years of the 21st century?", "db_id": "formula_1", "evidence": "date is between '2000-01-01' and '2010-12-31' in the database;year in races table refers to year extracted from date column", "code": "import pandas as pd\nfiltered = races[races['date'].between('2000-01-01', '2009-12-31')]\nresult = len(filtered) / 10.0", "sql": "SELECT CAST(COUNT(*) AS REAL) / 10 FROM races WHERE date BETWEEN '2000-01-01' AND '2009-12-31'", "difficulty": "simple" }, { "question_id": 997, "question": "Which citizenship do the vast majority of the drivers hold?", "db_id": "formula_1", "evidence": "Citizenship of majority of drivers = MAX(nationality); citizenship and nationality are synonyms", "code": "import pandas as pd\nresult = drivers.groupby('nationality').size().reset_index(name='count').sort_values('count', ascending=False).head(1)['nationality'].iloc[0]", "sql": "SELECT nationality FROM drivers GROUP BY nationality ORDER BY COUNT(driverId) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 998, "question": "In terms of number of points acquired, how many victories did the driver who ranked 91st acquired?", "db_id": "formula_1", "evidence": "victories refer to wins; 91st refers to points\n\n", "code": "import pandas as pd\ndriver_standings = pd.read_csv('driverStandings.csv')\nresult = driver_standings[driver_standings['position'] == 91]['wins'].sum()\nprint(result)", "sql": "SELECT SUM(wins) FROM driverStandings WHERE position = 91", "difficulty": "simple" }, { "question_id": 999, "question": "In terms of the fastest lap time, what is the name of the race which recorded the fastest lap speed by a racer?", "db_id": "formula_1", "evidence": "Fastest lap speed refers to MIN(fastestLapTime)", "code": "import pandas as pd\nmerged = pd.merge(races, results, on='raceId')\nfiltered = merged[merged['fastestLapTime'].notna()]\nsorted_data = filtered.sort_values('fastestLapTime')\nresult = sorted_data.iloc[0]['name']", "sql": "SELECT T1.name FROM races AS T1 INNER JOIN (SELECT raceId, MIN(fastestLapTime) AS min_time FROM results WHERE fastestLapTime IS NOT NULL GROUP BY raceId) AS T2 ON T1.raceId = T2.raceId ORDER BY T2.min_time ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1000, "question": "Which racetrack hosted the most recent race? Indicate the full location.", "db_id": "formula_1", "evidence": "full location refers to location+country; most recent race = MAX(date)\n\n", "code": "import pandas as pd\nmerged = pd.merge(circuits, races, on='circuitId', how='inner')\nsorted_races = merged.sort_values('date', ascending=False)\nmost_recent = sorted_races.head(1)\nresult = most_recent.assign(full_location=most_recent['location'] + ', ' + most_recent['country'])", "sql": "SELECT T1.location || ', ' || T1.country AS full_location FROM circuits AS T1 INNER JOIN races AS T2 ON T1.circuitId = T2.circuitId ORDER BY T2.date DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1001, "question": "What is full name of the racer who ranked 1st in the 3rd qualifying race held in the Marina Bay Street Circuit in 2008?", "db_id": "formula_1", "evidence": "Ranked 1st in the 3rd qualifying race refer to MIN(q3); 2008 is the year of race; full name of racer = forename, surname", "code": "import pandas as pd\n\n# Filter for Marina Bay Street Circuit\nmarina_bay_circuit = circuits[circuits['name'] == 'Marina Bay Street Circuit']\ncircuit_id = marina_bay_circuit['circuitId'].iloc[0]\n\n# Filter races for 2008 at Marina Bay\nraces_2008_marina = races[(races['year'] == 2008) & (races['circuitId'] == circuit_id)]\n\n# Get qualifying data for these races\nqualifying_data = pd.merge(qualifying, races_2008_marina[['raceId']], on='raceId')\n\n# Filter for drivers who have q3 times (participated in Q3)\nq3_participants = qualifying_data[qualifying_data['q3'].notna()]\n\n# Join with drivers to get names\nq3_with_drivers = pd.merge(q3_participants, drivers[['driverId', 'forename', 'surname']], on='driverId')\n\n# Convert q3 time string to seconds for sorting\ndef time_to_seconds(time_str):\n if pd.isna(time_str):\n return float('inf')\n parts = time_str.split(':')\n minutes = int(parts[0])\n seconds_parts = parts[1].split('.')\n seconds = float(seconds_parts[0])\n milliseconds = float(seconds_parts[1]) / 1000\n return minutes * 60 + seconds + milliseconds\n\nq3_with_drivers['q3_seconds'] = q3_with_drivers['q3'].apply(time_to_seconds)\n\n# Sort by q3 time and get the fastest (1st ranked)\nfastest = q3_with_drivers.sort_values('q3_seconds').iloc[0]\n\nresult = pd.DataFrame([{'forename': fastest['forename'], 'surname': fastest['surname']}])", "sql": "SELECT d.forename, d.surname FROM qualifying q JOIN drivers d ON q.driverId = d.driverId JOIN races r ON q.raceId = r.raceId JOIN circuits c ON r.circuitId = c.circuitId WHERE r.year = 2008 AND c.name = 'Marina Bay Street Circuit' AND q.position = 1 AND r.round = 3 LIMIT 1", "difficulty": "challenging" }, { "question_id": 1002, "question": "As of the present, what is the full name of the youngest racer? Indicate her nationality and the name of the race to which he/she first joined.", "db_id": "formula_1", "evidence": "full name refers to forename+surname; Youngest racer = MAX(dob)", "code": "import pandas as pd\n# 合并results和races获取比赛日期\nresults_races = pd.merge(results, races, on='raceId')\n# 计算每位车手最早参赛日期\nfirst_race = results_races.groupby('driverId')['date'].min().reset_index()\n# 关联races获取比赛名称\nfirst_race_info = pd.merge(first_race, races, on='date')\n# 关联drivers计算全名\ncombined = pd.merge(drivers, first_race_info, on='driverId')\ncombined['fullname'] = combined['forename'] + ' ' + combined['surname']\n# 按出生日期降序取最年轻车手\nresult = combined.sort_values('dob', ascending=False).iloc[[0]][['fullname', 'nationality', 'name']]", "sql": "SELECT T1.forename||' '||T1.surname AS fullname, T1.nationality, T3.name\nFROM drivers AS T1\nINNER JOIN (\n SELECT driverId, MIN(races.date) as first_date\n FROM results\n INNER JOIN races ON results.raceId = races.raceId\n GROUP BY driverId\n) AS T2 ON T1.driverId = T2.driverId\nINNER JOIN races AS T3 ON T2.first_date = T3.date\nORDER BY T1.dob DESC\nLIMIT 1", "difficulty": "moderate" }, { "question_id": 1003, "question": "How many accidents did the driver who had the highest number accidents in the Canadian Grand Prix have?", "db_id": "formula_1", "evidence": "number of accidents refers to the number where statusid = 3; Canadian Grand Prix refers to the race of name\n", "code": "import pandas as pd\n\n# Merge results with races and status\nmerged = pd.merge(results, races, on='raceId')\nmerged = pd.merge(merged, status, on='statusId')\n\n# Filter for accidents (statusId = 3) and Canadian Grand Prix\naccidents = merged[(merged['statusId'] == 3) & (merged['name'] == 'Canadian Grand Prix')]\n\n# Count accidents by driver\ndriver_accidents = accidents.groupby('driverId').size().reset_index(name='accident_count')\n\n# Get the maximum number of accidents\nresult = driver_accidents['accident_count'].max()", "sql": "SELECT COUNT(T1.driverId) FROM results AS T1 INNER JOIN races AS T2 on T1.raceId = T2.raceId INNER JOIN status AS T3 on T1.statusId = T3.statusId WHERE T3.statusId = 3 AND T2.name = 'Canadian Grand Prix' GROUP BY T1.driverId ORDER BY COUNT(T1.driverId) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1004, "question": "How many wins was achieved by the oldest racer? Indicate his/her full name.", "db_id": "formula_1", "evidence": "oldest racer refers to MIN(dob); full name refers to forename, surname.", "code": "import pandas as pd\n# Convert dob to datetime for proper comparison\ndrivers['dob'] = pd.to_datetime(drivers['dob'])\n# Get earliest birthdate\nmin_dob = drivers['dob'].min()\n# Join tables and filter for oldest driver(s)\nmerged = pd.merge(driverStandings, drivers, on='driverId')\nfiltered = merged[merged['dob'] == min_dob]\n# Aggregate wins and name\nresult = filtered.groupby('driverId').agg(\n total_wins=('wins', 'max'),\n forename=('forename', 'first'),\n surname=('surname', 'first')\n).reset_index()[['total_wins', 'forename', 'surname']]", "sql": "SELECT MAX(T1.wins) AS total_wins, T2.forename, T2.surname FROM driverStandings AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId WHERE T2.dob = (SELECT MIN(dob) FROM drivers) GROUP BY T2.driverId", "difficulty": "simple" }, { "question_id": 1005, "question": "What was the longest time a driver had ever spent at a pit stop?", "db_id": "formula_1", "evidence": "longest time spent at pitstop refers to MAX(duration)", "code": "import pandas as pd\nresult = pitStops.sort_values('duration', ascending=False).head(1)[['duration']]", "sql": "SELECT duration FROM pitStops ORDER BY duration DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1006, "question": "Among all the lap records set on various circuits, what is the time for the fastest one?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nresult = lapTimes.sort_values('milliseconds').iloc[0]['time']", "sql": "SELECT time FROM lapTimes ORDER BY milliseconds ASC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1007, "question": "What was the longest time that Lewis Hamilton had spent at a pit stop?", "db_id": "formula_1", "evidence": "longest time refes to MAX(duration);", "code": "import pandas as pd\n\n# 读取数据\npit_stops = pd.read_csv('pitStops.csv')\ndrivers = pd.read_csv('drivers.csv')\n\n# 1. 筛选 Lewis Hamilton 的 driverId (SQL: WHERE T2.forename = 'Lewis' AND T2.surname = 'Hamilton')\nlewis_driver = drivers[(drivers['forename'] == 'Lewis') & (drivers['surname'] == 'Hamilton')]\ndriver_id = lewis_driver['driverId'].iloc[0]\n\n# 2. 筛选该司机的进站记录 (SQL: FROM pitStops JOIN drivers ON driverId)\nlewis_stops = pit_stops[pit_stops['driverId'] == driver_id].copy()\n\n# 3. 将 duration 转换为数值 (SQL: ORDER BY duration DESC LIMIT 1)\n# 注意:SQL 中 duration 是 TEXT,但在求\"最长\"时间时,物理意义上应该是数值比较。\n# 必须转换为 float 才能正确排序 (避免 \"9.9\" > \"10.0\" 的字典序问题)\nlewis_stops['duration_num'] = pd.to_numeric(lewis_stops['duration'], errors='coerce')\n\n# 4. 获取最大值\nlongest_stop = lewis_stops.sort_values('duration_num', ascending=False).head(1)\n\n# 5. 输出结果 (输出原始的 duration 字符串以保持格式一致,或者输出数值均可,通常保持原格式)\nresult = longest_stop[['duration']]\n\nprint(result)", "sql": "SELECT T1.duration FROM pitStops AS T1 INNER JOIN drivers AS T2 on T1.driverId = T2.driverId WHERE T2.forename = 'Lewis' AND T2.surname = 'Hamilton' ORDER BY T1.duration DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1008, "question": "During which lap did Lewis Hamilton take a pit stop during the 2011 Australian Grand Prix?", "db_id": "formula_1", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(pitStops, drivers, on='driverId')\nmerged = pd.merge(merged, races, on='raceId')\nfiltered = merged[(merged['forename'] == 'Lewis') & (merged['surname'] == 'Hamilton') & (merged['year'] == 2011) & (merged['name'] == 'Australian Grand Prix')]\nresult = filtered[['lap']]", "sql": "SELECT T1.lap FROM pitStops AS T1 INNER JOIN drivers AS T2 on T1.driverId = T2.driverId INNER JOIN races AS T3 on T1.raceId = T3.raceId WHERE T2.forename = 'Lewis' AND T2.surname = 'Hamilton' AND T3.year = 2011 AND T3.name = 'Australian Grand Prix'", "difficulty": "simple" }, { "question_id": 1009, "question": "Please list the time each driver spent at the pit stop during the 2011 Australian Grand Prix.", "db_id": "formula_1", "evidence": "time spent at pit stop refers to durationdriver identifier refers to driverId", "code": "import pandas as pd\nmerged = pd.merge(pitStops, races, on='raceId')\nfiltered = merged[(merged['year'] == 2011) & (merged['name'] == 'Australian Grand Prix')]\nresult = filtered[['driverId', 'duration']]", "sql": "SELECT T1.driverId, T1.duration FROM pitStops AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId WHERE T2.year = 2011 AND T2.name = 'Australian Grand Prix'", "difficulty": "simple" }, { "question_id": 1010, "question": "What is the lap record set by Lewis Hamilton in a Formula_1 race?", "db_id": "formula_1", "evidence": "lap recod means the fastest time recorded which refers to time", "code": "import pandas as pd\nlap_times = pd.read_csv('lapTimes.csv')\ndrivers = pd.read_csv('drivers.csv')\nmerged_data = pd.merge(lap_times, drivers, on='driverId')\nfiltered_data = merged_data[(merged_data['forename'] == 'Lewis') & (merged_data['surname'] == 'Hamilton')]\nresult = filtered_data['time']\nprint(result)", "sql": "SELECT T1.time FROM lapTimes AS T1 INNER JOIN drivers AS T2 on T1.driverId = T2.driverId WHERE T2.forename = 'Lewis' AND T2.surname = 'Hamilton'", "difficulty": "simple" }, { "question_id": 1011, "question": "Which top 20 driver created the shortest lap time ever record in a Formula_1 race? Please give them full names.", "db_id": "formula_1", "evidence": "shortest lap time refers to MIN(time); the time format for the shortest lap time is 'MM:SS.mmm' or 'M:SS.mmm'; full name of the driver refers to forename, surname", "code": "import pandas as pd\nlap_times = pd.read_csv('lapTimes.csv')\ndrivers = pd.read_csv('drivers.csv')\ndef convert_time_to_seconds(time_str):\n if not isinstance(time_str, str) or ':' not in time_str or '.' not in time_str:\n return None\n try:\n minutes, rest = time_str.split(':', 1)\n seconds, milliseconds = rest.split('.', 1)\n total_seconds = int(minutes) * 60 + int(seconds) + int(milliseconds) / 1000\n return total_seconds\n except:\n return None\nlap_times['time_in_seconds'] = lap_times['time'].apply(convert_time_to_seconds)\nfiltered_lap_times = lap_times.dropna(subset=['time_in_seconds'])\nmin_lap_times = filtered_lap_times.groupby('driverId')['time_in_seconds'].min().reset_index()\nresult = pd.merge(min_lap_times, drivers, on='driverId').sort_values(by='time_in_seconds').head(20)[['forename', 'surname']]\nprint(result)", "sql": "WITH lap_times_in_seconds AS (SELECT driverId, (CASE WHEN SUBSTR(time, 1, INSTR(time, ':') - 1) <> '' THEN CAST(SUBSTR(time, 1, INSTR(time, ':') - 1) AS REAL) * 60 ELSE 0 END + CASE WHEN SUBSTR(time, INSTR(time, ':') + 1, INSTR(time, '.') - INSTR(time, ':') - 1) <> '' THEN CAST(SUBSTR(time, INSTR(time, ':') + 1, INSTR(time, '.') - INSTR(time, ':') - 1) AS REAL) ELSE 0 END + CASE WHEN SUBSTR(time, INSTR(time, '.') + 1) <> '' THEN CAST(SUBSTR(time, INSTR(time, '.') + 1) AS REAL) / 1000 ELSE 0 END) AS time_in_seconds FROM lapTimes WHERE time LIKE '%:%.%' AND LENGTH(time) > 0) SELECT T2.forename, T2.surname, T1.driverId FROM (SELECT driverId, MIN(time_in_seconds) AS min_time_in_seconds FROM lap_times_in_seconds) AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId ORDER BY T1.min_time_in_seconds ASC LIMIT 20", "difficulty": "challenging" }, { "question_id": 1012, "question": "What was the position of the circuits during Lewis Hamilton's fastest lap in a Formula_1 race?", "db_id": "formula_1", "evidence": "fastest lap refers to MIN(time)", "code": "import pandas as pd\n\n# 读取数据\nlap_times = pd.read_csv('lapTimes.csv')\ndrivers = pd.read_csv('drivers.csv')\nraces = pd.read_csv('races.csv')\ncircuits = pd.read_csv('circuits.csv')\n\n\n# 执行四表合并\nmerged_data = pd.merge(\n pd.merge(\n pd.merge(lap_times, drivers, on='driverId', suffixes=('_lap', '_driver')),\n races, \n on='raceId',\n suffixes=('_merged', '_race')\n ),\n circuits,\n on='circuitId',\n suffixes=('', '_circuit')\n)\n\n\n\n# 查找可能的单圈时间列名\npossible_time_columns = [\n 'time', 'time_lap', 'lapTime', 'lap_time', 'time_ms', 'duration'\n] # 常见的单圈时间列名变体\n\n# 检测实际存在的时间列\ntime_col = None\nfor col in possible_time_columns:\n if col in merged_data.columns:\n time_col = col\n break\n\nif time_col is None:\n all_columns = merged_data.columns.tolist()\n time_like_columns = [col for col in all_columns if 'time' in col.lower() or 'lap' in col.lower()]\n \n if time_like_columns:\n \n time_col = time_like_columns[0] # 使用第一个匹配的列\n\n\n\n# 过滤数据\nfiltered_data = merged_data[\n (merged_data['forename'] == 'Lewis') &\n (merged_data['surname'] == 'Hamilton')\n]\n\n# 转换时间格式为秒\ndef convert_time_to_seconds(time_str):\n if not isinstance(time_str, str):\n return None\n \n try:\n \n if ':' in time_str and '.' in time_str:\n minutes, rest = time_str.split(':', 1)\n seconds, milliseconds = rest.split('.', 1)\n return int(minutes) * 60 + int(seconds) + int(milliseconds) / 1000\n \n \n elif '.' in time_str:\n parts = time_str.split('.')\n if len(parts) == 2:\n return float(parts[0]) + float(parts[1]) / 1000\n \n \n elif time_str.isdigit():\n return int(time_str) / 1000\n \n return None\n except:\n return None\n\n# 转换时间并过滤无效值\nfiltered_data['time_in_seconds'] = filtered_data[time_col].apply(convert_time_to_seconds)\nfiltered_data = filtered_data.dropna(subset=['time_in_seconds'])\n\n\nresult = filtered_data.sort_values(by='time_in_seconds').head(1)[['name', 'location', 'position']]\nprint(result)", "sql": "SELECT T3.name AS circuit_name, T3.location AS circuit_location, T1.position FROM lapTimes AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T4 ON T1.raceId = T4.raceId INNER JOIN circuits AS T3 ON T4.circuitId = T3.circuitId WHERE T2.forename = 'Lewis' AND T2.surname = 'Hamilton' ORDER BY CAST(T1.time AS REAL) ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1013, "question": "What is the lap record for the Austrian Grand Prix Circuit?", "db_id": "formula_1", "evidence": "lap record means the fastest time recorded which refers to timelap record means the fastest time recorded which refers to fastestLapTime in constructorResults", "code": "import pandas as pd\nraces_circuits = pd.merge(races[['raceId', 'circuitId']], circuits[['circuitId', 'name']], on='circuitId')\nmerged = pd.merge(results, races_circuits, on='raceId')\nfiltered = merged[(merged['name'] == 'Red Bull Ring') & merged['milliseconds'].notnull()]\nresult = filtered[filtered['milliseconds'] == filtered['milliseconds'].min()]['fastestLapTime'].iloc[0]", "sql": "SELECT r.fastestLapTime AS lap_record\nFROM results r\nJOIN races ra ON r.raceId = ra.raceId\nJOIN circuits c ON ra.circuitId = c.circuitId\nWHERE c.name = 'Red Bull Ring'\n AND r.milliseconds IS NOT NULL\n AND r.milliseconds = (\n SELECT MIN(r2.milliseconds)\n FROM results r2\n JOIN races ra2 ON r2.raceId = ra2.raceId\n JOIN circuits c2 ON ra2.circuitId = c2.circuitId\n WHERE c2.name = 'Red Bull Ring'\n AND r2.milliseconds IS NOT NULL\n)\nLIMIT 1;", "difficulty": "simple" }, { "question_id": 1014, "question": "Please list the lap records for the circuits in Italy.", "db_id": "formula_1", "evidence": "lap record means the fastest time recorded which refers to time", "code": "import pandas as pd\n\n# 读取数据\nresults = pd.read_csv('results.csv')\nraces = pd.read_csv('races.csv')\ncircuits = pd.read_csv('circuits.csv')\n# 定义时间转换函数\ndef convert_time_to_seconds(time_str):\n if not isinstance(time_str, str) or ':' not in time_str or '.' not in time_str:\n return None\n try:\n minutes, rest = time_str.split(':', 1)\n seconds, milliseconds = rest.split('.', 1)\n total_seconds = int(minutes) * 60 + int(seconds) + int(milliseconds) / 1000\n return total_seconds\n except:\n return None\n\n# 执行三表合并,显式处理列名冲突\nmerged_data = pd.merge(\n pd.merge(results, races, on='raceId', suffixes=('_res', '_race')),\n circuits,\n on='circuitId',\n suffixes=('', '_circuit')\n)\n# 检测赛道名称列(通常来自 circuits 表)\nif 'name_circuit' in merged_data.columns:\n name_col = 'name_circuit'\nelif 'name' in merged_data.columns:\n name_col = 'name'\nelse:\n # 尝试查找所有可能的 name 列\n name_cols = [col for col in merged_data.columns if 'name' in col]\n if name_cols:\n name_col = name_cols[0] # 使用第一个匹配的列\n# 筛选意大利赛道并处理最快圈速\nitalian_circuits = merged_data[merged_data['country'] == 'Italy']\nitalian_circuits = italian_circuits.dropna(subset=['fastestLapTime'])\nitalian_circuits['time_in_seconds'] = italian_circuits['fastestLapTime'].apply(convert_time_to_seconds)\nitalian_circuits = italian_circuits.dropna(subset=['time_in_seconds'])\n# 计算每个赛道的最快圈速\nmin_times = italian_circuits.groupby('circuitId')['time_in_seconds'].min().reset_index()\n# 关联回原始数据获取完整信息\nresult = pd.merge(\n italian_circuits, \n min_times, \n on=['circuitId', 'time_in_seconds']\n)[[name_col, 'fastestLapTime']] # 使用动态检测的列名\nresult = result.drop_duplicates()\nprint(result)", "sql": "WITH fastest_lap_times AS ( SELECT T1.raceId, T1.FastestLapTime, T2.circuitId, (CAST(SUBSTR(T1.FastestLapTime, 1, INSTR(T1.FastestLapTime, ':') - 1) AS REAL) * 60) + CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, ':') + 1, INSTR(T1.FastestLapTime, '.') - INSTR(T1.FastestLapTime, ':') - 1) AS REAL) + CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, '.') + 1) AS REAL) / 1000 AS time_in_seconds FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN circuits AS T3 ON T2.circuitId = T3.circuitId WHERE T1.FastestLapTime IS NOT NULL AND T3.country = 'Italy' ), min_times AS ( SELECT circuitId, MIN(time_in_seconds) AS min_time FROM fastest_lap_times GROUP BY circuitId ) SELECT DISTINCT T3.name AS circuit_name, T1.FastestLapTime AS lap_record FROM fastest_lap_times AS T1 INNER JOIN min_times AS T2 ON T1.circuitId = T2.circuitId AND T1.time_in_seconds = T2.min_time INNER JOIN circuits AS T3 ON T1.circuitId = T3.circuitId;", "difficulty": "challenging" }, { "question_id": 1015, "question": "In which Formula_1 race was the lap record for the Austrian Grand Prix Circuit set?", "db_id": "formula_1", "evidence": "lap record means the fastest time recorded which refers to time", "code": "import pandas as pd\nresults = pd.read_csv('results.csv')\nraces = pd.read_csv('races.csv')\ncircuits = pd.read_csv('circuits.csv')\n\ndef convert_time_to_seconds(time_str):\n if not isinstance(time_str, str) or ':' not in time_str or '.' not in time_str:\n return None\n try:\n minutes, rest = time_str.split(':', 1)\n seconds, milliseconds = rest.split('.', 1)\n total_seconds = int(minutes) * 60 + int(seconds) + int(milliseconds) / 1000\n return total_seconds\n except:\n return None\n\nmerged_data = pd.merge(pd.merge(results, races, on='raceId'), circuits, on='circuitId')\n\naustrian_races = merged_data[merged_data['name_x'] == 'Austrian Grand Prix']\naustrian_races = austrian_races.dropna(subset=['fastestLapTime'])\n\naustrian_races['time_in_seconds'] = austrian_races['fastestLapTime'].apply(convert_time_to_seconds)\naustrian_races = austrian_races.dropna(subset=['time_in_seconds'])\n\nmin_time = austrian_races['time_in_seconds'].min()\n\nresult = austrian_races[austrian_races['time_in_seconds'] == min_time][['name_x']].drop_duplicates()\n\nprint(result)", "sql": "WITH fastest_lap_times AS ( SELECT T1.raceId, T1.FastestLapTime, (CAST(SUBSTR(T1.FastestLapTime, 1, INSTR(T1.FastestLapTime, ':') - 1) AS REAL) * 60) + (CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, ':') + 1, INSTR(T1.FastestLapTime, '.') - INSTR(T1.FastestLapTime, ':') - 1) AS REAL)) + (CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, '.') + 1) AS REAL) / 1000) AS time_in_seconds FROM results AS T1 WHERE T1.FastestLapTime IS NOT NULL ) SELECT DISTINCT T2.name FROM races AS T2 INNER JOIN circuits AS T3 ON T2.circuitId = T3.circuitId INNER JOIN fastest_lap_times AS FLT ON T2.raceId = FLT.raceId WHERE T2.name = 'Austrian Grand Prix' AND FLT.time_in_seconds = (SELECT MIN(FLT2.time_in_seconds) FROM fastest_lap_times AS FLT2 INNER JOIN races AS R ON FLT2.raceId = R.raceId WHERE R.name = 'Austrian Grand Prix')", "difficulty": "moderate" }, { "question_id": 1016, "question": "In the race a driver set the lap record for the Austrian Grand Prix Circuit, how long did he spent at the pit stop at that same race?", "db_id": "formula_1", "evidence": "lap record means the fastest time recorded which refers to time, how long spent at pitstop refers to duration", "code": "import pandas as pd\n\n# Convert fastest lap time to seconds\nresults_with_time = results[results['fastestLapTime'].notnull()].copy()\nresults_with_time['time_in_seconds'] = (\n results_with_time['fastestLapTime'].str.split(':').str[0].astype(float) * 60 +\n results_with_time['fastestLapTime'].str.split(':').str[1].str.split('.').str[0].astype(float) +\n results_with_time['fastestLapTime'].str.split(':').str[1].str.split('.').str[1].astype(float) / 1000\n)\n\n# Find Austrian GP races\nmerged = pd.merge(results_with_time, races, on='raceId')\naustrian_races = merged[merged['name'] == 'Austrian Grand Prix']\n\n# Get fastest lap record\nmin_time = austrian_races['time_in_seconds'].min()\nrecord_race = austrian_races[austrian_races['time_in_seconds'] == min_time][['raceId', 'driverId']]\n\n# Get pit stop duration\nresult = pd.merge(record_race, pitStops, on=['raceId', 'driverId'])[['duration']]", "sql": "WITH fastest_lap_times AS ( SELECT T1.raceId, T1.driverId, T1.FastestLapTime, (CAST(SUBSTR(T1.FastestLapTime, 1, INSTR(T1.FastestLapTime, ':') - 1) AS REAL) * 60) + (CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, ':') + 1, INSTR(T1.FastestLapTime, '.') - INSTR(T1.FastestLapTime, ':') - 1) AS REAL)) + (CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, '.') + 1) AS REAL) / 1000) as time_in_seconds FROM results AS T1 WHERE T1.FastestLapTime IS NOT NULL), lap_record_race AS ( SELECT T1.raceId, T1.driverId FROM results AS T1 INNER JOIN races AS T2 on T1.raceId = T2.raceId INNER JOIN circuits AS T3 on T2.circuitId = T3.circuitId INNER JOIN ( SELECT MIN(fastest_lap_times.time_in_seconds) as min_time_in_seconds FROM fastest_lap_times INNER JOIN races AS T2 on fastest_lap_times.raceId = T2.raceId INNER JOIN circuits AS T3 on T2.circuitId = T3.circuitId WHERE T2.name = 'Austrian Grand Prix') AS T4 ON (CAST(SUBSTR(T1.FastestLapTime, 1, INSTR(T1.FastestLapTime, ':') - 1) AS REAL) * 60) + (CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, ':') + 1, INSTR(T1.FastestLapTime, '.') - INSTR(T1.FastestLapTime, ':') - 1) AS REAL)) + (CAST(SUBSTR(T1.FastestLapTime, INSTR(T1.FastestLapTime, '.') + 1) AS REAL) / 1000) = T4.min_time_in_seconds WHERE T2.name = 'Austrian Grand Prix') SELECT T4.duration FROM lap_record_race INNER JOIN pitStops AS T4 on lap_record_race.raceId = T4.raceId AND lap_record_race.driverId = T4.driverId", "difficulty": "challenging" }, { "question_id": 1017, "question": "Please list the location coordinates of the circuits whose lap record is 1:29.488.", "db_id": "formula_1", "evidence": "lap records means the fastest time recorded which refers to time; coordinates are expressed as latitude and longitude which refers to (lat, lng)", "code": "import pandas as pd\n\n# Read the CSV files\ndf_circuits = pd.read_csv('circuits.csv')\ndf_races = pd.read_csv('races.csv')\ndf_lap_times = pd.read_csv('lapTimes.csv')\n\n# SQL: WHERE T1.time = '1:29.488'\n# Filter the lapTimes table (T1) directly. \n# This matches the SQL WHERE clause exactly and avoids calculating minimums.\ntarget_laps = df_lap_times[df_lap_times['time'] == '1:29.488']\n\n# SQL: INNER JOIN races AS T2 on T1.raceId = T2.raceId\n# Merge filtered laps with races\nmerged_races = pd.merge(target_laps, df_races, on='raceId')\n\n# SQL: INNER JOIN circuits AS T3 on T2.circuitId = T3.circuitId\n# Merge with circuits to get location data\nmerged_final = pd.merge(merged_races, df_circuits, on='circuitId')\n\n# SQL: SELECT T3.lat, T3.lng\nresult = merged_final[['lat', 'lng']].values.tolist()\n\nprint(result)", "sql": "SELECT T3.lat, T3.lng FROM lapTimes AS T1 INNER JOIN races AS T2 on T1.raceId = T2.raceId INNER JOIN circuits AS T3 on T2.circuitId = T3.circuitId WHERE T1.time = '1:29.488'", "difficulty": "moderate" }, { "question_id": 1018, "question": "What was the average time in milliseconds Lewis Hamilton spent at a pit stop during Formula_1 races?", "db_id": "formula_1", "evidence": "average of milliseconds;", "code": "import pandas as pd\nmerged = pd.merge(pitStops, drivers, on='driverId')\nfiltered = merged[(merged['forename'] == 'Lewis') & (merged['surname'] == 'Hamilton')]\nresult = filtered['milliseconds'].mean()", "sql": "SELECT AVG(T1.milliseconds) FROM pitStops AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T1.raceId = T3.raceId WHERE T2.forename = 'Lewis' AND T2.surname = 'Hamilton'", "difficulty": "simple" }, { "question_id": 1019, "question": "What is the average lap time in milliseconds of all the lap records set on the various circuits in Italy?", "db_id": "formula_1", "evidence": "average of milliseconds;", "code": "import pandas as pd\nmerged = pd.merge(lapTimes, races, on='raceId')\nmerged = pd.merge(merged, circuits, on='circuitId')\nfiltered = merged[merged['country'] == 'Italy']\nresult = filtered['milliseconds'].mean()", "sql": "SELECT AVG(T1.milliseconds) FROM lapTimes AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN circuits AS T3 ON T2.circuitId = T3.circuitId WHERE T3.country = 'Italy'", "difficulty": "moderate" }, { "question_id": 1020, "question": "Which player has the highest overall rating? Indicate the player's api id.", "db_id": "european_football_2", "evidence": "highest overall rating refers to MAX(overall_rating);", "code": "import pandas as pd\ndf = pd.read_csv('Player_Attributes.csv')\nresult = df.sort_values(by='overall_rating', ascending=False).head(1)['player_api_id'].iloc[0]", "sql": "SELECT player_api_id FROM Player_Attributes ORDER BY overall_rating DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1021, "question": "What is the height of the tallest player? Indicate his name.", "db_id": "european_football_2", "evidence": "tallest player refers to MAX(height);", "code": "import pandas as pd\nresult = Player.sort_values('height', ascending=False).head(1)[['player_name', 'height']]", "sql": "SELECT player_name, height FROM Player ORDER BY height DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1022, "question": "What is the preferred foot when attacking of the player with the lowest potential?", "db_id": "european_football_2", "evidence": "preferred foot when attacking refers to preferred_foot; lowest potential refers to MIN(potential);", "code": "import pandas as pd\ndf = pd.read_csv('Player_Attributes.csv')\nfiltered_df = df[df['potential'].notna()]\nsorted_df = filtered_df.sort_values(by='potential', ascending=True)\nresult = sorted_df.head(1)['preferred_foot'].iloc[0]", "sql": "SELECT preferred_foot FROM Player_Attributes WHERE potential IS NOT NULL ORDER BY potential ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1023, "question": "Among the players with an overall rating between 60 to 65, how many players whose going to be in all of your attack moves instead of defensing?", "db_id": "european_football_2", "evidence": "overall_rating > = 60 AND overall_rating < 65; players whose going to be in all of your attack moves instead of defensing refers to defensive_work_rate = 'low';", "code": "import pandas as pd\ndf = pd.read_csv('Player_Attributes.csv')\nfiltered_df = df[(df['overall_rating'] >= 60) & (df['overall_rating'] <= 65) & (df['defensive_work_rate'] == 'low')]\nresult = len(filtered_df)", "sql": "SELECT COUNT(id) FROM Player_Attributes WHERE overall_rating BETWEEN 60 AND 65 AND defensive_work_rate = 'low'", "difficulty": "moderate" }, { "question_id": 1024, "question": "Who are the top 5 players who perform better in crossing actions? Indicate their player id.", "db_id": "european_football_2", "evidence": "perform better in crossing actions refers to MAX(crossing)", "code": "import pandas as pd\nsorted_players = Player_Attributes.sort_values('crossing', ascending=False)\nresult = sorted_players[['player_api_id']].head(5)", "sql": "SELECT player_api_id FROM Player_Attributes ORDER BY crossing DESC LIMIT 5", "difficulty": "simple" }, { "question_id": 1025, "question": "Give the name of the league had the most goals in the 2016 season?", "db_id": "european_football_2", "evidence": "league that had the most goals refers to MAX(SUM(home_team_goal, away_team_goal)); 2016 season refers to season = '2015/2016';", "code": "import pandas as pd\nmatch_df = pd.read_csv('Match.csv')\nleague_df = pd.read_csv('League.csv')\nfiltered_matches = match_df[match_df['season'] == '2015/2016']\nmerged_df = pd.merge(filtered_matches, league_df, left_on='league_id', right_on='id')\ngrouped_df = merged_df.groupby('name').agg({'home_team_goal': 'sum', 'away_team_goal': 'sum'}).reset_index()\ngrouped_df['total_goals'] = grouped_df['home_team_goal'] + grouped_df['away_team_goal']\nsorted_df = grouped_df.sort_values(by='total_goals', ascending=False)\nresult = sorted_df.head(1)['name'].iloc[0]", "sql": "SELECT t2.name FROM Match AS t1 INNER JOIN League AS t2 ON t1.league_id = t2.id WHERE t1.season = '2015/2016' GROUP BY t2.name ORDER BY SUM(t1.home_team_goal + t1.away_team_goal) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1026, "question": "Which home team had lost the fewest matches in the 2016 season?", "db_id": "european_football_2", "evidence": "home team lost the matches refers to SUBTRACT(home_team_goal, away_team_goal) < 0; 2016 season refers to season = '2015/2016';", "code": "import pandas as pd\nmatch_df = pd.read_csv('Match.csv')\nteam_df = pd.read_csv('Team.csv')\nfiltered_data = match_df[(match_df['season'] == '2015/2016') &(match_df['home_team_goal'] < match_df['away_team_goal'])]\nmerged_df = pd.merge(filtered_data, team_df, left_on='home_team_api_id', right_on='team_api_id')\ngrouped = merged_df.groupby(['home_team_api_id', 'team_long_name']).size().reset_index(name='losses')\nresult = grouped.sort_values(['losses', 'home_team_api_id'], ascending=[True, True]).head(1)['team_long_name'].iloc[0]", "sql": "SELECT teamDetails.team_long_name FROM Match AS matchData INNER JOIN Team AS teamDetails ON matchData.home_team_api_id = teamDetails.team_api_id WHERE matchData.season = '2015/2016' AND matchData.home_team_goal - matchData.away_team_goal < 0 GROUP BY matchData.home_team_api_id ORDER BY COUNT(*) ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1027, "question": "Indicate the full names of the top 10 players with the highest number of penalties.", "db_id": "european_football_2", "evidence": "full name refers to player_name; players with highest number of penalties refers to MAX(penalties);", "code": "import pandas as pd\npenalty_max = Player_Attributes.groupby('player_api_id')['penalties'].max().reset_index()\nmerged = pd.merge(penalty_max, Player, on='player_api_id')\nresult = merged.sort_values('penalties', ascending=False).head(10)['player_name']", "sql": "SELECT p.player_name FROM Player AS p INNER JOIN (SELECT player_api_id, MAX(penalties) AS max_penalties FROM Player_Attributes GROUP BY player_api_id) AS pa ON p.player_api_id = pa.player_api_id ORDER BY pa.max_penalties DESC LIMIT 10", "difficulty": "simple" }, { "question_id": 1028, "question": "In Scotland Premier League, which away team won the most during the 2010 season?", "db_id": "european_football_2", "evidence": "Final result should return the Team.team_long_name; Scotland Premier League refers to League.name = 'Scotland Premier League'; away team refers to away_team_api_id; away team that won the most refers to MAX(SUBTRACT(away_team_goal, home_team_goal) > 0); 2010 season refers to season = '2009/2010'; won the most refers to MAX(COUNT(*));", "code": "import pandas as pd\nleague_df = pd.read_csv('League.csv')\nmatch_df = pd.read_csv('Match.csv')\nteam_df = pd.read_csv('Team.csv')\nfiltered_matches = match_df[(match_df['season'] == '2009/2010') & (match_df['away_team_goal'] > match_df['home_team_goal'])]\nmerged_with_league = pd.merge(filtered_matches, league_df, left_on='league_id', right_on='id')\nscotland_matches = merged_with_league[merged_with_league['name'] == 'Scotland Premier League']\nmerged_with_team = pd.merge(scotland_matches, team_df, left_on='away_team_api_id', right_on='team_api_id')\ngrouped_df = merged_with_team.groupby(['away_team_api_id', 'team_long_name']).size().reset_index(name='wins')\nsorted_df = grouped_df.sort_values(['wins', 'away_team_api_id'], ascending=[False, False])\nresult = sorted_df.head(1)['team_long_name'].iloc[0]", "sql": "SELECT teamInfo.team_long_name FROM League AS leagueData INNER JOIN Match AS matchData ON leagueData.id = matchData.league_id INNER JOIN Team AS teamInfo ON matchData.away_team_api_id = teamInfo.team_api_id WHERE leagueData.name = 'Scotland Premier League' AND matchData.season = '2009/2010' AND matchData.away_team_goal - matchData.home_team_goal > 0 GROUP BY matchData.away_team_api_id ORDER BY COUNT(*) DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1029, "question": "What are the speed in which attacks are put together of the top 4 teams with the highest build Up Play Speed?", "db_id": "european_football_2", "evidence": "speed in which attacks are put together refers to buildUpPlaySpeed;highest build up play speed refers to MAX(buildUpPlaySpeed)", "code": "import pandas as pd\ndf = pd.read_csv('Team_Attributes.csv')\nsorted_df = df.sort_values(by='buildUpPlaySpeed', ascending=False)\ntop_4 = sorted_df.head(4)\nresult = top_4['buildUpPlaySpeed'].tolist()", "sql": "SELECT buildUpPlaySpeed FROM Team_Attributes ORDER BY buildUpPlaySpeed DESC LIMIT 4", "difficulty": "moderate" }, { "question_id": 1030, "question": "Give the name of the league had the most matches end as draw in the 2016 season?", "db_id": "european_football_2", "evidence": "most matches end as draw refers to MAX(SUM(home_team_goal = away_team_goal)); 2016 season refers to season = '2015/2016';", "code": "import pandas as pd\n\n# Filter matches from 2015/2016 season where home and away goals are equal (draws)\ndraws = Match[Match['season'] == '2015/2016']\ndraws = draws[draws['home_team_goal'] == draws['away_team_goal']]\n\n# Merge with League table to get league names\ndraws_with_league = pd.merge(draws, League, left_on='league_id', right_on='id')\n\n# Group by league name and count matches\nleague_draws = draws_with_league.groupby('name').size().reset_index(name='draw_count')\n\n# Sort by draw count descending and get the top league\nresult = league_draws.sort_values('draw_count', ascending=False).head(1)['name'].values[0]", "sql": "SELECT t2.name FROM Match AS t1 INNER JOIN League AS t2 ON t1.league_id = t2.id WHERE t1.season = '2015/2016' AND t1.home_team_goal = t1.away_team_goal GROUP BY t2.name ORDER BY COUNT(t1.id) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1031, "question": "At present, calculate for the player's age who have a sprint speed of no less than 97 between 2013 to 2015.", "db_id": "european_football_2", "evidence": "players age at present = SUBTRACT((DATETIME(), birthday)); sprint speed of no less than 97 refers to sprint_speed > = 97; between 2013 to 2015 refers to YEAR(date) > = '2013' AND YEAR(date) < = '2015'; ", "code": "import pandas as pd\n\n# Read the necessary CSV files\nplayer_attributes_df = pd.read_csv('Player_Attributes.csv')\nplayer_df = pd.read_csv('Player.csv')\n\n# Filter player attributes for sprint speed >= 97 and date between 2013 to 2015\nfiltered_attributes_df = player_attributes_df[\n (player_attributes_df['sprint_speed'] >= 97) &\n (player_attributes_df['date'].str.contains('2013|2014|2015'))\n]\n\n# Merge with player DataFrame to get player names and birthdays\nmerged_df = pd.merge(filtered_attributes_df, player_df, on='player_api_id')\n\n# Calculate current age\nfrom datetime import datetime\n\ncurrent_year = datetime.now().year\nmerged_df['age'] = current_year - pd.to_datetime(merged_df['birthday']).dt.year\n\n# Select distinct player names and their ages\nresult = merged_df[['player_name', 'age']].drop_duplicates()\n\n# Print the result\nprint(result)", "sql": "SELECT DISTINCT DATETIME() - T2.birthday age FROM Player_Attributes AS t1 INNER JOIN Player AS t2 ON t1.player_api_id = t2.player_api_id WHERE STRFTIME('%Y',t1.`date`) >= '2013' AND STRFTIME('%Y',t1.`date`) <= '2015' AND t1.sprint_speed >= 97", "difficulty": "challenging" }, { "question_id": 1032, "question": "Give the name of the league with the highest matches of all time and how many matches were played in the said league.", "db_id": "european_football_2", "evidence": " league with highest matches of all time refers to MAX(COUNT(league_id));", "code": "import pandas as pd\n\n# Read tables\nmatch_df = pd.read_csv('Match.csv')\nleague_df = pd.read_csv('League.csv')\n\n# Group matches by league_id and count the number of matches in each league\nleague_match_counts = match_df['league_id'].value_counts().reset_index()\nleague_match_counts.columns = ['league_id', 'match_count']\n\n# Merge with League table to get the league names\nresult = pd.merge(league_match_counts, league_df, left_on='league_id', right_on='id')[['name', 'match_count']]\n\n# Sort by match_count in descending order and get the top league\nresult = result.sort_values(by='match_count', ascending=False).head(1)\n\nprint(result)", "sql": "SELECT t2.name, t1.max_count FROM League AS t2 JOIN (SELECT league_id, MAX(cnt) AS max_count FROM (SELECT league_id, COUNT(id) AS cnt FROM Match GROUP BY league_id) AS subquery) AS t1 ON t1.league_id = t2.id", "difficulty": "moderate" }, { "question_id": 1033, "question": "What is the average height of players born between 1990 and 1995?", "db_id": "european_football_2", "evidence": "average height = DIVIDE(SUM(height), COUNT(id)); players born between 1990 and 1995 refers to birthday > = '1990-01-01 00:00:00' AND birthday < '1996-01-01 00:00:00';", "code": "import pandas as pd\nplayer = Player\nfiltered = player[(player['birthday'] >= '1990-01-01') & (player['birthday'] < '1996-01-01')]\nresult = filtered['height'].sum() / filtered['id'].count()", "sql": "SELECT SUM(height) / COUNT(id) FROM Player WHERE SUBSTR(birthday, 1, 4) BETWEEN '1990' AND '1995'", "difficulty": "simple" }, { "question_id": 1034, "question": "List the players' api id who had the highest above average overall ratings in 2010.", "db_id": "european_football_2", "evidence": "highest above average overall ratings refers to MAX(overall_rating); in 2010 refers to substr(date,1,4) = '2010';", "code": "import pandas as pd\ndf = pd.read_csv('Player_Attributes.csv')\ndf['date'] = pd.to_datetime(df['date'])\nfiltered_df = df[df['date'].dt.year == 2010]\navg_rating = filtered_df['overall_rating'].mean()\nabove_avg_df = filtered_df[filtered_df['overall_rating'] > avg_rating]\nsorted_df = above_avg_df.sort_values(by='overall_rating', ascending=False)\nresult = sorted_df.head(1)['player_api_id'].iloc[0]", "sql": "SELECT player_api_id FROM Player_Attributes WHERE SUBSTR(`date`, 1, 4) = '2010' AND overall_rating > (SELECT AVG(overall_rating) FROM Player_Attributes WHERE SUBSTR(`date`, 1, 4) = '2010') ORDER BY overall_rating DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1035, "question": "Give the team_fifa_api_id of teams with more than 50 but less than 60 build-up play speed.", "db_id": "european_football_2", "evidence": "teams with more than 50 but less than 60 build-up play speed refers to buildUpPlaySpeed >50 AND buildUpPlaySpeed <60; ", "code": "import pandas as pd\ndf = pd.read_csv('Team_Attributes.csv')\nfiltered_df = df[(df['buildUpPlaySpeed'] > 50) & (df['buildUpPlaySpeed'] < 60)]\nresult = filtered_df[['team_fifa_api_id']].drop_duplicates()['team_fifa_api_id'].tolist()", "sql": "SELECT DISTINCT team_fifa_api_id FROM Team_Attributes WHERE buildUpPlaySpeed > 50 AND buildUpPlaySpeed < 60", "difficulty": "simple" }, { "question_id": 1036, "question": "List the long name of teams with above-average build-up play passing in 2012.", "db_id": "european_football_2", "evidence": "long name of teams refers to team_long_name; build-up play passing refers to buildUpPlayPassing; above-average build-up play passing = buildUpPlayPassing > DIVIDE(SUM(buildUpPlayPassing), COUNT(team_long_name) WHERE buildUpPlayPassing IS NOT NULL); in 2012 refers to strftime('%Y', date) = '2012'; ", "code": "import pandas as pd\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df['date'] = pd.to_datetime(team_attributes_df['date'])\nfiltered_attributes = team_attributes_df[team_attributes_df['date'].dt.year == 2012]\nmerged_df = pd.merge(filtered_attributes, team_df, on='team_api_id')\navg_passing = filtered_attributes['buildUpPlayPassing'].mean()\nabove_avg_teams = merged_df[merged_df['buildUpPlayPassing'] > avg_passing]\nresult = above_avg_teams[['team_long_name']].drop_duplicates()['team_long_name'].tolist()", "sql": "SELECT DISTINCT t4.team_long_name FROM Team_Attributes AS t3 INNER JOIN Team AS t4 ON t3.team_api_id = t4.team_api_id WHERE SUBSTR(t3.`date`, 1, 4) = '2012' AND t3.buildUpPlayPassing > ( SELECT CAST(SUM(t2.buildUpPlayPassing) AS REAL) / COUNT(t1.id) FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE STRFTIME('%Y',t2.`date`) = '2012')", "difficulty": "challenging" }, { "question_id": 1037, "question": "Calculate the percentage of players who prefer left foot, who were born between 1987 and 1992.", "db_id": "european_football_2", "evidence": "players who prefer left foot refers to preferred_foot = 'left'; percentage of players who prefer left foot = DIVIDE(MULTIPLY((SUM(preferred_foot = 'left'), 100)), COUNT(player_fifa_api_id)); born between 1987 and 1992 refers to YEAR(birthday) BETWEEN '1987' AND '1992';percentage of players who prefer left foot = DIVIDE(MULTIPLY(COUNT(DISTINCT CASE WHEN preferred_foot = 'left' THEN player_api_id END), 100), COUNT(DISTINCT player_api_id)); born between 1987 and 1992 refers to YEAR(birthday) BETWEEN 1987 AND 1992", "code": "import pandas as pd\n\n# Load the necessary tables\nplayer_attributes = pd.read_csv('Player_Attributes.csv')\nplayers = pd.read_csv('Player.csv')\n\n# Filter players born between 1987 and 1992\nplayers['birthday'] = pd.to_datetime(players['birthday'])\nfiltered_players = players[(players['birthday'].dt.year >= 1987) & (players['birthday'].dt.year <= 1992)]\n\n# Merge with player attributes\nmerged_data = pd.merge(filtered_players, player_attributes, on='player_api_id')\n\n# Calculate the percentage of players who prefer left foot\nleft_foot_count = merged_data[merged_data['preferred_foot'] == 'left'].shape[0]\ntotal_count = merged_data.shape[0]\npercentage_left_foot = (left_foot_count / total_count) * 100\n\n# Record the final result\nresult = percentage_left_foot\n\n# Print the final result\nprint(result)", "sql": "SELECT CAST(COUNT(CASE WHEN t2.preferred_foot = 'left' THEN t1.id ELSE NULL END) AS REAL) * 100 / COUNT(t1.id) percent FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE SUBSTR(t1.birthday, 1, 4) BETWEEN '1987' AND '1992'", "difficulty": "challenging" }, { "question_id": 1038, "question": "List the top 5 leagues in ascending order of the number of goals made in all seasons combined.", "db_id": "european_football_2", "evidence": "sum of home_team_goal, away_team_goal;", "code": "import pandas as pd\nLeague = pd.read_csv('League.csv')\nMatch = pd.read_csv('Match.csv')\n\n# 重命名League表的id列\nLeague = League.rename(columns={'id': 'league_id'})\nmerged_df = pd.merge(League, Match, on='league_id', how='inner')\n\nmerged_df['total_goals'] = merged_df['home_team_goal'] + merged_df['away_team_goal']\ngrouped_df = merged_df.groupby(['league_id', 'name'], as_index=False)['total_goals'].sum()\nresult_df = grouped_df.sort_values(by='total_goals', ascending=True).head(5)\nresult = result_df[['name', 'total_goals']].to_dict('records')", "sql": "SELECT League.name, SUM(Match.home_team_goal + Match.away_team_goal) AS total_goals FROM League JOIN Match ON League.id = Match.league_id GROUP BY League.id, League.name ORDER BY total_goals ASC LIMIT 5", "difficulty": "moderate" }, { "question_id": 1039, "question": "Find the average number of long-shot done by Ahmed Samir Farag.", "db_id": "european_football_2", "evidence": "count of player_fifa_api_id; sum of long_shots;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Ahmed Samir Farag']\nresult = filtered['long_shots'].sum() / filtered['date'].count()", "sql": "SELECT CAST(SUM(t2.long_shots) AS REAL) / COUNT(t2.`date`) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Ahmed Samir Farag'", "difficulty": "simple" }, { "question_id": 1040, "question": "List the top 10 players' names whose heights are above 180 in descending order of average heading accuracy.", "db_id": "european_football_2", "evidence": "heights are above 180 refers to Player.height > 180; average heading accuracy = DIVIDE(SUM(heading_accuracy), COUNT(player_fifa_api_id));", "code": "import pandas as pd\nPlayer = pd.read_csv('Player.csv')\nPlayer_Attributes = pd.read_csv('Player_Attributes.csv')\nPlayer = Player.rename(columns={'id': 'player_id'})\nmerged_df = pd.merge(Player, Player_Attributes, on='player_api_id', how='inner')\nfiltered_df = merged_df[merged_df['height'] > 180]\ngrouped_df = filtered_df.groupby(['player_id', 'player_name'], as_index=False)['heading_accuracy'].mean()\nresult_df = grouped_df.sort_values(['heading_accuracy','player_id'], ascending=[False,False]).head(10)\nresult = result_df[['player_name']]['player_name'].tolist()", "sql": "SELECT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.height > 180 GROUP BY t1.id ORDER BY CAST(SUM(t2.heading_accuracy) AS REAL) / COUNT(t2.`player_fifa_api_id`) DESC LIMIT 10", "difficulty": "moderate" }, { "question_id": 1041, "question": "For the teams with normal build-up play dribbling class in 2014, List the names of the teams with less than average chance creation passing, in descending order of chance creation passing.", "db_id": "european_football_2", "evidence": "normal build-up play dribbling class refers to buildUpPlayDribblingClass = 'Normal'; in 2014 refers to date > = '2014-01-01 00:00:00' AND date < = '2014-01-31 00:00:00'; names of the teams refers to team_long_name; less than average chance creation passing = DIVIDE(SUM(chanceCreationPassing), COUNT(id)) > chanceCreationPassing;", "code": "import pandas as pd\n\nteam = pd.read_csv('Team.csv')\nteam_attributes = pd.read_csv('Team_Attributes.csv')\n\n# Ensure date column is string type to avoid datetime issues\nteam_attributes['date'] = team_attributes['date'].astype(str)\n\n# Calculate average from Team_Attributes with SQL-equivalent filtering\nsubquery_data = team_attributes[\n (team_attributes['buildUpPlayDribblingClass'] == 'Normal') &\n (team_attributes['date'].str.startswith('2014'))\n]\navg_chance = subquery_data['chanceCreationPassing'].mean()\n\n# Join Team with Team_Attributes using SQL-equivalent logic\nmerged = pd.merge(team, team_attributes, on='team_api_id')\n\n# Apply ALL SQL WHERE conditions in post-join filtering\nfiltered = merged[\n (merged['buildUpPlayDribblingClass'] == 'Normal') &\n (merged['date'].str.startswith('2014')) &\n (merged['chanceCreationPassing'] < avg_chance)\n]\n\n# Sort by chance creation passing descending\nresult = filtered.sort_values(by='chanceCreationPassing', ascending=False)[['team_long_name']].reset_index(drop=True)", "sql": "SELECT t.team_long_name FROM Team t JOIN Team_Attributes ta ON t.team_api_id = ta.team_api_id WHERE ta.buildUpPlayDribblingClass = 'Normal' AND ta.date LIKE '2014%' AND ta.chanceCreationPassing < (SELECT AVG(chanceCreationPassing) FROM Team_Attributes WHERE buildUpPlayDribblingClass = 'Normal' AND date LIKE '2014%') ORDER BY ta.chanceCreationPassing DESC", "difficulty": "challenging" }, { "question_id": 1042, "question": "List the name of leagues in which the average goals by the home team is higher than the away team in the 2009/2010 season.", "db_id": "european_football_2", "evidence": "name of league refers to League.name; average goals by the home team is higher than the away team = AVG(home_team_goal) > AVG(away_team_goal); AVG(xx_goal) = SUM(xx_goal) / COUNT(DISTINCT Match.id); 2009/2010 season refers to season = '2009/2010'", "code": "import pandas as pd\n\n# Filter matches for 2009/2010 season\nmatches_2009_2010 = Match[Match['season'] == '2009/2010']\n\n# Merge with League table\nmerged = pd.merge(League, matches_2009_2010, left_on='id', right_on='league_id')\n\n# Group by league name and calculate average goals\ngrouped = merged.groupby('name').agg({\n 'home_team_goal': ['sum', 'count'],\n 'away_team_goal': ['sum', 'count']\n})\n\n# Calculate averages\ngrouped['avg_home_goals'] = grouped[('home_team_goal', 'sum')] / grouped[('home_team_goal', 'count')]\ngrouped['avg_away_goals'] = grouped[('away_team_goal', 'sum')] / grouped[('away_team_goal', 'count')]\n\n# Filter leagues where avg home goals > avg away goals\nfiltered = grouped[grouped['avg_home_goals'] > grouped['avg_away_goals']]\n\n# Get the league names\nresult = pd.DataFrame({'name': filtered.index})", "sql": "SELECT t1.name FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t2.season = '2009/2010' GROUP BY t1.name HAVING (CAST(SUM(t2.home_team_goal) AS REAL) / COUNT(DISTINCT t2.id)) - (CAST(SUM(t2.away_team_goal) AS REAL) / COUNT(DISTINCT t2.id)) > 0", "difficulty": "challenging" }, { "question_id": 1043, "question": "What is the short name of the football team Queens Park Rangers?", "db_id": "european_football_2", "evidence": "short name of the football team refers to team_short_name; Queens Park Rangers refers to team_long_name = 'Queens Park Rangers';", "code": "import pandas as pd\nresult = Team[Team['team_long_name'] == 'Queens Park Rangers']['team_short_name']", "sql": "SELECT team_short_name FROM Team WHERE team_long_name = 'Queens Park Rangers'", "difficulty": "simple" }, { "question_id": 1044, "question": "List the football players with a birthyear of 1970 and a birthmonth of October.", "db_id": "european_football_2", "evidence": "players with a birthyear of 1970 and a birthmonth of October refers to substr(birthday,1,7) AS 'year-month',WHERE year = '1970' AND month = '10';", "code": "import pandas as pd\nresult = Player[Player['birthday'].str[:7] == '1970-10']['player_name']", "sql": "SELECT player_name FROM Player WHERE SUBSTR(birthday, 1, 7) = '1970-10'", "difficulty": "simple" }, { "question_id": 1045, "question": "What is the attacking work rate of the football playerr Franco Zennaro?", "db_id": "european_football_2", "evidence": "", "code": "import pandas as pd\n\n# Merge Player and Player_Attributes tables\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\n\n# Filter for Franco Zennaro\nfiltered = merged[merged['player_name'] == 'Franco Zennaro']\n\n# Get distinct attacking work rate values\nresult = filtered[['attacking_work_rate']].drop_duplicates()", "sql": "SELECT DISTINCT t2.attacking_work_rate FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Franco Zennaro'", "difficulty": "simple" }, { "question_id": 1046, "question": "What is the ADO Den Haag team freedom of movement in the 1st two thirds of the pitch?", "db_id": "european_football_2", "evidence": "ADO Den Haag refers to team_long_name = 'ADO Den Haag'; freedom of movement in the 1st two thirds of the pitch refers to buildUpPlayPositioningClass;", "code": "import pandas as pd\nresult = pd.merge(Team[Team['team_long_name'] == 'ADO Den Haag'][['team_fifa_api_id']], Team_Attributes[['team_fifa_api_id', 'buildUpPlayPositioningClass']], on='team_fifa_api_id')['buildUpPlayPositioningClass'].drop_duplicates()", "sql": "SELECT DISTINCT t2.buildUpPlayPositioningClass FROM Team AS t1 INNER JOIN Team_attributes AS t2 ON t1.team_fifa_api_id = t2.team_fifa_api_id WHERE t1.team_long_name = 'ADO Den Haag'", "difficulty": "moderate" }, { "question_id": 1047, "question": "What is the football player Francois Affolter header's finishing rate on 18/09/2014?", "db_id": "european_football_2", "evidence": "header's finishing rate refers to heading_accuracy; on 18/09/2014 refers to date = '2014-09-18 00:00:00';", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[(merged['player_name'] == 'Francois Affolter') & (merged['date'].str[:10] == '2014-09-18')]\nresult = filtered['heading_accuracy'].values[0] if len(filtered) > 0 else None", "sql": "SELECT t2.heading_accuracy FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Francois Affolter' AND SUBSTR(t2.`date`, 1, 10) = '2014-09-18'", "difficulty": "moderate" }, { "question_id": 1048, "question": "What is the overall rating of the football player Gabriel Tamas in year 2011?", "db_id": "european_football_2", "evidence": "in year 2011 refers to strftime('%Y', date) = '2011';", "code": "import pandas as pd\n\ndef solve_query(player_data, player_attributes_data):\n # Ensure the date column is in datetime format\n if 'date' in player_attributes_data.columns:\n player_attributes_data['date'] = pd.to_datetime(player_attributes_data['date'])\n\n # Filter for Gabriel Tamas in the Player table\n player_filtered = player_data[player_data['player_name'] == 'Gabriel Tamas']\n\n # Extract player_api_id for Gabriel Tamas\n player_api_id = player_filtered['player_api_id'].values[0] if not player_filtered.empty else None\n\n if player_api_id is not None:\n # Filter Player_Attributes for the matching player_api_id and year 2011\n attributes_filtered = player_attributes_data[(player_attributes_data['player_api_id'] == player_api_id) & \n (player_attributes_data['date'].dt.year == 2011)]\n\n # Select the overall_rating column\n result = attributes_filtered['overall_rating']\n return result.reset_index(drop=True)\n else:\n return pd.Series([])\n\n# Example function call - Replace with actual dataframes\n# result = solve_query(player_df, player_attributes_df)\n# print(result)", "sql": "SELECT t2.overall_rating FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Gabriel Tamas' AND strftime('%Y', t2.date) = '2011'", "difficulty": "simple" }, { "question_id": 1049, "question": "How many matches in the 2015/2016 season were held in Scotland Premier League\n?", "db_id": "european_football_2", "evidence": "Scotland Premier League refers to League.name = 'Scotland Premier League';", "code": "import pandas as pd\nmerged = pd.merge(League, Match, left_on='id', right_on='league_id')\nfiltered = merged[(merged['season'] == '2015/2016') & (merged['name'] == 'Scotland Premier League')]\nresult = len(filtered)", "sql": "SELECT COUNT(t2.id) FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t2.season = '2015/2016' AND t1.name = 'Scotland Premier League'", "difficulty": "simple" }, { "question_id": 1050, "question": "What is the preferred foot when attacking of the youngest football player?", "db_id": "european_football_2", "evidence": "preferred foot when attacking refers to preferred_foot; youngest football player refers to latest birthday;", "code": "import pandas as pd\n\ndef solve_query(player_df, player_attributes_df):\n # Ensure date column is in datetime format\n if 'date' in player_attributes_df.columns:\n player_attributes_df['date'] = pd.to_datetime(player_attributes_df['date'])\n\n # Find the latest attribute record for each player\n latest_attributes = player_attributes_df.loc[player_attributes_df.groupby('player_api_id')['date'].idxmax()]\n\n # Merge with Player table to get birthday information\n if 'birthday' in player_df.columns:\n player_df['birthday'] = pd.to_datetime(player_df['birthday'])\n\n merged_data = pd.merge(player_df, latest_attributes, left_on='player_api_id', right_on='player_api_id')\n\n # Sort by birthday descending and select the preferred_foot of the youngest player\n youngest_player = merged_data.sort_values(by='birthday', ascending=False).iloc[0]\n return youngest_player['preferred_foot']\n\n# Example function call assuming `player` and `player_attributes` are DataFrames\ndata_player = pd.DataFrame({'player_api_id': [1, 2], 'birthday': ['2000-01-01', '1995-05-05']})\ndata_player_attributes = pd.DataFrame({\n 'player_api_id': [1, 1, 2],\n 'preferred_foot': ['left', 'right', 'left'],\n 'date': ['2023-01-01', '2022-01-01', '2023-01-01']\n})\nresult = solve_query(data_player, data_player_attributes)\nprint(result)", "sql": "SELECT t2.preferred_foot FROM Player AS t1 INNER JOIN (SELECT player_api_id, preferred_foot, MAX(date) FROM Player_Attributes GROUP BY player_api_id) AS t2 ON t1.player_api_id = t2.player_api_id ORDER BY t1.birthday DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1051, "question": "List all the football player with the highest potential score.", "db_id": "european_football_2", "evidence": "potential score refers to potential; highest potential score refers to MAX(potential);", "code": "import pandas as pd\n\n# Find the maximum potential score\nmax_potential = Player_Attributes['potential'].max()\n\n# Filter player attributes with highest potential\nhighest_potential_players = Player_Attributes[Player_Attributes['potential'] == max_potential][['player_api_id']]\n\n# Merge with Player table to get player names\nresult = pd.merge(highest_potential_players, Player, on='player_api_id')[['player_name']].drop_duplicates()", "sql": "SELECT DISTINCT(t1.player_name) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.potential = (SELECT MAX(potential) FROM Player_Attributes) ", "difficulty": "simple" }, { "question_id": 1052, "question": "Among all the players whose weight is under 130, how many of them preferred foot in attacking is left?", "db_id": "european_football_2", "evidence": "weight < 130; preferred foot in attacking refers to preferred_foot; preferred_foot = 'left';", "code": "import pandas as pd\nplayer_df = pd.read_csv('Player.csv')\nplayer_attributes_df = pd.read_csv('Player_Attributes.csv')\nmerged_df = pd.merge(player_df, player_attributes_df, on='player_api_id', how='inner', suffixes=('_player', '_attributes'))\nfiltered_df = merged_df[(merged_df['weight'] < 130) & (merged_df['preferred_foot'] == 'left')]\nresult = filtered_df['id_player'].nunique()", "sql": "SELECT COUNT(DISTINCT t1.id) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.weight < 130 AND t2.preferred_foot = 'left'", "difficulty": "moderate" }, { "question_id": 1053, "question": "List the football teams that has a chance creation passing class of Risky. Inidcate its short name only.", "db_id": "european_football_2", "evidence": "chance creation passing class refers to chanceCreationPassingClass; chanceCreationPassingClass = 'Risky'; short name refers to team_short_name;", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nfiltered_attributes = team_attributes_df[team_attributes_df['chanceCreationPassingClass'] == 'Risky']\nmerged_df = pd.merge(filtered_attributes, team_df, on='team_api_id')\nresult = merged_df['team_short_name'].unique().tolist()", "sql": "SELECT DISTINCT t1.team_short_name FROM Team AS t1 INNER JOIN Team_attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.chanceCreationPassingClass = 'Risky'", "difficulty": "moderate" }, { "question_id": 1054, "question": "What is the defensive work rate of the football player David Wilson\n?", "db_id": "european_football_2", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'David Wilson']\nresult = filtered[['defensive_work_rate']].drop_duplicates()", "sql": "SELECT DISTINCT t2.defensive_work_rate FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'David Wilson'", "difficulty": "simple" }, { "question_id": 1055, "question": "When is the birthday of the football player who has the highest overall rating?", "db_id": "european_football_2", "evidence": "football player who has the highest overall rating refers to MAX(overall_rating);", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nresult = merged.sort_values('overall_rating', ascending=False).head(1)[['birthday']]", "sql": "SELECT t1.birthday FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id ORDER BY t2.overall_rating DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1056, "question": "What is the name of the football league in the country of Netherlands?", "db_id": "european_football_2", "evidence": "name of the football league refers to League.name;", "code": "import pandas as pd\nresult = pd.merge(Country[Country['name'] == 'Netherlands'], League, left_on='id', right_on='country_id')[['name_y']].rename(columns={'name_y': 'name'})", "sql": "SELECT t2.name FROM Country AS t1 INNER JOIN League AS t2 ON t1.id = t2.country_id WHERE t1.name = 'Netherlands'", "difficulty": "simple" }, { "question_id": 1057, "question": "Calculate the average home team goal in the 2010/2011 season in the country of Poland.", "db_id": "european_football_2", "evidence": "name equals 'Poland' in the database; season equals '2010/2011' in the database; ratio calculated by dividing 2010 by 2011; count of DISTINCT Match.id; sum of home_team_goal; average of home_team_goal;", "code": "import pandas as pd\nmerged = pd.merge(Country, Match, left_on='id', right_on='country_id')\nfiltered = merged[(merged['name'] == 'Poland') & (merged['season'] == '2010/2011')]\nresult = filtered['home_team_goal'].mean()", "sql": "SELECT CAST(SUM(t2.home_team_goal) AS REAL) / COUNT(t2.id) FROM Country AS t1 INNER JOIN Match AS t2 ON t1.id = t2.country_id WHERE t1.name = 'Poland' AND t2.season = '2010/2011'", "difficulty": "moderate" }, { "question_id": 1058, "question": "Who has the highest average finishing rate between the highest and shortest football player?", "db_id": "european_football_2", "evidence": "finishing rate refers to finishing; highest average finishing rate = MAX(AVG(finishing)); highest football player refers to MAX(height); shortest football player refers to MIN(height);", "code": "import pandas as pd\n\n# Get max and min heights\nmax_height = Player['height'].max()\nmin_height = Player['height'].min()\n\n# Get players with max height\nmax_height_players = Player[Player['height'] == max_height]\n\n# Get players with min height \nmin_height_players = Player[Player['height'] == min_height]\n\n# Merge with attributes and calculate average finishing for max height\nmax_merge = pd.merge(max_height_players, Player_Attributes, on='player_api_id')\nmax_avg_finishing = max_merge['finishing'].mean()\n\n# Merge with attributes and calculate average finishing for min height\nmin_merge = pd.merge(min_height_players, Player_Attributes, on='player_api_id')\nmin_avg_finishing = min_merge['finishing'].mean()\n\n# Create result dataframe\nresult_df = pd.DataFrame({\n 'result': [max_avg_finishing, min_avg_finishing],\n 'A': ['Max', 'Min']\n})\n\n# Sort by result descending and get top 1\nresult = result_df.sort_values('result', ascending=False).head(1)['A'].values[0]", "sql": "SELECT A FROM ( SELECT AVG(finishing) result, 'Max' A FROM Player AS T1 INNER JOIN Player_Attributes AS T2 ON T1.player_api_id = T2.player_api_id WHERE T1.height = ( SELECT MAX(height) FROM Player ) UNION SELECT AVG(finishing) result, 'Min' A FROM Player AS T1 INNER JOIN Player_Attributes AS T2 ON T1.player_api_id = T2.player_api_id WHERE T1.height = ( SELECT MIN(height) FROM Player ) ) ORDER BY result DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1059, "question": "Please list player names which are higher than 180.", "db_id": "european_football_2", "evidence": "height is greater than 180 in the database;", "code": "import pandas as pd\nresult = Player[Player['height'] > 180][['player_name']]", "sql": "SELECT player_name FROM Player WHERE height > 180", "difficulty": "simple" }, { "question_id": 1060, "question": "How many players were born after 1990?", "db_id": "european_football_2", "evidence": "born after 1990 refers to strftime('%Y', birthday) = '1990';", "code": "import pandas as pd\n\n# Convert birthday to datetime and filter players born after 1990\nPlayer['birthday'] = pd.to_datetime(Player['birthday'])\nresult = len(Player[Player['birthday'].dt.year > 1990])", "sql": "SELECT COUNT(id) FROM Player WHERE STRFTIME('%Y', birthday) > '1990'", "difficulty": "simple" }, { "question_id": 1061, "question": "How many players whose first names are Adam and weigh more than 170?", "db_id": "european_football_2", "evidence": "team names refers to team_long_name; speed class refers to buildUpPlaySpeedClass; buildUpPlaySpeedClass = 'Fast';player names refers to player_name; weight refers to weight", "code": "import pandas as pd\nresult = len(Player[(Player['player_name'].str.startswith('Adam')) & (Player['weight'] > 170)])", "sql": "SELECT COUNT(id) FROM Player WHERE weight > 170 AND player_name LIKE 'Adam%'", "difficulty": "simple" }, { "question_id": 1062, "question": "Which players had an overall rating of over 80 from 2008 to 2010? Please list player names.", "db_id": "european_football_2", "evidence": "overall_rating > 80; from 2008 to 2010 refers to strftime('%Y', date) BETWEEN '2008' AND '2010';", "code": "import pandas as pd\nPlayer_Attributes['year'] = pd.to_datetime(Player_Attributes['date']).dt.year\nfiltered_attributes = Player_Attributes[(Player_Attributes['overall_rating'] > 80) & (Player_Attributes['year'].between(2008, 2010))]\nmerged = pd.merge(filtered_attributes, Player, left_on='player_api_id', right_on='player_api_id')\nresult = merged[['player_name']].drop_duplicates()", "sql": "SELECT DISTINCT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.overall_rating > 80 AND SUBSTR(t2.`date`, 1, 4) BETWEEN '2008' AND '2010'", "difficulty": "moderate" }, { "question_id": 1063, "question": "What is Aaron Doran's potential score?", "db_id": "european_football_2", "evidence": "potential score refers to potential;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Aaron Doran']\nsorted_df = filtered.sort_values('date', ascending=False)\nresult = sorted_df.iloc[0]['potential']", "sql": "SELECT t2.potential FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Aaron Doran' ORDER BY t2.date DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1064, "question": "List out of players whose preferred foot is left.", "db_id": "european_football_2", "evidence": "preferred_foot equals 'left' in the database;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nleft_footed = merged[merged['preferred_foot'] == 'left']\nresult = left_footed[['id_x', 'player_name']].drop_duplicates().rename(columns={'id_x': 'id'})", "sql": "SELECT DISTINCT t1.id, t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.preferred_foot = 'left'", "difficulty": "simple" }, { "question_id": 1065, "question": "Please list all team names which the speed class is fast.", "db_id": "european_football_2", "evidence": "team names refers to team_long_name; speed class refers to buildUpPlaySpeedClass; buildUpPlaySpeedClass = 'Fast';", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nfiltered_attributes = team_attributes_df[team_attributes_df['buildUpPlaySpeedClass'] == 'Fast']\nmerged_df = pd.merge(filtered_attributes, team_df, on='team_api_id')\nresult = merged_df['team_long_name'].unique().tolist()", "sql": "SELECT DISTINCT t1.team_long_name FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.buildUpPlaySpeedClass = 'Fast'", "difficulty": "simple" }, { "question_id": 1066, "question": "What is the passing class of CLB team?", "db_id": "european_football_2", "evidence": "passing class refers to buildUpPlayPassingClass; CLB refers to team_short_name = 'CLB';", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nfiltered_teams = team_df[team_df['team_short_name'] == 'CLB']\nmerged_df = pd.merge(filtered_teams, team_attributes_df, on='team_api_id')\nresult = merged_df['buildUpPlayPassingClass'].unique().tolist()", "sql": "SELECT DISTINCT t2.buildUpPlayPassingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_short_name = 'CLB'", "difficulty": "simple" }, { "question_id": 1067, "question": "Which teams have build up play passing more than 70? Please list their short names.", "db_id": "european_football_2", "evidence": "build up play passing refers to buildUpPlayPassing; buildUpPlayPassing > 70; short names refers to team_short_name;", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nfiltered_attributes = team_attributes_df[team_attributes_df['buildUpPlayPassing'] > 70]\nmerged_df = pd.merge(filtered_attributes, team_df, on='team_api_id')\nresult = merged_df['team_short_name'].unique().tolist()", "sql": "SELECT DISTINCT t1.team_short_name FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.buildUpPlayPassing > 70", "difficulty": "moderate" }, { "question_id": 1068, "question": "From 2010 to 2015, what was the average overall rating of players who are higher than 170?", "db_id": "european_football_2", "evidence": "from 2010 to 2015 refers to strftime('%Y', date) >= '2010' AND <= '2015'; average overall rating = SUM(t2.overall_rating)/ COUNT(t2.id); higher than 170 refers to Player.height > 170;", "code": "import pandas as pd\n\n# Convert date strings to datetime\nPlayer_Attributes['date'] = pd.to_datetime(Player_Attributes['date'])\n\n# Filter by year range\nfiltered_attrs = Player_Attributes[(Player_Attributes['date'].dt.year >= 2010) & (Player_Attributes['date'].dt.year <= 2015)]\n\n# Merge with Player table\nmerged = pd.merge(filtered_attrs, Player, on='player_api_id')\n\n# Filter by height\nfiltered = merged[merged['height'] > 170]\n\n# Calculate average overall rating\nresult = filtered['overall_rating'].mean()", "sql": "SELECT CAST(SUM(t2.overall_rating) AS REAL) / COUNT(t2.id) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.height > 170 AND STRFTIME('%Y',t2.`date`) >= '2010' AND STRFTIME('%Y',t2.`date`) <= '2015'", "difficulty": "moderate" }, { "question_id": 1069, "question": "Which football player has the shortest height?", "db_id": "european_football_2", "evidence": "shortest height refers to MIN(height);", "code": "import pandas as pd\nresult = Player.nsmallest(1, 'height')[['player_name']]", "sql": "SELECT player_name FROM player ORDER BY height ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1070, "question": "Which country is the league Italy Serie A from?", "db_id": "european_football_2", "evidence": "Italy Serie A from refers to League.name = 'Italy Serie A';", "code": "import pandas as pd\n\n# Assume Country and League DataFrames exist\nmerged = pd.merge(Country, League, left_on='id', right_on='country_id')\nfiltered = merged[merged['name_y'] == 'Italy Serie A']\nresult = filtered[['name_x']].rename(columns={'name_x': 'name'})", "sql": "SELECT t1.name FROM Country AS t1 INNER JOIN League AS t2 ON t1.id = t2.country_id WHERE t2.name = 'Italy Serie A'", "difficulty": "simple" }, { "question_id": 1071, "question": "List the football team that has a build up play speed of 31, build up plan dribbling of 53, and build up play passing of 32. Only indicate the short name of the team.", "db_id": "european_football_2", "evidence": "build up play speed refers to buildUpPlaySpeed; buildUpPlaySpeed = 31; build up play dribbling refers to buildUpPlayDribbling; buildUpPlayDribbling = 53; build up play passing refers to buildUpPlayPassing; buildUpPlayPassing = 32; short name of the team refers to team_short_name;", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nfiltered_attributes = team_attributes_df[(team_attributes_df['buildUpPlaySpeed'] == 31) & (team_attributes_df['buildUpPlayDribbling'] == 53) & (team_attributes_df['buildUpPlayPassing'] == 32)]\nmerged_df = pd.merge(filtered_attributes, team_df, on='team_api_id')\nresult = merged_df['team_short_name'].unique().tolist()", "sql": "SELECT DISTINCT t1.team_short_name FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.buildUpPlaySpeed = 31 AND t2.buildUpPlayDribbling = 53 AND t2.buildUpPlayPassing = 32", "difficulty": "challenging" }, { "question_id": 1072, "question": "What is the average overall rating of the football player Aaron Doran?", "db_id": "european_football_2", "evidence": "average of overall_rating;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Aaron Doran']\nresult = filtered['overall_rating'].mean()", "sql": "SELECT CAST(SUM(t2.overall_rating) AS REAL) / COUNT(t2.id) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Aaron Doran'", "difficulty": "simple" }, { "question_id": 1073, "question": "How many matches were held in the league Germany 1. Bundesliga\nfrom August to October 2008?", "db_id": "european_football_2", "evidence": "Germany 1. Bundesliga refers to League.name = 'Germany 1. Bundesliga'; from August to October 2008 refers to strftime('%Y-%m', date) BETWEEN '2008-08' AND '2008-10';", "code": "import pandas as pd\nmerged = pd.merge(League, Match, left_on='id', right_on='league_id')\nfiltered = merged[(merged['name'] == 'Germany 1. Bundesliga') & (merged['date'].str[:7] >= '2008-08') & (merged['date'].str[:7] <= '2008-10')]\nresult = len(filtered)", "sql": "SELECT COUNT(t2.id) FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t1.name = 'Germany 1. Bundesliga' AND SUBSTR(t2.`date`, 1, 7) BETWEEN '2008-08' AND '2008-10'", "difficulty": "moderate" }, { "question_id": 1074, "question": "List all the short name of the football team that had a home team goal of 10?", "db_id": "european_football_2", "evidence": "short name of the football team refers to team_short_name; home team goal refers to home_team_goal; home_team_goal = 10;", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nmatch_df = pd.read_csv('Match.csv')\nfiltered_matches = match_df[match_df['home_team_goal'] == 10]\nmerged_df = pd.merge(filtered_matches, team_df, left_on='home_team_api_id', right_on='team_api_id')\nresult = merged_df['team_short_name'].tolist()", "sql": "SELECT t1.team_short_name FROM Team AS t1 INNER JOIN Match AS t2 ON t1.team_api_id = t2.home_team_api_id WHERE t2.home_team_goal = 10", "difficulty": "simple" }, { "question_id": 1075, "question": "List all the football player with the highest balance score and potential score of 61.", "db_id": "european_football_2", "evidence": "balance score refers to balance; highest balance score refers to MAX(balance); potential score refers to potential; potential = 61;", "code": "import pandas as pd\n\ndef solve_query(player_df, player_attributes_df):\n # Filter potential score of 61\n filtered_attributes = player_attributes_df[player_attributes_df['potential'] == 61]\n\n # Find the highest balance score within the filtered data\n max_balance = filtered_attributes['balance'].max()\n\n # Filter players with the highest balance score\n top_players = filtered_attributes[filtered_attributes['balance'] == max_balance]\n\n # Merge with Player table to get player names\n result = pd.merge(top_players, player_df, left_on='player_api_id', right_on='player_api_id', how='inner')\n\n # Select and return player names\n return result['player_name']\n\n# Example function call (replace input DataFrames with actual data)\nplayer_data = pd.DataFrame({'player_api_id': [1, 2, 3], 'player_name': ['John', 'Doe', 'Smith']})\nplayer_attributes_data = pd.DataFrame({'player_api_id': [1, 2, 3], 'potential': [61, 61, 50], 'balance': [85, 85, 70]})\nresult = solve_query(player_data, player_attributes_data)\nprint(result)", "sql": "SELECT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.potential = 61 AND t2.balance = (SELECT MAX(balance) FROM Player_Attributes WHERE potential = 61)", "difficulty": "moderate" }, { "question_id": 1076, "question": "What is the difference of the average ball control score between Abdou Diallo and Aaron Appindangoye\n?", "db_id": "european_football_2", "evidence": "player_name equals 'Abdou Diallo' in the database; player_name equals 'Aaron Appindangoye' in the database; player_name equals 'XX XX' in the database; count of CASE WHEN player_name = 'XX XX' THEN id ELSE NULL END; sum of CASE WHEN player_name = 'XX XX' THEN ball_control ELSE 0 END; average of ball_control WHERE player_name = 'Abdou Diallo'; average of ball_control WHERE player_name = 'Aaron Appindangoye'; average of ball_control WHERE player_name = 'XX XX';", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nabdou_diallo = merged[merged['player_name'] == 'Abdou Diallo']['ball_control']\naaron_appindangoye = merged[merged['player_name'] == 'Aaron Appindangoye']['ball_control']\nresult = abdou_diallo.mean() - aaron_appindangoye.mean()", "sql": "SELECT CAST(SUM(CASE WHEN t1.player_name = 'Abdou Diallo' THEN t2.ball_control ELSE 0 END) AS REAL) / COUNT(CASE WHEN t1.player_name = 'Abdou Diallo' THEN t2.id ELSE NULL END) - CAST(SUM(CASE WHEN t1.player_name = 'Aaron Appindangoye' THEN t2.ball_control ELSE 0 END) AS REAL) / COUNT(CASE WHEN t1.player_name = 'Aaron Appindangoye' THEN t2.id ELSE NULL END) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id", "difficulty": "challenging" }, { "question_id": 1077, "question": "What's the long name for the team GEN?", "db_id": "european_football_2", "evidence": "long name for the team refers to team_long_name; team_short_name = 'GEN';", "code": "import pandas as pd\nresult = Team[Team['team_short_name'] == 'GEN']['team_long_name']", "sql": "SELECT team_long_name FROM Team WHERE team_short_name = 'GEN'", "difficulty": "simple" }, { "question_id": 1078, "question": "Which player is older, Aaron Lennon or Abdelaziz Barrada?", "db_id": "european_football_2", "evidence": "The larger the birthday value, the younger the person is, and vice versa;", "code": "import pandas as pd\n\ndef solve_query(player_df):\n # Ensure 'birthday' column exists and convert to datetime\n if 'birthday' in player_df.columns:\n player_df['birthday'] = pd.to_datetime(player_df['birthday'], errors='coerce')\n else:\n raise ValueError(\"'birthday' column is missing in player_df\")\n\n # Filter players by name\n target_players = ['Aaron Lennon', 'Abdelaziz Barrada']\n filtered_players = player_df[player_df['player_name'].isin(target_players)]\n\n # Handle empty results\n if filtered_players.empty:\n return None\n\n # Sort by birthday in ascending order (older first)\n sorted_players = filtered_players.sort_values(by='birthday')\n\n # Return the oldest player's name\n return sorted_players.iloc[0]['player_name']\n\n# Example function call with assumed DataFrame 'player_df'\n# result = solve_query(player_df)\n# print(result)", "sql": "SELECT player_name FROM Player WHERE player_name IN ('Aaron Lennon', 'Abdelaziz Barrada') ORDER BY birthday ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1079, "question": "Which player is the tallest?", "db_id": "european_football_2", "evidence": "tallest player refers to MAX(height);", "code": "import pandas as pd\nresult = Player.nlargest(1, 'height')[['player_name']]", "sql": "SELECT player_name FROM Player ORDER BY height DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1080, "question": "Among the players whose preferred foot was the left foot when attacking, how many of them would remain in his position when the team attacked?", "db_id": "european_football_2", "evidence": "preferred foot when attacking was the left refers to preferred_foot = 'left'; players who would remain in his position when the team attacked refers to attacking_work_rate = 'low';", "code": "import pandas as pd\nplayer_attributes_df = pd.read_csv('Player_Attributes.csv')\nfiltered_df = player_attributes_df[(player_attributes_df['preferred_foot'] == 'left') & (player_attributes_df['attacking_work_rate'] == 'low')]\nresult = len(filtered_df)", "sql": "SELECT COUNT(player_api_id) FROM Player_Attributes WHERE preferred_foot = 'left' AND attacking_work_rate = 'low'", "difficulty": "moderate" }, { "question_id": 1081, "question": "Which country is the Belgium Jupiler League from?", "db_id": "european_football_2", "evidence": "Belgium Jupiler League refers to League.name = 'Belgium Jupiler League';", "code": "import pandas as pd\n\n# Assume Country and League DataFrames exist\nmerged = pd.merge(Country, League, left_on='id', right_on='country_id')\nfiltered = merged[merged['name_y'] == 'Belgium Jupiler League']\nresult = filtered[['name_x']]\nresult.columns = ['name']", "sql": "SELECT t1.name FROM Country AS t1 INNER JOIN League AS t2 ON t1.id = t2.country_id WHERE t2.name = 'Belgium Jupiler League'", "difficulty": "simple" }, { "question_id": 1082, "question": "Please list the leagues from Germany.", "db_id": "european_football_2", "evidence": "Germany refers to Country.name = 'Germany';", "code": "import pandas as pd\n\n# Filter Country table for Germany\ngermany = Country[Country['name'] == 'Germany']\n\n# Join with League table\nmerged = pd.merge(germany, League, left_on='id', right_on='country_id')\n\n# Select only the league names\nresult = merged[['name_y']].rename(columns={'name_y': 'name'})", "sql": "SELECT t2.name FROM Country AS t1 INNER JOIN League AS t2 ON t1.id = t2.country_id WHERE t1.name = 'Germany'", "difficulty": "simple" }, { "question_id": 1083, "question": "Which player has the strongest overall strength?", "db_id": "european_football_2", "evidence": "overall strength refers to overall_rating; strongest overall strength refers to MAX(overall_rating);", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nmerged_sorted = merged.sort_values('overall_rating', ascending=False)\nresult = merged_sorted[['player_name']].head(1)", "sql": "SELECT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id ORDER BY t2.overall_rating DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1084, "question": "Among the players born before the year 1986, how many of them would remain in his position and defense while the team attacked?", "db_id": "european_football_2", "evidence": "players born before the year 1986 refers to strftime('%Y', birthday)<'1986'; players who would remain in his position and defense while the team attacked refers to defensive_work_rate = 'high'; Should consider DISTINCT in the final result;", "code": "import pandas as pd\n\n# Convert birthday to datetime and extract year\nPlayer['birth_year'] = pd.to_datetime(Player['birthday']).dt.year\n\n# Filter players born before 1986\nplayers_before_1986 = Player[Player['birth_year'] < 1986]\n\n# Merge with Player_Attributes\nmerged = pd.merge(players_before_1986, Player_Attributes, on='player_api_id')\n\n# Filter for high defensive work rate\nhigh_defensive = merged[merged['defensive_work_rate'] == 'high']\n\n# Count distinct players\nresult = high_defensive['player_name'].nunique()", "sql": "SELECT COUNT(DISTINCT t1.player_name) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE STRFTIME('%Y',t1.birthday) < '1986' AND t2.defensive_work_rate = 'high'", "difficulty": "challenging" }, { "question_id": 1085, "question": "Which of these players performs the best in crossing actions, Alexis, Ariel Borysiuk or Arouna Kone?", "db_id": "european_football_2", "evidence": "player who perform best in crossing actions refers to MAX(crossing);", "code": "import pandas as pd\n\n# Merge Player and Player_Attributes tables\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\n\n# Filter for the three players\nfiltered = merged[merged['player_name'].isin(['Alexis', 'Ariel Borysiuk', 'Arouna Kone'])]\n\n# Sort by crossing in descending order and get the top player\nresult = filtered[['player_name', 'crossing']].sort_values('crossing', ascending=False).head(1)", "sql": "SELECT t1.player_name, t2.crossing FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name IN ('Alexis', 'Ariel Borysiuk', 'Arouna Kone') ORDER BY t2.crossing DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1086, "question": "What's the heading accuracy of Ariel Borysiuk?", "db_id": "european_football_2", "evidence": "", "code": "import pandas as pd\n\n# Merge Player and Player_Attributes tables\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\n\n# Filter for Ariel Borysiuk\nfiltered = merged[merged['player_name'] == 'Ariel Borysiuk']\n\n# Get heading_accuracy values\nresult = filtered[['heading_accuracy']]", "sql": "SELECT t2.heading_accuracy FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Ariel Borysiuk'", "difficulty": "simple" }, { "question_id": 1087, "question": "Among the players whose height is over 180, how many of them have a volley score of over 70?", "db_id": "european_football_2", "evidence": "height > 180; volley score refers to volleys; volleys > 70;", "code": "import pandas as pd\nplayer_df = pd.read_csv('Player.csv')\nplayer_attributes_df = pd.read_csv('Player_Attributes.csv')\nmerged_df = pd.merge(player_df, player_attributes_df, on='player_api_id', how='inner')\nfiltered_df = merged_df[(merged_df['height'] > 180) & (merged_df['volleys'] > 70)]\nresult = filtered_df.drop_duplicates(subset=['player_api_id']).shape[0]", "sql": "SELECT COUNT(DISTINCT t1.id) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.height > 180 AND t2.volleys > 70", "difficulty": "simple" }, { "question_id": 1088, "question": "Please list the names of the players whose volley score and dribbling score are over 70.", "db_id": "european_football_2", "evidence": "volley score are over 70 refers to volleys > 70; dribbling score refers to dribbling are over 70 refers to dribbling > 70;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[(merged['volleys'] > 70) & (merged['dribbling'] > 70)]\nresult = filtered[['player_name']].drop_duplicates()", "sql": "SELECT DISTINCT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.volleys > 70 AND t2.dribbling > 70", "difficulty": "moderate" }, { "question_id": 1089, "question": "How many matches in the 2008/2009 season were held in Belgium?", "db_id": "european_football_2", "evidence": "Belgium refers to Country.name = 'Belgium';", "code": "import pandas as pd\ncountry_df = pd.read_csv('Country.csv')\nmatch_df = pd.read_csv('Match.csv')\nfiltered_country = country_df[country_df['name'] == 'Belgium']\nmerged_df = pd.merge(filtered_country, match_df, left_on='id', right_on='country_id')\nfiltered_matches = merged_df[merged_df['season'] == '2008/2009']\nresult = len(filtered_matches)", "sql": "SELECT COUNT(t2.id) FROM Country AS t1 INNER JOIN Match AS t2 ON t1.id = t2.country_id WHERE t1.name = 'Belgium' AND t2.season = '2008/2009'", "difficulty": "simple" }, { "question_id": 1090, "question": "What is the long passing score of the oldest player?", "db_id": "european_football_2", "evidence": "long passing score refers to long_passing; oldest player refers to oldest birthday;", "code": "import pandas as pd\n\n# Get the latest player attributes for each player\nlatest_attrs = Player_Attributes.sort_values('date').groupby('player_api_id').last()\n\n# Merge with Player table to get birthday\nmerged = pd.merge(Player[['player_api_id', 'birthday']], latest_attrs[['long_passing']], left_on='player_api_id', right_index=True)\n\n# Find the oldest player (earliest birthday) and get their long passing score\nresult = merged.sort_values('birthday').iloc[0]['long_passing']", "sql": "SELECT t2.long_passing FROM Player AS t1 INNER JOIN (SELECT player_api_id, long_passing, MAX(date) FROM Player_Attributes GROUP BY player_api_id) AS t2 ON t1.player_api_id = t2.player_api_id ORDER BY t1.birthday ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1091, "question": "How many matches were held in the Belgium Jupiler League in April, 2009?", "db_id": "european_football_2", "evidence": "Belgium Jupiler League refers to League.name = 'Belgium Jupiler League'; in April, 2009 refers to SUBSTR(`date`, 1, 7);", "code": "import pandas as pd\nmerged = pd.merge(League, Match, left_on='id', right_on='league_id')\nfiltered = merged[(merged['name'] == 'Belgium Jupiler League') & (merged['date'].str[:7] == '2009-04')]\nresult = len(filtered)", "sql": "SELECT COUNT(t2.id) FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t1.name = 'Belgium Jupiler League' AND SUBSTR(t2.`date`, 1, 7) = '2009-04'", "difficulty": "moderate" }, { "question_id": 1092, "question": "Give the name of the league had the most matches in the 2008/2009 season?", "db_id": "european_football_2", "evidence": "league that had the most matches in the 2008/2009 season refers to MAX(league_name WHERE season = '2008/2009');", "code": "import pandas as pd\nmatch_df = pd.read_csv('Match.csv')\nleague_df = pd.read_csv('League.csv')\nfiltered_match = match_df[match_df['season'] == '2008/2009']\njoined_df = pd.merge(filtered_match, league_df, left_on='league_id', right_on='id')\ngrouped = joined_df.groupby('name').size().reset_index(name='match_count')\nmax_matches = grouped['match_count'].max()\nresult = grouped[grouped['match_count'] == max_matches]['name']", "sql": "SELECT t1.name FROM League AS t1 JOIN Match AS t2 ON t1.id = t2.league_id WHERE t2.season = '2008/2009' GROUP BY t1.name HAVING COUNT(t2.id) = (SELECT MAX(match_count) FROM (SELECT COUNT(t2.id) AS match_count FROM Match AS t2 WHERE t2.season = '2008/2009' GROUP BY t2.league_id))", "difficulty": "simple" }, { "question_id": 1093, "question": "What is the average overall rating of the players born before the year 1986?", "db_id": "european_football_2", "evidence": "average overall rating = DIVIDE(SUM(overall_rating), COUNT(id)); born before the year 1986 refers to strftime('%Y', birthday) < '1986';", "code": "import pandas as pd\n# 假设数据已加载为DataFrame\n# Player = pd.read_csv('Player.csv')\n# Player_Attributes = pd.read_csv('Player_Attributes.csv')\n\n# 合并两个表\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\n\n# 提取出生年份并转换为整数\nmerged['year_born'] = merged['birthday'].str.slice(0,4).astype(int)\n\n# 筛选1986年之前出生的球员\nfiltered = merged[merged['year_born'] < 1986]\n\n# 计算平均评分\naverage_overall_rating = filtered['overall_rating'].sum() / len(filtered)\n\n# 创建结果DataFrame\nresult = pd.DataFrame({'average_overall_rating': [average_overall_rating]})", "sql": "SELECT SUM(t2.overall_rating) / COUNT(t1.id) AS average_overall_rating FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE SUBSTR(t1.birthday, 1, 4) < '1986';", "difficulty": "moderate" }, { "question_id": 1094, "question": "How much higher in percentage is Ariel Borysiuk's overall rating than that of Paulin Puel?", "db_id": "european_football_2", "evidence": "player_name equals 'Ariel Borysiuk' in the database; player_name equals 'Paulin Puel' in the database;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'].isin(['Ariel Borysiuk', 'Paulin Puel'])]\nfiltered['date'] = pd.to_datetime(filtered['date'])\nlatest_ratings = filtered.sort_values(['player_name','date'], ascending=[True,False]).groupby('player_name').head(1)\nratings = latest_ratings.set_index('player_name')['overall_rating']\nresult = (ratings['Ariel Borysiuk'] - ratings['Paulin Puel']) / ratings['Paulin Puel'] * 100", "sql": "SELECT (a.rating - p.rating) * 100.0 / p.rating\nFROM (\n SELECT overall_rating AS rating\n FROM Player\n JOIN Player_Attributes USING (player_api_id)\n WHERE player_name = 'Ariel Borysiuk'\n ORDER BY date DESC\n LIMIT 1\n) AS a,\n(\n SELECT overall_rating AS rating\n FROM Player\n JOIN Player_Attributes USING (player_api_id)\n WHERE player_name = 'Paulin Puel'\n ORDER BY date DESC\n LIMIT 1\n) AS p", "difficulty": "challenging" }, { "question_id": 1095, "question": "How much is the average build up play speed of the Heart of Midlothian team?", "db_id": "european_football_2", "evidence": "Heart of Midlothian refers to team_long_name = 'Heart of Midlothian'; average build up play speed refers to  AVG(buildUpPlaySpeed)", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nmerged_df = pd.merge(team_df, team_attributes_df, on='team_api_id')\nfiltered_df = merged_df[merged_df['team_long_name'] == 'Heart of Midlothian']\naverage_speed = filtered_df['buildUpPlaySpeed'].mean()\nresult = average_speed", "sql": "SELECT CAST(SUM(t2.buildUpPlaySpeed) AS REAL) / COUNT(t2.id) FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'Heart of Midlothian'", "difficulty": "moderate" }, { "question_id": 1096, "question": "Calculate the average overall rating of Pietro Marino.", "db_id": "european_football_2", "evidence": "Pietro Marino refers to player_name = 'Pietro Marino'; average overall rating AVG(T1.overall_rating)", "code": "import pandas as pd\nfiltered_player = Player[Player['player_name'] == 'Pietro Marino']\nmerged = pd.merge(filtered_player, Player_Attributes, on='player_api_id')\nresult = merged['overall_rating'].mean()", "sql": "SELECT CAST(SUM(t2.overall_rating) AS REAL) / COUNT(t2.id) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Pietro Marino'", "difficulty": "moderate" }, { "question_id": 1097, "question": "What is Aaron Lennox's total crossing score?", "db_id": "european_football_2", "evidence": "Aaron Lennox's refers to T2.player_name = 'Aaron Lennox'; total crossing score refers to SUM(crossing)", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Aaron Lennox']\nresult = filtered['crossing'].sum()", "sql": "SELECT SUM(t2.crossing) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Aaron Lennox'", "difficulty": "simple" }, { "question_id": 1098, "question": "What is Ajax's highest chance creation passing score and what is it classified as?", "db_id": "european_football_2", "evidence": "Ajax's refers to team_long_name = 'Ajax'; chance creation passing score refers to MAX(chanceCreationPassing); classified refer to chanceCreationPassingClass", "code": "import pandas as pd\nteam_df = pd.read_csv('Team.csv')\nteam_attributes_df = pd.read_csv('Team_Attributes.csv')\nmerged_df = pd.merge(team_df, team_attributes_df, on='team_api_id')\nfiltered_df = merged_df[merged_df['team_long_name'] == 'Ajax']\nsorted_df = filtered_df.sort_values(by='chanceCreationPassing', ascending=False)\nresult = sorted_df[['chanceCreationPassing', 'chanceCreationPassingClass']].head(1).iloc[0].tolist()", "sql": "SELECT t2.chanceCreationPassing, t2.chanceCreationPassingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'Ajax' ORDER BY t2.chanceCreationPassing DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1099, "question": "Which foot is preferred by Abdou Diallo?", "db_id": "european_football_2", "evidence": "Abdou Diallo refers to player_name = 'Abdou Diallo'; foot is preferred refers to preferred_foot", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Abdou Diallo']\nresult = filtered[['preferred_foot']].drop_duplicates()", "sql": "SELECT DISTINCT t2.preferred_foot FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Abdou Diallo'", "difficulty": "simple" }, { "question_id": 1100, "question": "What is the highest overall rating received by Dorlan Pabon?", "db_id": "european_football_2", "evidence": "Dorlan Pabon refers to T2.player_name = 'Dorlan Pabon'; highest overall rating refers to MAX(overall_rating)", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Dorlan Pabon']\nresult = filtered['overall_rating'].max()", "sql": "SELECT MAX(t2.overall_rating) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Dorlan Pabon'", "difficulty": "simple" }, { "question_id": 1101, "question": "What is the average number of goals made by Parma as the away team while playing in Italy?", "db_id": "european_football_2", "evidence": "Parma refers to team_long_name = 'Parma'; average number of goals refers to AVG(away_team_goal)", "code": "import pandas as pd\nmerged = pd.merge(Match, Team, left_on='away_team_api_id', right_on='team_api_id')\nmerged = pd.merge(merged, Country, left_on='country_id', right_on='id')\nfiltered = merged[(merged['team_long_name'] == 'Parma') & (merged['name'] == 'Italy')]\nresult = filtered['away_team_goal'].mean()", "sql": "SELECT AVG(T1.away_team_goal) FROM \"Match\" AS T1 INNER JOIN Team AS T2 ON T1.away_team_api_id = T2.team_api_id INNER JOIN Country AS T3 ON T1.country_id = T3.id WHERE T2.team_long_name = 'Parma' AND T3.name = 'Italy'", "difficulty": "moderate" }, { "question_id": 1102, "question": "For the players who had a 77 points overall rating on 2016/6/23, who was the oldest? Give the name of the player.", "db_id": "european_football_2", "evidence": "77 points overall rating refers to overall_rating = 77; on 2016/6/23 refers to date LIKE '2016-06-23%'; The larger the birthday value, the younger the person is, and vice versa;", "code": "import pandas as pd\nfiltered_attributes = Player_Attributes[Player_Attributes['date'].str.startswith('2016-06-23')]\nfiltered_attributes = filtered_attributes[filtered_attributes['overall_rating'] == 77]\nmerged = pd.merge(Player, filtered_attributes, on='player_api_id')\nresult = merged.sort_values('birthday').iloc[0]['player_name']", "sql": "SELECT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE SUBSTR(t2.`date`, 1, 10) = '2016-06-23' AND t2.overall_rating = 77 ORDER BY t1.birthday ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1103, "question": "What was the overall rating for Aaron Mooy on 2016/2/4?", "db_id": "european_football_2", "evidence": "Aaron Mooy refers to player_name = 'Aaron Mooy'; on 2016/2/4 refers to date LIKE '2016-02-04%';", "code": "import pandas as pd\n\ndef solve_query(player_data, player_attributes_data):\n # Check if necessary columns exist\n if 'player_name' not in player_data.columns or 'player_api_id' not in player_data.columns:\n return pd.DataFrame({'overall_rating': []})\n\n if 'player_api_id' not in player_attributes_data.columns or 'date' not in player_attributes_data.columns or 'overall_rating' not in player_attributes_data.columns:\n return pd.DataFrame({'overall_rating': []})\n\n # Filter player data for 'Aaron Mooy'\n aaron_mooy = player_data[player_data['player_name'] == 'Aaron Mooy']\n\n if aaron_mooy.empty:\n return pd.DataFrame({'overall_rating': []})\n\n # Get the player_api_id for Aaron Mooy\n player_api_id = aaron_mooy.iloc[0]['player_api_id']\n\n # Convert date column to datetime in player_attributes_data\n try:\n player_attributes_data['date'] = pd.to_datetime(player_attributes_data['date'])\n except Exception:\n return pd.DataFrame({'overall_rating': []})\n\n # Filter player attributes data by date and player_api_id\n filtered_data = player_attributes_data[\n (player_attributes_data['player_api_id'] == player_api_id) & \n (player_attributes_data['date'].dt.strftime('%Y-%m-%d') == '2016-02-04')\n ]\n\n # Select the overall_rating column\n result = filtered_data[['overall_rating']]\n return result\n\n# Example function call with placeholder DataFrames\n# Replace player_df and player_attributes_df with actual data\nplayer_df = pd.DataFrame({\n 'player_name': ['Aaron Mooy'],\n 'player_api_id': [12345]\n})\n\nplayer_attributes_df = pd.DataFrame({\n 'player_api_id': [12345],\n 'date': ['2016-02-04 00:00:00'],\n 'overall_rating': [75]\n})\n\nresult = solve_query(player_df, player_attributes_df)\nprint(result)", "sql": "SELECT t2.overall_rating FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE SUBSTR(t2.`date`, 1, 10) = '2016-02-04' AND t1.player_name = 'Aaron Mooy'", "difficulty": "moderate" }, { "question_id": 1104, "question": "What was the potiential for Francesco Parravicini on 2010/8/30?", "db_id": "european_football_2", "evidence": "Francesco Parravicini refers to player_name = 'Francesco Parravicini'; on 2010/8/30 refers to date = '2010-08-30 00:00:00'", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[(merged['player_name'] == 'Francesco Parravicini') & (merged['date'].str[:10] == '2010-08-30')]\nresult = filtered[['potential']]", "sql": "SELECT t2.potential FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE SUBSTR(t2.`date`, 1, 10) = '2010-08-30' AND t1.player_name = 'Francesco Parravicini'", "difficulty": "moderate" }, { "question_id": 1105, "question": "How was Francesco Migliore's attacking work rate on 2015/5/1?", "db_id": "european_football_2", "evidence": "Francesco Migliore refers to player_name = 'Francesco Migliore'; on 2015/5/1 refers to date LIKE '2015-05-01%';", "code": "import pandas as pd\n\ndef solve_query(player_data, player_attributes_data):\n # Ensure the date column is in datetime format\n player_attributes_data['date'] = pd.to_datetime(player_attributes_data['date'])\n\n # Filter for the specific player and date\n player_filter = player_data[player_data['player_name'] == 'Francesco Migliore']\n if player_filter.empty:\n return pd.DataFrame({'attacking_work_rate': []})\n\n player_api_id = player_filter.iloc[0]['player_api_id']\n\n # Filter Player_Attributes for the given player_api_id and date\n target_date = '2015-05-01'\n filtered_attributes = player_attributes_data[\n (player_attributes_data['player_api_id'] == player_api_id) & \n (player_attributes_data['date'].dt.strftime('%Y-%m-%d').str.startswith(target_date))\n ]\n\n # Return the attacking_work_rate column\n return filtered_attributes[['attacking_work_rate']]\n\n# Example usage with sample dataframes\n# Replace these with actual data loading logic\ndata_player = {\n 'player_api_id': [1, 2],\n 'player_name': ['Francesco Migliore', 'Other Player'],\n 'player_fifa_api_id': [101, 102],\n 'birthday': ['1990-01-01', '1985-05-05'],\n 'height': [180, 175],\n 'weight': [75, 70]\n}\ndata_attributes = {\n 'id': [1001, 1002],\n 'player_fifa_api_id': [101, 102],\n 'player_api_id': [1, 2],\n 'date': ['2015-05-01 12:00:00', '2015-06-01 14:30:00'],\n 'overall_rating': [80, 75],\n 'potential': [85, 80],\n 'preferred_foot': ['right', 'left'],\n 'attacking_work_rate': ['medium', 'high'],\n 'defensive_work_rate': ['medium', 'low']\n}\n\nplayer_df = pd.DataFrame(data_player)\nattributes_df = pd.DataFrame(data_attributes)\n\n# Call the function\nresult = solve_query(player_df, attributes_df)\nprint(result)", "sql": "SELECT t2.attacking_work_rate FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.`date` LIKE '2015-05-01%' AND t1.player_name = 'Francesco Migliore'", "difficulty": "moderate" }, { "question_id": 1106, "question": "Tell the defensive work rate for Kevin Berigaud on 2013/2/22.", "db_id": "european_football_2", "evidence": "Kevin Berigaud refers to player_name = 'Kevin Berigaud'; on 2013/2/22 refers to date = '2013-02-22 00:00:00'", "code": "import pandas as pd\n\n# Merge Player and Player_Attributes tables\nmerged = pd.merge(Player, Player_Attributes, on='player_fifa_api_id')\n\n# Filter for Kevin Berigaud and the specific date\nfiltered = merged[(merged['player_name'] == 'Kevin Berigaud') & (merged['date'].str[:10] == '2013-02-22')]\n\n# Get the defensive work rate\nresult = filtered[['defensive_work_rate']]", "sql": "SELECT t2.defensive_work_rate FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_fifa_api_id = t2.player_fifa_api_id WHERE SUBSTR(t2.`date`, 1, 10) = '2013-02-22' AND t1.player_name = 'Kevin Berigaud'", "difficulty": "moderate" }, { "question_id": 1107, "question": "When was the first time did Kevin Constant have his highest crossing score? Give the date.", "db_id": "european_football_2", "evidence": "Kevin Constant refers to player_name = 'Kevin Constant'; highest crossing score refers to MAX(crossing)highest crossing score refers to MAX(crossing); first occurrence refers to MIN(date)", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['player_name'] == 'Kevin Constant']\nsorted_df = filtered.sort_values(by=['crossing', 'date'], ascending=[False, True])\nresult = sorted_df[['date']].head(1)", "sql": "SELECT `date` FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Kevin Constant' ORDER BY t2.crossing DESC, t2.date ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1108, "question": "What was the build up play speed class for \"Willem II\" on 2011/2/22?", "db_id": "european_football_2", "evidence": "\"Willem II\" refers to team_long_name = 'Willem II'; on 2011/2/22 refers to date = '2012-02-22'", "code": "import pandas as pd\n\n# Merge Team and Team_Attributes tables\nmerged = pd.merge(Team, Team_Attributes, on='team_api_id')\n\n# Filter for Willem II and the specific date\nfiltered = merged[(merged['team_long_name'] == 'Willem II') & (merged['date'].str[:10] == '2011-02-22')]\n\n# Get the buildUpPlaySpeedClass\nresult = filtered['buildUpPlaySpeedClass'].iloc[0] if len(filtered) > 0 else None", "sql": "SELECT t2.buildUpPlaySpeedClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'Willem II' AND SUBSTR(t2.`date`, 1, 10) = '2011-02-22'", "difficulty": "moderate" }, { "question_id": 1109, "question": "How was the build up play dribbling class for \"LEI\" on 2015/9/10?", "db_id": "european_football_2", "evidence": "\"LEI\" refers to team_short_name = 'LEI'; on 2015/9/10 refers to  date = '2015-09-10 00:00:00'", "code": "import pandas as pd\nmerged = pd.merge(Team, Team_Attributes, on='team_api_id')\nfiltered = merged[(merged['team_short_name'] == 'LEI') & (merged['date'].str[:10] == '2015-09-10')]\nresult = filtered['buildUpPlayDribblingClass'].iloc[0] if len(filtered) > 0 else None", "sql": "SELECT t2.buildUpPlayDribblingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_short_name = 'LEI' AND SUBSTR(t2.`date`, 1, 10) = '2015-09-10'", "difficulty": "moderate" }, { "question_id": 1110, "question": "Tell the build Up play passing class for \"FC Lorient\" on 2010/2/22.", "db_id": "european_football_2", "evidence": "\"FC Lorient\" refers to team_long_name = 'FC Lorient'; on 2010/2/22 refers to date LIKE '2010-02-22%';", "code": "import pandas as pd\nmerged = pd.merge(Team, Team_Attributes, on='team_api_id')\nfiltered = merged[(merged['team_long_name'] == 'FC Lorient') & (merged['date'].str.startswith('2010-02-22'))]\nresult = filtered['buildUpPlayPassingClass'].iloc[0] if len(filtered) > 0 else None", "sql": "SELECT t2.buildUpPlayPassingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'FC Lorient' AND t2.`date` LIKE '2010-02-22%'", "difficulty": "moderate" }, { "question_id": 1111, "question": "State the chance creation passing class for \"PEC Zwolle\" on 2013/9/20.", "db_id": "european_football_2", "evidence": "\"PEC Zwolle\" refers to team_long_name = 'PEC Zwolle'; on 2013/9/20 refers to date = '2013-09-20 00:00:00'", "code": "import pandas as pd\n\n# Merge Team and Team_Attributes tables\nmerged = pd.merge(Team, Team_Attributes, on='team_api_id')\n\n# Filter for PEC Zwolle and the specific date\nfiltered = merged[(merged['team_long_name'] == 'PEC Zwolle') & (merged['date'].str[:10] == '2013-09-20')]\n\n# Get the chanceCreationPassingClass\nresult = filtered['chanceCreationPassingClass'].iloc[0] if len(filtered) > 0 else None", "sql": "SELECT t2.chanceCreationPassingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'PEC Zwolle' AND SUBSTR(t2.`date`, 1, 10) = '2013-09-20'", "difficulty": "moderate" }, { "question_id": 1112, "question": "What was the chance creation crossing class for \"Hull City\" on 2010/2/22?", "db_id": "european_football_2", "evidence": "\"Hull City\" refers to team_long_name = 'Hull City'; on 2010/2/22 refers to date = '2010-02-22 00:00:00'", "code": "import pandas as pd\n\n# Merge Team and Team_Attributes\nmerged = pd.merge(Team, Team_Attributes, on='team_api_id')\n\n# Filter for Hull City and date 2010-02-22\nfiltered = merged[(merged['team_long_name'] == 'Hull City') & (merged['date'].str[:10] == '2010-02-22')]\n\n# Get the chanceCreationCrossingClass\nresult = filtered['chanceCreationCrossingClass'].iloc[0] if len(filtered) > 0 else None", "sql": "SELECT t2.chanceCreationCrossingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'Hull City' AND SUBSTR(t2.`date`, 1, 10) = '2010-02-22'", "difficulty": "moderate" }, { "question_id": 1113, "question": "For the team \"Hannover 96\", what was its defence aggression class on 2015/9/10?", "db_id": "european_football_2", "evidence": "\"Hannover 96\" refers to team_long_name = 'Hannover 96'; on 2015/9/10 refers to date LIKE '2015-09-10%';", "code": "import pandas as pd\nteam_id = Team[Team['team_long_name'] == 'Hannover 96']['team_api_id'].values[0]\nresult = Team_Attributes[(Team_Attributes['team_api_id'] == team_id) & (Team_Attributes['date'].str.startswith('2015-09-10'))]['defenceAggressionClass']", "sql": "SELECT t2.defenceAggressionClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_long_name = 'Hannover 96' AND t2.`date` LIKE '2015-09-10%'", "difficulty": "moderate" }, { "question_id": 1114, "question": "What was the average overall rating for Marko Arnautovic from 2007/2/22 to 2016/4/21?", "db_id": "european_football_2", "evidence": "average overall rating refers to avg(overall_rating); Marko Arnautovic refers to player_name = 'Marko Arnautovic'; from 2007/2/22 to 2016/4/21 refers to the first 10 characters of date BETWEEN '2007-02-22' and '2016-04-21'", "code": "import pandas as pd\nPlayer_Attributes['date'] = pd.to_datetime(Player_Attributes['date'])\nfiltered_dates = Player_Attributes[(Player_Attributes['date'] >= '2007-02-22') & (Player_Attributes['date'] <= '2016-04-21')]\nmerged = pd.merge(Player, filtered_dates, on='player_api_id')\nmarko_data = merged[merged['player_name'] == 'Marko Arnautovic']\nresult = marko_data['overall_rating'].mean()", "sql": "SELECT AVG(t2.overall_rating) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.player_name = 'Marko Arnautovic' AND SUBSTR(t2.`date`, 1, 10) BETWEEN '2007-02-22' AND '2016-04-21'", "difficulty": "challenging" }, { "question_id": 1115, "question": "What percentage is Landon Donovan's overall rating higher than Jordan Bowery on 2013/7/12?", "db_id": "european_football_2", "evidence": "Landon Donovan's refers to player_name = 'Landon Donovan'; Jordan Bowery refers to player_name = 'Jordan Bowery'; percentage refers to DIVIDE(SUBTRACT(player_name = 'Landon Donovan' overall_rating; player_name = 'Jordan Bowery' overall_rating), player_name = 'Landon Donovan' overall_rating)*100", "code": "import pandas as pd\n\n# Get Landon Donovan's rating on 2013-07-12\nlandon = pd.merge(Player[Player['player_name'] == 'Landon Donovan'], Player_Attributes, on='player_api_id')\nlandon = landon[landon['date'].str.startswith('2013-07-12')]\nlandon = landon.sort_values('date', ascending=False).head(1)\nlandon_rating = landon['overall_rating'].iloc[0]\n\n# Get Jordan Bowery's rating on 2013-07-12\njordan = pd.merge(Player[Player['player_name'] == 'Jordan Bowery'], Player_Attributes, on='player_api_id')\njordan = jordan[jordan['date'].str.startswith('2013-07-12')]\njordan = jordan.sort_values('date', ascending=False).head(1)\njordan_rating = jordan['overall_rating'].iloc[0]\n\n# Calculate percentage difference\nresult = pd.DataFrame([{'LvsJ_percent': (landon_rating - jordan_rating) * 100.0 / landon_rating}])", "sql": "SELECT (ld.overall_rating - jb.overall_rating) * 100.0 / ld.overall_rating AS LvsJ_percent\nFROM \n (SELECT overall_rating \n FROM Player p\n INNER JOIN Player_Attributes pa ON p.player_api_id = pa.player_api_id\n WHERE p.player_name = 'Landon Donovan'\n AND pa.date LIKE '2013-07-12%'\n ORDER BY pa.date DESC\n LIMIT 1) ld,\n (SELECT overall_rating\n FROM Player p\n INNER JOIN Player_Attributes pa ON p.player_api_id = pa.player_api_id\n WHERE p.player_name = 'Jordan Bowery'\n AND pa.date LIKE '2013-07-12%'\n ORDER BY pa.date DESC\n LIMIT 1) jb", "difficulty": "challenging" }, { "question_id": 1116, "question": "List down most tallest players' name.", "db_id": "european_football_2", "evidence": "tallest refers to rank based on the height in descending order; Most tallest players refers to rank = 1 ", "code": "import pandas as pd\n\ndef solve_query(player_df):\n # Check if required columns exist\n if 'height' not in player_df.columns or 'player_name' not in player_df.columns:\n return pd.DataFrame(columns=['player_name'])\n\n # Handle NULL values in height column\n player_df = player_df.dropna(subset=['height'])\n\n # Rank players based on height in descending order\n player_df['rank'] = player_df['height'].rank(method='dense', ascending=False)\n\n # Filter for rank = 1 and select player_name\n result_df = player_df[player_df['rank'] == 1][['player_name']]\n\n return result_df\n\n# Example function call (replace `player_data` with actual DataFrame)\n# player_data = pd.read_csv('Player.csv')\n# result = solve_query(player_data)\n# print(result)", "sql": "SELECT player_name FROM (SELECT player_name, height, DENSE_RANK() OVER (ORDER BY height DESC) as rank FROM Player) WHERE rank = 1", "difficulty": "simple" }, { "question_id": 1117, "question": "What are the player api id of 10 heaviest players?", "db_id": "european_football_2", "evidence": "heaviest refers to MAX(weight)", "code": "import pandas as pd\n\n# 读取Player表\ndf = pd.read_csv('Player.csv')\n\n# 按weight列降序排序,并选择前10行\nresult = df.sort_values(by='weight', ascending=False).head(10)[['player_api_id']]\n", "sql": "SELECT player_api_id FROM Player ORDER BY weight DESC LIMIT 10", "difficulty": "simple" }, { "question_id": 1118, "question": "List down the name of players who are 35 years old and above.", "db_id": "european_football_2", "evidence": "35 years old and above refers to datetime(CURRENT_TIMESTAMP,'localtime') - datetime(birthday) > 34", "code": "import pandas as pd\nPlayer['birthday'] = pd.to_datetime(Player['birthday'])\nnow = pd.Timestamp.now()\nage = now.year - Player['birthday'].dt.year\nage -= ((now.month < Player['birthday'].dt.month) | ((now.month == Player['birthday'].dt.month) & (now.day < Player['birthday'].dt.day))).astype(int)\nresult = Player[age >= 35][['player_name']]", "sql": "SELECT player_name FROM Player WHERE (strftime('%Y', 'now') - strftime('%Y', birthday)) > 35 OR ((strftime('%Y', 'now') - strftime('%Y', birthday)) = 35 AND strftime('%m-%d', 'now') >= strftime('%m-%d', birthday))", "difficulty": "simple" }, { "question_id": 1119, "question": "How many home team goal have been scored by Aaron Lennon?", "db_id": "european_football_2", "evidence": "player_name equals 'Aaron Lennon' in the database;", "code": "import pandas as pd\n# 假设所有表已加载为DataFrame\n# 获取Aaron Lennon的player_api_id\naaron_id = Player[Player['player_name'] == 'Aaron Lennon']['player_api_id'].iloc[0]\n# 构建主队球员列列表\nhome_player_cols = ['home_player_1','home_player_2','home_player_3','home_player_4','home_player_5','home_player_6','home_player_7','home_player_8','home_player_9','home_player_10','home_player_11']\n# 创建掩码判断是否出现在任何主队位置\nmask = Match[home_player_cols].apply(lambda x: (x == aaron_id)).any(axis=1)\n# 计算符合条件的比赛的主队进球总和\nresult = Match.loc[mask, 'home_team_goal'].sum()", "sql": "SELECT SUM(t2.home_team_goal) FROM Player AS t1 INNER JOIN `Match` AS t2 ON t1.player_api_id IN (t2.home_player_1, t2.home_player_2, t2.home_player_3, t2.home_player_4, t2.home_player_5, t2.home_player_6, t2.home_player_7, t2.home_player_8, t2.home_player_9, t2.home_player_10, t2.home_player_11) WHERE t1.player_name = 'Aaron Lennon';", "difficulty": "simple" }, { "question_id": 1120, "question": "Sum up the away team goal scored by both Daan Smith and Filipe Ferreira.", "db_id": "european_football_2", "evidence": "Daan Smith refers to player_name = 'Daan Smith'; Filipe Ferreira refers to player_name = 'Filipe Ferreira'", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\nplayer_df = pd.read_csv('Player.csv')\nmatch_df = pd.read_csv('Match.csv')\n\n# 筛选出Daan Smith和Filipe Ferreira的记录\nplayers_of_interest = player_df[player_df['player_name'].isin(['Daan Smith', 'Filipe Ferreira'])]\n\n# 创建一个包含所有away_player_X列的列表\naway_player_columns = [f'away_player_{i}' for i in range(1, 12)]\n\n# 将Match表与Player表进行连接\nmerged_dfs = []\nfor col in away_player_columns:\n merged_df = pd.merge(match_df, players_of_interest, left_on=col, right_on='player_api_id', how='inner')\n merged_dfs.append(merged_df)\n\n# 合并所有连接结果\nfinal_merged_df = pd.concat(merged_dfs).drop_duplicates().reset_index(drop=True)\n\n# 计算away_team_goal的总和\nresult = final_merged_df['away_team_goal'].sum()\n\n# 输出结果\nprint(result)", "sql": "SELECT SUM(T1.away_team_goal) AS total_away_goals FROM Match AS T1 JOIN Player AS T2 ON T1.away_player_1 = T2.player_api_id OR T1.away_player_2 = T2.player_api_id OR T1.away_player_3 = T2.player_api_id OR T1.away_player_4 = T2.player_api_id OR T1.away_player_5 = T2.player_api_id OR T1.away_player_6 = T2.player_api_id OR T1.away_player_7 = T2.player_api_id OR T1.away_player_8 = T2.player_api_id OR T1.away_player_9 = T2.player_api_id OR T1.away_player_10 = T2.player_api_id OR T1.away_player_11 = T2.player_api_id WHERE T2.player_name IN ('Daan Smith', 'Filipe Ferreira')", "difficulty": "moderate" }, { "question_id": 1121, "question": "Calculate the total home team goal scored by players whose age are 30 years old and below.", "db_id": "european_football_2", "evidence": "age are 30 years old and below refers to SUBTRACT(datetime(CURRENT_TIMESTAMP,'localtime'), datetime(birthday) < 31)", "code": "import pandas as pd\\nfrom datetime import datetime, timedelta\\n\\n# 读取数据\\nplayer_df = pd.read_csv('Player.csv')\\nmatch_df = pd.read_csv('Match.csv')\\n\\n# 计算球员的年龄\\ncurrent_year = datetime.now().year\\nplayer_df['age'] = current_year - pd.to_datetime(player_df['birthday']).dt.year\\n\\n# 筛选30岁及以下的球员\\nyoung_players = player_df[player_df['age'] <= 30]\\n\\n# 获取这些球员的player_api_id\\nyoung_player_ids = young_players['player_api_id'].tolist()\\n\\n# 创建一个布尔掩码,用于筛选包含这些球员的比赛\\nhome_player_columns = [f'home_player_{i}' for i in range(1, 12)]\\nmask = match_df[home_player_columns].isin(young_player_ids).any(axis=1)\\n\\n# 应用掩码并计算主场进球总数\\nresult = match_df[mask]['home_team_goal'].sum()\\n\\n# 输出结果\\nprint(result)", "sql": "SELECT SUM(DISTINCT t2.home_team_goal) FROM Match AS t2 WHERE EXISTS (SELECT 1 FROM Player WHERE (strftime('%Y','now') - strftime('%Y',birthday)) <= 30 AND player_api_id IN (t2.home_player_1,t2.home_player_2,t2.home_player_3,t2.home_player_4,t2.home_player_5,t2.home_player_6,t2.home_player_7,t2.home_player_8,t2.home_player_9,t2.home_player_10,t2.home_player_11))", "difficulty": "moderate" }, { "question_id": 1122, "question": "State the name of the most strongest player.", "db_id": "european_football_2", "evidence": "strongest players refers to player has MAX(overall_rating)", "code": "import pandas as pd\nmax_rating = Player_Attributes['overall_rating'].max()\nplayers_with_max_rating = Player_Attributes[Player_Attributes['overall_rating'] == max_rating]['player_api_id'].unique()\nresult = Player[Player['player_api_id'].isin(players_with_max_rating)]['player_name'].unique()", "sql": "SELECT DISTINCT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.overall_rating = (SELECT MAX(overall_rating) FROM Player_Attributes)", "difficulty": "simple" }, { "question_id": 1123, "question": "What is the name of players with the highest potential?", "db_id": "european_football_2", "evidence": "highest potential refers to MAX(potential)", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nmax_potential = merged['potential'].max()\nresult = merged[merged['potential'] == max_potential][['player_name']].drop_duplicates()", "sql": "SELECT DISTINCT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id ORDER BY t2.potential DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1124, "question": "Who are the players that tend to be attacking when their mates were doing attack moves? List down their name.", "db_id": "european_football_2", "evidence": "tend to be attacking when their mates were doing attack moves refers to attacking_work_rate = 'high';", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['attacking_work_rate'] == 'high']\nresult = filtered[['player_name']].drop_duplicates()", "sql": "SELECT DISTINCT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.attacking_work_rate = 'high'", "difficulty": "moderate" }, { "question_id": 1125, "question": "Among the players with finishing rate of 1, pick the eldest player and state the player's name.", "db_id": "european_football_2", "evidence": "eldest player refers to MAX(SUBTRACT(datetime(CURRENT_TIMESTAMP,'localtime'),datetime(birthday))); finishing rate of 1 refers to finishing = 1", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfinishing_1 = merged[merged['finishing'] == 1]\noldest = finishing_1.sort_values('birthday').iloc[0]\nresult = oldest['player_name']", "sql": "SELECT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.finishing = 1 ORDER BY t1.birthday ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1126, "question": "State the name of players who came from Belgium.", "db_id": "european_football_2", "evidence": "name of players refers to player_name; Belgium is name of country", "code": "import pandas as pd\n\n# Read the CSV files\ndf_country = pd.read_csv('Country.csv')\ndf_match = pd.read_csv('Match.csv')\ndf_player = pd.read_csv('Player.csv')\n\n# Step 1: Filter Country for 'Belgium'\n# SQL: WHERE t1.name = 'Belgium'\nbelgium_country = df_country[df_country['name'] == 'Belgium']\n\n# Step 2: Join Country with Match to find matches in Belgium\n# SQL: FROM Country AS t1 INNER JOIN Match AS t2 ON t1.id = t2.country_id\nmerged_match = pd.merge(belgium_country, df_match, left_on='id', right_on='country_id')\n\n# Step 3: Join the result with Player using 'home_player_1'\n# SQL: INNER JOIN Player AS t3 ON t2.home_player_1 = t3.player_api_id\nmerged_final = pd.merge(merged_match, df_player, left_on='home_player_1', right_on='player_api_id')\n\n# Step 4: Select the player_name column and convert to list of lists to match SQL output format\n# SQL: SELECT t3.player_name\nresult = merged_final[['player_name']].values.tolist()\n\nprint(result)", "sql": "SELECT t3.player_name FROM Country AS t1 INNER JOIN Match AS t2 ON t1.id = t2.country_id INNER JOIN Player AS t3 ON t2.home_player_1 = t3.player_api_id WHERE t1.name = 'Belgium'", "difficulty": "simple" }, { "question_id": 1127, "question": "Locate players with vision scores of 90 and above, state the country of these players.", "db_id": "european_football_2", "evidence": "vision is greater than 89 in the database;", "code": "import pandas as pd\n\n# Filter players with vision > 89\nhigh_vision_players = Player_Attributes[Player_Attributes['vision'] > 89][['player_api_id']].drop_duplicates()\n\n# Get all player_api_ids from Match table (home_player_1 to home_player_11, away_player_1 to away_player_11)\nhome_cols = [f'home_player_{i}' for i in range(1, 12)]\naway_cols = [f'away_player_{i}' for i in range(1, 12)]\nall_player_cols = home_cols + away_cols\n\n# Melt Match data to get all player appearances with country_id\nmatch_players = Match[['country_id'] + all_player_cols].melt(id_vars=['country_id'], value_vars=all_player_cols, value_name='player_api_id')\nmatch_players = match_players[match_players['player_api_id'].notna()][['country_id', 'player_api_id']].drop_duplicates()\n\n# Merge high vision players with match data\nmerged = pd.merge(high_vision_players, match_players, on='player_api_id')\n\n# Merge with Country to get country names\nmerged_with_country = pd.merge(merged, Country, left_on='country_id', right_on='id')\n\n# Get distinct country names\nresult = merged_with_country[['name']].drop_duplicates().reset_index(drop=True)", "sql": "SELECT DISTINCT c.name FROM Player_Attributes pa JOIN Player p ON pa.player_api_id = p.player_api_id JOIN Match m ON p.player_api_id IN (m.home_player_1,m.home_player_2,m.home_player_3,m.home_player_4,m.home_player_5,m.home_player_6,m.home_player_7,m.home_player_8,m.home_player_9,m.home_player_10,m.home_player_11,m.away_player_1,m.away_player_2,m.away_player_3,m.away_player_4,m.away_player_5,m.away_player_6,m.away_player_7,m.away_player_8,m.away_player_9,m.away_player_10,m.away_player_11) JOIN League l ON m.league_id = l.id JOIN Country c ON l.country_id = c.id WHERE pa.vision >= 90", "difficulty": "moderate" }, { "question_id": 1128, "question": "Which country's players have the heaviest average weights?", "db_id": "european_football_2", "evidence": "average of weight;", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\ncountry_df = pd.read_csv('Country.csv')\nmatch_df = pd.read_csv('Match.csv')\nplayer_df = pd.read_csv('Player.csv')\n\n# 创建一个包含所有home_player_X列的列表\nhome_player_columns = [f'home_player_{i}' for i in range(1, 12)]\n\n# 将Match表与Player表进行连接\nmerged_dfs = []\nfor col in home_player_columns:\n merged_df = pd.merge(match_df, player_df, left_on=col, right_on='player_api_id', how='inner')\n merged_dfs.append(merged_df)\n\n# 合并所有连接结果\nfinal_merged_df = pd.concat(merged_dfs).drop_duplicates().reset_index(drop=True)\n\n# 将合并后的表与Country表进行连接\nfinal_merged_df = pd.merge(final_merged_df, country_df, left_on='country_id', right_on='id', how='inner')\n\n# 按国家分组并计算平均体重\naverage_weights = final_merged_df.groupby('name')['weight'].mean().reset_index()\n\n# 按平均体重降序排序,并取第一个结果\nresult = average_weights.sort_values(by='weight', ascending=False).head(1)[['name']]\n\n# 输出结果\nprint(result)", "sql": "SELECT t1.name FROM Country AS t1 INNER JOIN Match AS t2 ON t1.id = t2.country_id INNER JOIN Player AS t3 ON t2.home_player_1 = t3.player_api_id GROUP BY t1.name ORDER BY AVG(t3.weight) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1129, "question": "List down the long name for slow speed class team.", "db_id": "european_football_2", "evidence": "slow speed class refers to buildUpPlaySpeedClass = 'Slow'; long name refers to team_long_name", "code": "import pandas as pd\n\n# Read the necessary tables\nteam_attributes = pd.read_csv('Team_Attributes.csv')\nteams = pd.read_csv('Team.csv')\n\n# Filter teams with buildUpPlaySpeedClass = 'Slow'\nslow_speed_teams = team_attributes[team_attributes['buildUpPlaySpeedClass'] == 'Slow']\n\n# Merge with Team table to get the long names\nresult = pd.merge(slow_speed_teams, teams, on='team_api_id')['team_long_name'].unique()\n\n# Print the result\nprint(result)", "sql": "SELECT DISTINCT t1.team_long_name FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.buildUpPlaySpeedClass = 'Slow'", "difficulty": "simple" }, { "question_id": 1130, "question": "What are the short name of team who played safe while creating chance of passing?", "db_id": "european_football_2", "evidence": "played safe while creating chance of passing refers to chanceCreationPassingClass = 'Safe'; short name of team refers to team_short_name", "code": "import pandas as pd\n\n# Load the necessary tables\nteam_attributes = pd.read_csv('Team_Attributes.csv')\nteam = pd.read_csv('Team.csv')\n\n# Filter teams that played safe while creating chance of passing\nsafe_teams = team_attributes[team_attributes['chanceCreationPassingClass'] == 'Safe']\n\n# Merge with Team table to get the short name of the team\nresult = pd.merge(safe_teams, team, on='team_api_id', how='inner')[['team_short_name']]\n\n# Print the result\nprint(result)", "sql": "SELECT DISTINCT t1.team_short_name FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.chanceCreationPassingClass = 'Safe'", "difficulty": "moderate" }, { "question_id": 1131, "question": "What is the average heights of Italy players?", "db_id": "european_football_2", "evidence": "average heights refers to Avg(height); Italy is name of country", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\nmatch_df = pd.read_csv('Match.csv')\nleague_df = pd.read_csv('League.csv')\ncountry_df = pd.read_csv('Country.csv')\nplayer_df = pd.read_csv('Player.csv')\n\n# 提取意大利的联赛ID\nitaly_league_ids = league_df[league_df['country_id'] == country_df[country_df['name'] == 'Italy']['id'].values[0]]['id']\n\n# 提取意大利球员的player_api_id\nhome_players_columns = [f'home_player_{i}' for i in range(1, 12)]\naway_players_columns = [f'away_player_{i}' for i in range(1, 12)]\nall_players_columns = home_players_columns + away_players_columns\n\nitaly_players_df = pd.DataFrame()\nfor col in all_players_columns:\n temp_df = match_df[match_df['league_id'].isin(italy_league_ids)][['id', col]].rename(columns={col: 'player_api_id'})\n italy_players_df = pd.concat([italy_players_df, temp_df], ignore_index=True)\n\n# 去重\nitaly_players_df = italy_players_df.drop_duplicates(subset=['player_api_id'])\n\n# 计算意大利球员的平均身高\naverage_height = player_df[player_df['player_api_id'].isin(italy_players_df['player_api_id'])]['height'].mean()\n\nprint(average_height)", "sql": "WITH italy_players AS ( SELECT DISTINCT player_id FROM ( SELECT home_player_1 AS player_id, league_id FROM Match UNION ALL SELECT home_player_2 AS player_id, league_id FROM Match UNION ALL SELECT home_player_3 AS player_id, league_id FROM Match UNION ALL SELECT home_player_4 AS player_id, league_id FROM Match UNION ALL SELECT home_player_5 AS player_id, league_id FROM Match UNION ALL SELECT home_player_6 AS player_id, league_id FROM Match UNION ALL SELECT home_player_7 AS player_id, league_id FROM Match UNION ALL SELECT home_player_8 AS player_id, league_id FROM Match UNION ALL SELECT home_player_9 AS player_id, league_id FROM Match UNION ALL SELECT home_player_10 AS player_id, league_id FROM Match UNION ALL SELECT home_player_11 AS player_id, league_id FROM Match UNION ALL SELECT away_player_1 AS player_id, league_id FROM Match UNION ALL SELECT away_player_2 AS player_id, league_id FROM Match UNION ALL SELECT away_player_3 AS player_id, league_id FROM Match UNION ALL SELECT away_player_4 AS player_id, league_id FROM Match UNION ALL SELECT away_player_5 AS player_id, league_id FROM Match UNION ALL SELECT away_player_6 AS player_id, league_id FROM Match UNION ALL SELECT away_player_7 AS player_id, league_id FROM Match UNION ALL SELECT away_player_8 AS player_id, league_id FROM Match UNION ALL SELECT away_player_9 AS player_id, league_id FROM Match UNION ALL SELECT away_player_10 AS player_id, league_id FROM Match UNION ALL SELECT away_player_11 AS player_id, league_id FROM Match ) AS mp JOIN League L ON mp.league_id = L.id JOIN Country C ON L.country_id = C.id WHERE C.name = 'Italy' ) SELECT AVG(P.height) FROM Player P WHERE P.player_api_id IN (SELECT player_id FROM italy_players);", "difficulty": "simple" }, { "question_id": 1132, "question": "Please provide the names of top three football players who are over 180 cm tall in alphabetical order.", "db_id": "european_football_2", "evidence": "over 180 cm tall refers to height > 180; name of football player refers to player_name", "code": "import pandas as pd\nimport numpy as np\n\nresult = Player[Player['height'] > 180].sort_values('player_name').head(3)[['player_name']]", "sql": "SELECT player_name FROM Player WHERE height > 180 ORDER BY player_name LIMIT 3", "difficulty": "simple" }, { "question_id": 1133, "question": "How many football players born after the 1990s have the first name \"Aaron\"?", "db_id": "european_football_2", "evidence": "first name \"Aaron\" refers to player_name LIKE 'Aaron%'; born after the 1990s refers to birthday > '1990'", "code": "import pandas as pd\nresult = len(Player[(Player['birthday'] > '1990') & (Player['player_name'].str.startswith('Aaron'))])", "sql": "SELECT COUNT(id) FROM Player WHERE birthday > '1990' AND player_name LIKE 'Aaron%';", "difficulty": "simple" }, { "question_id": 1134, "question": "What is the difference between players 6 and 23's jumping scores?", "db_id": "european_football_2", "evidence": "id equals 6 in the database; id equals 23 in the database;", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\nplayer_attributes_df = pd.read_csv('Player_Attributes.csv')\n\n# 筛选出id为6和23的记录\nplayer_6_jumping = player_attributes_df[player_attributes_df['id'] == 6]['jumping'].sum()\nplayer_23_jumping = player_attributes_df[player_attributes_df['id'] == 23]['jumping'].sum()\n\n# 计算跳跃分数的差值\ndifference = player_6_jumping - player_23_jumping\n\nprint(difference)", "sql": "SELECT SUM(CASE WHEN t1.id = 6 THEN t1.jumping ELSE 0 END) - SUM(CASE WHEN t1.id = 23 THEN t1.jumping ELSE 0 END) FROM Player_Attributes AS t1", "difficulty": "simple" }, { "question_id": 1135, "question": "Please provide top five football players' IDs who are among the lowest potential players and prefer to use the right foot when attacking.", "db_id": "european_football_2", "evidence": "lowest potential players refers to MIN(potential); prefer to use the right foot when attacking refers to preferred_foot = 'right'", "code": "import pandas as pd\nmin_potential = Player_Attributes['potential'].min()\nfiltered = Player_Attributes[(Player_Attributes['preferred_foot'] == 'right') & (Player_Attributes['potential'] == min_potential)]\nresult = filtered['player_api_id'].drop_duplicates().head(5)", "sql": "SELECT player_api_id FROM Player_Attributes WHERE preferred_foot = 'right' AND potential = (SELECT MIN(potential) FROM Player_Attributes) GROUP BY player_api_id ORDER BY potential ASC LIMIT 5", "difficulty": "moderate" }, { "question_id": 1136, "question": "How many players had the highest potential score for crossing that preferred to use their left foots while attacking?", "db_id": "european_football_2", "evidence": "highest potential score for crossing refers to MAX(crossing); preferred to use their left foots while attacking refers to preferred_foot = 'left'", "code": "import pandas as pd\n\n# 读取Player_Attributes表为DataFrame\ndf = pd.read_csv('Player_Attributes.csv') # 假设数据存储在CSV文件中,实际使用时请替换为正确的数据源\n\n# 找到crossing列的最大值\nmax_crossing = df['crossing'].max()\n\n# 筛选出preferred_foot为'left'且crossing等于最大值的记录\nfiltered_df = df[(df['preferred_foot'] == 'left') & (df['crossing'] == max_crossing)]\n\n# 计算符合条件的记录数\nresult = len(filtered_df)\n\n# 输出结果\nprint(result)", "sql": "SELECT COUNT(t1.id) FROM Player_Attributes AS t1 WHERE t1.preferred_foot = 'left' AND t1.crossing = ( SELECT MAX(crossing) FROM Player_Attributes)", "difficulty": "moderate" }, { "question_id": 1137, "question": "What percentage of players have a strength and stamina score of more than 80?", "db_id": "european_football_2", "evidence": "stamina is greater than 80 in the database; strength is greater than 80 in the database;", "code": "import pandas as pd\n\n# 读取Player_Attributes表为DataFrame\ndf = pd.read_csv('Player_Attributes.csv')\n\n# 筛选strength和stamina都大于80的记录\nfiltered_df = df.query('strength > 80 and stamina > 80')\n\n# 计算符合条件的记录数占总记录数的百分比\npercentage = (len(filtered_df) / len(df)) * 100\n\n# 输出结果\nresult = percentage\nresult", "sql": "SELECT CAST(COUNT(CASE WHEN strength > 80 AND stamina > 80 THEN id ELSE NULL END) AS REAL) * 100 / COUNT(id) FROM Player_Attributes t", "difficulty": "simple" }, { "question_id": 1138, "question": "In what country did the Poland Ekstraklasa take place?", "db_id": "european_football_2", "evidence": "", "code": "import pandas as pd\n\n# 读取Country表和League表\ncountry_df = pd.read_csv('Country.csv')\nleague_df = pd.read_csv('League.csv')\n\n# 筛选出联赛名称为'Poland Ekstraklasa'的记录\nfiltered_league_df = league_df[league_df['name'] == 'Poland Ekstraklasa']\n\n# 获取对应的country_id\ncountry_ids = filtered_league_df['country_id'].unique()\n\n# 从Country表中筛选出对应的国家名称\nresult = country_df[country_df['id'].isin(country_ids)]['name']\n\n# 输出结果\nprint(result)", "sql": "SELECT name FROM Country WHERE id IN ( SELECT country_id FROM League WHERE name = 'Poland Ekstraklasa' )", "difficulty": "simple" }, { "question_id": 1139, "question": "What was the final score for the match on September 24, 2008, in the Belgian Jupiler League between the home team and the away team?", "db_id": "european_football_2", "evidence": "September 24, 2008 refers to date like '2008-09-24%'; in the Belgian Jupiler League refers to League.name = 'Belgium Jupiler League'; final score for home team refers to home_team_goal; final score for away team refers to away_team_goal", "code": "import pandas as pd\n\n# Merge League and Match tables\nmerged = pd.merge(Match, League, left_on='league_id', right_on='id')\n\n# Filter for Belgium Jupiler League and date starting with 2008-09-24\nfiltered = merged[(merged['name'] == 'Belgium Jupiler League') & (merged['date'].str.startswith('2008-09-24'))]\n\n# Select only the required columns\nresult = filtered[['home_team_goal', 'away_team_goal']]", "sql": "SELECT t2.home_team_goal, t2.away_team_goal FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t1.name = 'Belgium Jupiler League' AND t2.`date` LIKE '2008-09-24%'", "difficulty": "challenging" }, { "question_id": 1140, "question": "What are Alexis Blin's sprint speed, agility, and acceleration scores?", "db_id": "european_football_2", "evidence": "player_name equals 'Alexis Blin' in the database;", "code": "import pandas as pd\n\ndef solve_query(player_df, player_attributes_df):\n # Check if required columns exist\n if 'player_name' not in player_df.columns or 'player_api_id' not in player_df.columns:\n return pd.DataFrame(columns=['sprint_speed', 'agility', 'acceleration'])\n\n if 'player_api_id' not in player_attributes_df.columns or 'sprint_speed' not in player_attributes_df.columns \\\n or 'agility' not in player_attributes_df.columns or 'acceleration' not in player_attributes_df.columns:\n return pd.DataFrame(columns=['sprint_speed', 'agility', 'acceleration'])\n\n try:\n # Filter player DataFrame for 'Alexis Blin'\n alexis_blin = player_df[player_df['player_name'] == 'Alexis Blin']\n\n # Get player_api_id of Alexis Blin\n player_api_id = alexis_blin['player_api_id']\n\n # Filter Player_Attributes based on player_api_id\n result = player_attributes_df[player_attributes_df['player_api_id'].isin(player_api_id)]\n\n # Select relevant columns\n result = result[['sprint_speed', 'agility', 'acceleration']]\n\n return result\n\n except Exception as e:\n return pd.DataFrame(columns=['sprint_speed', 'agility', 'acceleration'])\n\n# Example function call with placeholder DataFrames\n# Replace these with actual data in practice\nplayer_data = pd.DataFrame({\n 'player_api_id': [1, 2, 3],\n 'player_name': ['John Doe', 'Alexis Blin', 'Jane Smith']\n})\n\nplayer_attributes_data = pd.DataFrame({\n 'player_api_id': [2, 3],\n 'sprint_speed': [75, 80],\n 'agility': [68, 72],\n 'acceleration': [85, 90]\n})\n\nresult = solve_query(player_data, player_attributes_data)\nprint(result)", "sql": "SELECT sprint_speed, agility, acceleration FROM Player_Attributes WHERE player_api_id IN ( SELECT player_api_id FROM Player WHERE player_name = 'Alexis Blin' )", "difficulty": "simple" }, { "question_id": 1141, "question": "Does the KSV Cercle Brugge team have a slow, balanced or fast speed class?", "db_id": "european_football_2", "evidence": "KSV Cercle Brugge refers to team_long_name = 'KSV Cercle Brugge'; speed class refers to buildUpPlaySpeedClass", "code": "import pandas as pd\nmerged = pd.merge(Team_Attributes, Team, on='team_api_id')\nfiltered = merged[merged['team_long_name'] == 'KSV Cercle Brugge']\nresult = filtered[['buildUpPlaySpeedClass']].drop_duplicates()", "sql": "SELECT DISTINCT t1.buildUpPlaySpeedClass FROM Team_Attributes AS t1 INNER JOIN Team AS t2 ON t1.team_api_id = t2.team_api_id WHERE t2.team_long_name = 'KSV Cercle Brugge'", "difficulty": "moderate" }, { "question_id": 1142, "question": "In the 2015–2016 season, how many games were played in the Italian Serie A league?", "db_id": "european_football_2", "evidence": "season equals '2015/2016' in the database; ratio calculated by dividing 2015 by 2016;", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\nCountry = pd.read_csv('Country.csv')\nLeague = pd.read_csv('League.csv')\nMatch = pd.read_csv('Match.csv')\n\n# 进行JOIN操作\nmerged_df = pd.merge(Country, League, left_on='id', right_on='country_id', how='inner')\nmerged_df = pd.merge(merged_df, Match, left_on='id_y', right_on='league_id', how='inner')\n\n# 筛选条件\nfiltered_df = merged_df.query('name_x == \"Italy\" and name_y == \"Serie A\" and season == \"2015/2016\"')\n\n# 计算比赛数量\nmatch_count = filtered_df['id_y'].count()\n\n# 输出结果\nprint(match_count)", "sql": "SELECT COUNT(t2.id) FROM Country AS t0 INNER JOIN League AS t1 ON t0.id = t1.country_id INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t0.name = 'Italy' AND t1.name = 'Serie A' AND t2.season = '2015/2016'", "difficulty": "simple" }, { "question_id": 1143, "question": "What was the highest score of the home team in the Netherlands Eredivisie league?", "db_id": "european_football_2", "evidence": "highest score of the home team refers to MAX(home_team_goal)", "code": "import pandas as pd\n\n# Assume League and Match DataFrames exist\nmerged = pd.merge(League, Match, left_on='id', right_on='league_id')\nfiltered = merged[merged['name'] == 'Netherlands Eredivisie']\nresult = filtered['home_team_goal'].max()", "sql": "SELECT MAX(t2.home_team_goal) FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t1.name = 'Netherlands Eredivisie'", "difficulty": "simple" }, { "question_id": 1144, "question": "Please state the finishing rate and curve score of the player who has the heaviest weight.", "db_id": "european_football_2", "evidence": "finishing rate refer to finishing; curve score refer to curve; heaviest weight refers to MAX(weight)", "code": "import pandas as pd\n# 找到体重最大的球员ID\nmax_player_id = Player.loc[Player['weight'].idxmax(), 'player_api_id']\n# 筛选该球员的最新属性记录\nresult = Player_Attributes[Player_Attributes['player_api_id'] == max_player_id] \\\n .sort_values('date', ascending=False) \\\n [['finishing', 'curve']].head(1)", "sql": "SELECT finishing, curve FROM Player_Attributes WHERE player_api_id = ( SELECT player_api_id FROM Player ORDER BY weight DESC LIMIT 1 ) ORDER BY date DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1145, "question": "Which top 4 leagues had the most games in the 2015-2016 season?", "db_id": "european_football_2", "evidence": "in the 2015-2016 season refers to season = '2015/2016'; league with most games refers to League.name where MAX(COUNT(id))", "code": "import pandas as pd\nmerged = pd.merge(League, Match, left_on='id', right_on='league_id')\nfiltered = merged[merged['season'] == '2015/2016']\ngrouped = filtered.groupby('name')['id_y'].count().reset_index()\ngrouped.columns = ['name', 'game_count']\nresult = grouped.sort_values('game_count', ascending=False).head(4)['name']", "sql": "SELECT t1.name FROM League AS t1 INNER JOIN Match AS t2 ON t1.id = t2.league_id WHERE t2.season = '2015/2016' GROUP BY t1.name ORDER BY COUNT(t2.id) DESC LIMIT 4", "difficulty": "simple" }, { "question_id": 1146, "question": "Please provide the full name of the away team that scored the most goals.", "db_id": "european_football_2", "evidence": "full name refers to team_long_name; away team refers to away_team_api_id; scored the most goals refers to MAX(away_team_goal)", "code": "import pandas as pd\n\nmatch_df = pd.read_csv('Match.csv')\nteam_df = pd.read_csv('Team.csv')\n\nmerged_df = pd.merge(match_df, team_df, left_on='away_team_api_id', right_on='team_api_id')\nsorted_df = merged_df.sort_values(by='away_team_goal', ascending=False)\nresult = sorted_df[['team_long_name']].head(1).reset_index(drop=True)", "sql": "SELECT t2.team_long_name FROM Match AS t1 INNER JOIN Team AS t2 ON t1.away_team_api_id = t2.team_api_id ORDER BY t1.away_team_goal DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1147, "question": "Please name one player whose overall strength is the greatest.", "db_id": "european_football_2", "evidence": "overall strength is the greatest refers to MAX(overall_rating)", "code": "import pandas as pd\nmax_rating = Player_Attributes['overall_rating'].max()\nmax_rating_players = Player_Attributes[Player_Attributes['overall_rating'] == max_rating]\nresult = pd.merge(Player, max_rating_players, on='player_api_id')[['player_name']].drop_duplicates()", "sql": "SELECT DISTINCT t1.player_name FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t2.overall_rating = ( SELECT MAX(overall_rating) FROM Player_Attributes)", "difficulty": "simple" }, { "question_id": 1148, "question": "What is the percentage of players that are under 180 cm who have an overall strength of more than 70?", "db_id": "european_football_2", "evidence": "overall_rating is greater than 70 in the database; height is less than 180 in the database; count of height < 180 AND overall_rating > 70; count of id;", "code": "import pandas as pd\nmerged = pd.merge(Player, Player_Attributes, on='player_api_id')\nfiltered = merged[merged['height'] < 180]\nresult = (filtered[filtered['overall_rating'] > 70].shape[0] / filtered.shape[0]) * 100", "sql": "SELECT CAST(COUNT(CASE WHEN t2.overall_rating > 70 THEN t1.id ELSE NULL END) AS REAL) * 100 / COUNT(t1.id) percent FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.height < 180", "difficulty": "moderate" }, { "question_id": 1149, "question": "Are there more in-patient or outpatient who were male? What is the deviation in percentage?", "db_id": "thrombosis_prediction", "evidence": "male refers to SEX = 'M'; in-patient refers to Admission = '+'; outpatient refers to Admission = '-'; percentage = DIVIDE(COUNT(ID) where SEX = 'M' and Admission = '+', COUNT(ID) where SEX  = 'M' and Admission = '-')in-patient count refers to SUM(CASE WHEN Admission = '+' THEN 1 ELSE 0 END); outpatient count refers to SUM(CASE WHEN Admission = '-' THEN 1 ELSE 0 END); deviation percentage refers to (in-patient count - outpatient count) * 100 / outpatient count", "code": "import pandas as pd\nmale_patients = Patient[Patient['SEX'] == 'M']\ninpatient = (male_patients['Admission'] == '+').sum()\noutpatient = (male_patients['Admission'] == '-').sum()\npercentage = abs((inpatient - outpatient) * 100 / outpatient)\nresult = pd.DataFrame({'InPatientCount': [inpatient], 'OutPatientCount': [outpatient], 'PercentageDeviation': [percentage]})", "sql": "WITH MalePatientCounts AS (\n SELECT \n SUM(CASE WHEN Admission = '+' THEN 1 ELSE 0 END) AS InPatientCount,\n SUM(CASE WHEN Admission = '-' THEN 1 ELSE 0 END) AS OutPatientCount\n FROM Patient\n WHERE SEX = 'M'\n)\nSELECT \n InPatientCount, \n OutPatientCount, \n ABS((InPatientCount - OutPatientCount) * 100.0 / OutPatientCount) AS PercentageDeviation\nFROM MalePatientCounts;", "difficulty": "moderate" }, { "question_id": 1150, "question": "What is the percentage of female patient were born after 1930?", "db_id": "thrombosis_prediction", "evidence": "female refers to Sex = 'F'; patient who were born after 1930 refers to year(Birthday) > '1930'; calculation = DIVIDE(COUNT(ID) where year(Birthday) > '1930' and SEX = 'F'), (COUNT(ID) where SEX = 'F')", "code": "import pandas as pd\nPatient['Birthday'] = pd.to_datetime(Patient['Birthday'])\nfemale_patients = Patient[Patient['SEX'] == 'F']\nfemale_after_1930 = female_patients[female_patients['Birthday'].dt.year > 1930]\nresult = (len(female_after_1930) / len(female_patients)) * 100", "sql": "SELECT CAST(SUM(CASE WHEN STRFTIME('%Y', Birthday) > '1930' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) FROM Patient WHERE SEX = 'F'", "difficulty": "moderate" }, { "question_id": 1151, "question": "For patient born between Year 1930 to 1940, how many percent of them were inpatient?", "db_id": "thrombosis_prediction", "evidence": "patient born between Year 1930 to 1940 refers to year(Birthday) BETWEEN '1930-01-01' AND '1940-12-31'; inpatient refers to Admission = '+'", "code": "import pandas as pd\n\n# Filter patients born between 1930 and 1940\nfiltered_patients = Patient[(Patient['Birthday'] >= '1930-01-01') & (Patient['Birthday'] <= '1940-12-31')]\n\n# Calculate percentage of inpatients\ninpatient_count = (filtered_patients['Admission'] == '+').sum()\ntotal_count = len(filtered_patients)\npercentage = (inpatient_count / total_count) * 100 if total_count > 0 else 0\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(SUM(CASE WHEN Admission = '+' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) FROM Patient WHERE STRFTIME('%Y', Birthday) BETWEEN '1930' AND '1940'", "difficulty": "moderate" }, { "question_id": 1152, "question": "What is the ratio of outpatient to inpatient followed up treatment among all the 'SLE' diagnosed patient?", "db_id": "thrombosis_prediction", "evidence": "'SLE' diagnosed patient means Diagnosis = 'SLE'; inpatient refers to Admission = '+'; outpatient refers to Admission = '-'; calculation = DIVIDE(COUNT(ID) where Diagnosis = 'SLE' and Admission = '+', COUNT(ID) where Diagnosis = 'SLE' and Admission = '-')", "code": "import pandas as pd\nsle_mask = Patient['Diagnosis'] == 'SLE'\nadm_counts = Patient.loc[sle_mask, 'Admission'].value_counts()\nresult = adm_counts.get('-', 0) / adm_counts.get('+', 0)", "sql": "SELECT SUM(CASE WHEN Admission = '-' THEN 1.0 ELSE 0 END) / SUM(CASE WHEN Admission = '+' THEN 1.0 ELSE 0 END) FROM Patient WHERE Diagnosis = 'SLE'", "difficulty": "moderate" }, { "question_id": 1153, "question": "What is the disease patient '30609' diagnosed with. List all the date of laboratory tests done for this patient.", "db_id": "thrombosis_prediction", "evidence": "'30609' is the Patient ID; disease means Diagnosis", "code": "import pandas as pd\n\n# Filter patient with ID 30609\npatient_30609 = Patient[Patient['ID'] == 30609]\n\n# Get diagnosis for this patient\ndiagnosis = patient_30609['Diagnosis'].values[0] if len(patient_30609) > 0 else None\n\n# Get all laboratory test dates for this patient\nlab_tests = Laboratory[Laboratory['ID'] == 30609]['Date']\n\n# Combine results\nresult = pd.DataFrame({\n 'Diagnosis': [diagnosis] * len(lab_tests),\n 'Date': lab_tests.values\n})", "sql": "SELECT T1.Diagnosis, T2.Date FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.ID = 30609", "difficulty": "simple" }, { "question_id": 1154, "question": "State the sex and birthday of patient ID '163109'. When was the examination taken and what symptom does the patient had.", "db_id": "thrombosis_prediction", "evidence": "When was the examination taken refers to `Examination Date`", "code": "import pandas as pd\n\ndef solve_query(patient_df, examination_df):\n # Check if necessary columns exist\n if 'ID' not in patient_df.columns or 'ID' not in examination_df.columns:\n return pd.DataFrame(columns=['SEX', 'Birthday', 'Examination Date', 'Symptoms'])\n\n # Filter for patient with ID 163109\n patient_filtered = patient_df[patient_df['ID'] == 163109]\n\n # Merge patient and examination data on ID\n merged_data = pd.merge(patient_filtered, examination_df, on='ID', how='inner')\n\n # Select required columns\n result = merged_data[['SEX', 'Birthday', 'Examination Date', 'Symptoms']]\n\n # Convert 'Examination Date' to datetime if it exists and is not already datetime\n if 'Examination Date' in result.columns:\n result['Examination Date'] = pd.to_datetime(result['Examination Date'], errors='coerce')\n\n return result\n\n# Example usage\ndata_patient = {\n 'ID': [163109],\n 'SEX': ['Male'],\n 'Birthday': ['1985-04-20'],\n 'Description': [None],\n 'First Date': [None],\n 'Admission': [None],\n 'Diagnosis': [None]\n}\ndata_examination = {\n 'ID': [163109],\n 'Examination Date': ['2023-01-15'],\n 'aCL IgG': [None],\n 'aCL IgM': [None],\n 'ANA': [None],\n 'ANA Pattern': [None],\n 'aCL IgA': [None],\n 'Diagnosis': [None],\n 'KCT': [None],\n 'RVVT': [None],\n 'LAC': [None],\n 'Symptoms': ['Fever'],\n 'Thrombosis': [None]\n}\n\n# Create DataFrames\npatient_df = pd.DataFrame(data_patient)\nexamination_df = pd.DataFrame(data_examination)\n\n# Call the function\nresult = solve_query(patient_df, examination_df)\nprint(result)", "sql": "SELECT T1.SEX, T1.Birthday, T2.`Examination Date`, T2.Symptoms FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.ID = 163109", "difficulty": "simple" }, { "question_id": 1155, "question": "List the patient ID, sex and birthday of patient with LDH beyond normal range.", "db_id": "thrombosis_prediction", "evidence": "LDH beyond normal range refers to LDH > '500';", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if required columns exist\n if 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns:\n return pd.DataFrame(columns=['ID', 'SEX', 'Birthday'])\n if 'LDH' not in laboratory_df.columns:\n return pd.DataFrame(columns=['ID', 'SEX', 'Birthday'])\n\n # Filter Laboratory DataFrame where LDH > 500\n try:\n filtered_lab = laboratory_df[laboratory_df['LDH'] > 500]\n except TypeError:\n laboratory_df['LDH'] = pd.to_numeric(laboratory_df['LDH'], errors='coerce')\n filtered_lab = laboratory_df[laboratory_df['LDH'] > 500]\n\n # Merge with Patient table on ID\n merged_df = pd.merge(patient_df, filtered_lab, on='ID', how='inner')\n\n # Select distinct ID, SEX, and Birthday\n result = merged_df[['ID', 'SEX', 'Birthday']].drop_duplicates()\n\n return result\n\n# Example usage (replace the DataFrames with actual data)\npatient_data = pd.DataFrame({'ID': [1, 2, 3], 'SEX': ['M', 'F', 'M'], 'Birthday': ['1990-01-01', '1985-05-15', '1970-12-12']})\nlaboratory_data = pd.DataFrame({'ID': [1, 2, 3], 'Date': ['2023-01-01', '2023-01-02', '2023-01-03'], 'LDH': [600, 400, 700]})\n\nresult = solve_query(patient_data, laboratory_data)\nprint(result)", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.LDH > 500", "difficulty": "simple" }, { "question_id": 1156, "question": "State the ID and age of patient with positive degree of coagulation.", "db_id": "thrombosis_prediction", "evidence": "age refers to SUBTRACT(year(current_timestamp), year(Birthday)); positive degree of coagulation refers to RVVT = '+';", "code": "import pandas as pd\n\ndef solve_query(patient_df, examination_df):\n # Ensure 'Birthday' column exists and is converted to datetime\n if 'Birthday' in patient_df.columns:\n patient_df['Birthday'] = pd.to_datetime(patient_df['Birthday'], errors='coerce')\n else:\n raise KeyError(\"'Birthday' column is missing in patient_df\")\n\n # Ensure 'RVVT' column exists in examination_df\n if 'RVVT' not in examination_df.columns:\n raise KeyError(\"'RVVT' column is missing in examination_df\")\n\n # Filter rows where RVVT is '+'\n positive_rvvt = examination_df[examination_df['RVVT'] == '+']\n\n # Merge with patient data on ID\n merged_data = pd.merge(positive_rvvt, patient_df, how='inner', on='ID')\n\n # Calculate age using current year minus birth year\n current_year = pd.Timestamp.now().year\n merged_data['Age'] = merged_data['Birthday'].dt.year.apply(\n lambda x: current_year - x if pd.notnull(x) else None\n )\n\n # Select distinct ID and Age\n result = merged_data[['ID', 'Age']].drop_duplicates()\n\n return result\n\n# Example function call (replace with actual DataFrames)\n# result = solve_query(patient_df, examination_df)\n# print(result)", "sql": "SELECT DISTINCT T1.ID, STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T2.RVVT = '+'", "difficulty": "moderate" }, { "question_id": 1157, "question": "For patients with severe degree of thrombosis, list their ID, sex and disease the patient is diagnosed with.", "db_id": "thrombosis_prediction", "evidence": "severe degree of thrombosis refers to thrombosis = 2; disease refers to diagnosis;", "code": "import pandas as pd\n\n# Read the tables from CSV files\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\n\n# Filter patients with severe degree of thrombosis (thrombosis = 2)\nsevere_thrombosis_patients = examination_df[examination_df['Thrombosis'] == 2]\n\n# Merge with the Patient table to get ID, sex, and diagnosis\nresult = pd.merge(severe_thrombosis_patients[['ID']], patient_df[['ID', 'SEX', 'Diagnosis']], on='ID')\n\n# Print the result\nprint(result)", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Diagnosis FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T2.Thrombosis = 2", "difficulty": "simple" }, { "question_id": 1158, "question": "List all patients who were born in 1937 whose total cholesterol was beyond the normal range.", "db_id": "thrombosis_prediction", "evidence": "who were born in 1937 refers to year(birthday) = '1937'; total cholesterol was beyond the normal range refers to `T-CHO` > = '250'", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter patients born in 1937 and with T-CHO >= 250\nfiltered = merged[(pd.to_datetime(merged['Birthday']).dt.year == 1937) & (merged['T-CHO'] >= 250)]\n\n# Get unique patient IDs\nresult = filtered[['ID']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE STRFTIME('%Y', T1.Birthday) = '1937' AND T2.`T-CHO` >= 250", "difficulty": "moderate" }, { "question_id": 1159, "question": "For patient with albumin level lower than 3.5, list their ID, sex and diagnosis.", "db_id": "thrombosis_prediction", "evidence": "albumin level lower than 3.5 refers to ALB < 3.5;", "code": "import pandas as pd\n\ndef solve_query(patient_data, laboratory_data):\n # Ensure the required columns are present before processing\n if 'ALB' not in laboratory_data.columns or 'ID' not in laboratory_data.columns:\n return pd.DataFrame(columns=['ID', 'SEX', 'Diagnosis'])\n\n if 'ID' not in patient_data.columns or 'SEX' not in patient_data.columns or 'Diagnosis' not in patient_data.columns:\n return pd.DataFrame(columns=['ID', 'SEX', 'Diagnosis'])\n\n try:\n # Filter laboratory data for ALB < 3.5\n filtered_laboratory = laboratory_data[laboratory_data['ALB'] < 3.5]\n\n # Merge with patient data on ID\n merged_data = pd.merge(patient_data, filtered_laboratory, on='ID', how='inner')\n\n # Select distinct ID, SEX, Diagnosis from the merged data\n result = merged_data[['ID', 'SEX', 'Diagnosis']].drop_duplicates()\n\n return result\n except Exception as e:\n return pd.DataFrame(columns=['ID', 'SEX', 'Diagnosis'])\n\n# Example usage\ndata_patient = pd.DataFrame({'ID': [1, 2, 3], 'SEX': ['M', 'F', 'M'], 'Diagnosis': ['A', 'B', 'C']})\ndata_lab = pd.DataFrame({'ID': [1, 2, 4], 'ALB': [3.0, 4.0, 3.2]})\nresult = solve_query(data_patient, data_lab)\nprint(result)", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Diagnosis FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.ALB < 3.5", "difficulty": "simple" }, { "question_id": 1160, "question": "What is the percentage of female patient had total protein not within the normal range?", "db_id": "thrombosis_prediction", "evidence": "female refers to sex = 'F'; total protein not within the normal range refers to TP < '6.0' or TP > '8.5'; calculation = DIVIDE((ID where sex = 'F' and TP < '6.0' or TP > '8.5'), COUNT(ID)) * 100", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for female patients\nfemale_data = merged[merged['SEX'] == 'F']\n\n# Count female patients with TP not in normal range (TP < 6.0 or TP > 8.5)\nabnormal_tp_count = len(female_data[(female_data['TP'] < 6.0) | (female_data['TP'] > 8.5)])\n\n# Total count of female patients\ntotal_female_count = len(female_data)\n\n# Calculate percentage\nresult = (abnormal_tp_count / total_female_count) * 100 if total_female_count > 0 else 0", "sql": "SELECT CAST(SUM(CASE WHEN T1.SEX = 'F' AND (T2.TP < 6.0 OR T2.TP > 8.5) THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F'", "difficulty": "moderate" }, { "question_id": 1161, "question": "For in-patient age 50 and above, what is their average anti-cardiolipin antibody (IgG) concentration?", "db_id": "thrombosis_prediction", "evidence": "in-patient refers to Admission = '+'; age 50 and above refers to SUBTRACT(year(current_timestamp), year(Birthday)) >= '50'; average anti-cardiolipin antibody (IgG) concentration refers to AVG(aCL IgG)", "code": "import pandas as pd\n\ndef solve_query(patient_df, examination_df):\n try:\n # Ensure 'Birthday' is datetime type\n if 'Birthday' in patient_df.columns:\n patient_df['Birthday'] = pd.to_datetime(patient_df['Birthday'], errors='coerce')\n\n # Calculate age\n current_year = pd.Timestamp.now().year\n if 'Birthday' in patient_df.columns:\n patient_df['Age'] = patient_df['Birthday'].dt.year.apply(lambda x: current_year - x if pd.notnull(x) else None)\n\n # Filter in-patients aged 50 and above\n filtered_patients = patient_df[(patient_df['Admission'] == '+') & (patient_df['Age'] >= 50)]\n\n # Merge with Examination table\n merged_data = pd.merge(filtered_patients, examination_df, left_on='ID', right_on='ID', how='inner')\n\n # Calculate average aCL IgG concentration\n if 'aCL IgG' in merged_data.columns:\n avg_acl_igg = merged_data['aCL IgG'].mean()\n return avg_acl_igg\n else:\n return None\n except Exception as e:\n return None\n\n# Example function call with placeholder DataFrames\n# Replace these with actual data\n# patient_df = pd.DataFrame({...})\n# examination_df = pd.DataFrame({...})\n# result = solve_query(patient_df, examination_df)\n# print(result)", "sql": "SELECT AVG(T2.`aCL IgG`) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) >= 50 AND T1.Admission = '+'", "difficulty": "challenging" }, { "question_id": 1162, "question": "How many female patients who came at the hospital in 1997 was immediately followed at the outpatient clinic?", "db_id": "thrombosis_prediction", "evidence": "female refers to sex = 'F'; came at the hospital in 1997 refers to year(Description) = '1997'; immediately followed at the outpatient clinic refers to Admission = '-'", "code": "import pandas as pd\nPatient['Description'] = pd.to_datetime(Patient['Description'])\nfiltered = Patient[(Patient['Description'].dt.year == 1997) & (Patient['SEX'] == 'F') & (Patient['Admission'] == '-')]\nresult = len(filtered)", "sql": "SELECT COUNT(*) FROM Patient WHERE STRFTIME('%Y', Description) = '1997' AND SEX = 'F' AND Admission = '-'", "difficulty": "moderate" }, { "question_id": 1163, "question": "What was the age of the youngest patient when they initially arrived at the hospital?", "db_id": "thrombosis_prediction", "evidence": "age refers to SUBTRACT(YEAR(`First Date`),YEAR(Birthday))", "code": "import pandas as pd\n\n# Read the Patient table\npatient_df = pd.read_csv('Patient.csv')\n\n# Calculate the age of each patient when they initially arrived at the hospital\npatient_df['Age'] = pd.to_datetime(patient_df['First Date']).dt.year - pd.to_datetime(patient_df['Birthday']).dt.year\n\n# Find the minimum age\nyoungest_age = patient_df['Age'].min()\n\n# Store the result\nresult = youngest_age\n\n# Print the final result\nprint(result)", "sql": "SELECT MIN(STRFTIME('%Y', `First Date`) - STRFTIME('%Y', Birthday)) FROM Patient", "difficulty": "simple" }, { "question_id": 1164, "question": "How many of the patients with the most serious thrombosis cases examined in 1997 are women?", "db_id": "thrombosis_prediction", "evidence": "the most serious thrombosis refers to Thrombosis = '1' (the most severe one); women refers to sex = 'F'", "code": "import pandas as pd\n\n# Merge Patient and Examination tables\nmerged = pd.merge(Patient, Examination, on='ID')\n\n# Filter for female patients\nmerged = merged[merged['SEX'] == 'F']\n\n# Convert Examination Date to datetime and extract year\nmerged['Examination Date'] = pd.to_datetime(merged['Examination Date'])\nmerged = merged[merged['Examination Date'].dt.year == 1997]\n\n# Filter for most serious thrombosis cases (Thrombosis = 1)\nmerged = merged[merged['Thrombosis'] == 1]\n\n# Count unique patients\nresult = merged['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND STRFTIME('%Y', T2.`Examination Date`) = '1997' AND T2.Thrombosis = 1", "difficulty": "moderate" }, { "question_id": 1165, "question": "What is the age gap between the youngest and oldest patient with a normal triglyceride recorded?", "db_id": "thrombosis_prediction", "evidence": "age gap refers to SUBTRACT(MAX(year(Birthday)) - MIN(year(Birthday))); normal triglyceride refers to tg > = 200", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for normal triglyceride (TG >= 200)\nfiltered = merged[merged['TG'] >= 200]\n\n# Extract year from Birthday\nfiltered['Birth_Year'] = pd.to_datetime(filtered['Birthday']).dt.year\n\n# Calculate age gap\nmax_year = filtered['Birth_Year'].max()\nmin_year = filtered['Birth_Year'].min()\nresult = max_year - min_year", "sql": "SELECT STRFTIME('%Y', MAX(T1.Birthday)) - STRFTIME('%Y', MIN(T1.Birthday)) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.TG >= 200", "difficulty": "moderate" }, { "question_id": 1166, "question": "What are the symptoms observed by the youngest patient to ever did a medical examination? Identify their diagnosis.", "db_id": "thrombosis_prediction", "evidence": "The larger the birthday value, the younger the person is, and vice versa; symptoms observed refers to the symptoms is not NULL", "code": "import pandas as pd\n\n# 读取患者和检查数据 \npatient_df = pd.read_csv ('Patient.csv')\nexamination_df = pd.read_csv ('Examination.csv')\n\n# 合并两个数据集 \nmerged_df = pd.merge (\n patient_df,\n examination_df,\n on='ID',\n how='inner'\n)\n\n# 筛选有症状记录的行 \nfiltered_df = merged_df [merged_df ['Symptoms'].notna ()]\n\n# 按生日降序排序(最新生日即最年轻)\nsorted_df = filtered_df.sort_values (by='Birthday', ascending=False)\n\n# 取第一条记录并选择需要的列 \nresult = sorted_df.head (1)[['Symptoms', 'Diagnosis_x']]\n\n# 输出结果 \nprint (result)", "sql": "SELECT T2.Symptoms, T1.Diagnosis FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T2.Symptoms IS NOT NULL ORDER BY T1.Birthday DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1167, "question": "For the year that concluded on December 31, 1998, how many male patients on average were tested in the lab each month?", "db_id": "thrombosis_prediction", "evidence": "the year that concluded on December 31, 1998 refers to Date BETWEEN '1998-01-01' AND '1998-12-31'; male refers to SEX = 'M'; calculation = DIVIDE(COUNT(ID), 12)", "code": "import pandas as pd\nimport numpy as np\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for year 1998 and male patients\nfiltered = merged[(merged['Date'] >= '1998-01-01') & (merged['Date'] <= '1998-12-31') & (merged['SEX'] == 'M')]\n\n# Count unique patient IDs and divide by 12 months\nresult = len(filtered['ID'].unique()) / 12", "sql": "SELECT CAST(COUNT(T1.ID) AS REAL) / 12 FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE STRFTIME('%Y', T2.Date) = '1998' AND T1.SEX = 'M'", "difficulty": "moderate" }, { "question_id": 1168, "question": "The oldest SJS patient's medical laboratory work was completed on what date, and what age was the patient when they initially arrived at the hospital?", "db_id": "thrombosis_prediction", "evidence": "The larger the birthday value, the younger the person is, and vice versa; 'SJS' refers to diagnosis; (SUBTRACT(year(`First Date`)), year(Birthday)); age of the patients when they initially arrived at the hospital refers to year(Birthday)", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nmerged['Birthday'] = pd.to_datetime(merged['Birthday'])\nmerged['First Date'] = pd.to_datetime(merged['First Date'])\nmerged['Date'] = pd.to_datetime(merged['Date'])\nfiltered = merged[(merged['Diagnosis'] == 'SJS') & merged['Birthday'].notnull() & (merged['Date'] == merged['First Date'])]\nfiltered['InitialAge'] = filtered['First Date'].dt.year - filtered['Birthday'].dt.year\nresult = filtered.sort_values('Birthday').head(1)[['Date', 'InitialAge']]", "sql": "SELECT T1.Date, STRFTIME('%Y', T2.`First Date`) - STRFTIME('%Y', T2.Birthday) AS InitialAge FROM Laboratory AS T1 INNER JOIN Patient AS T2 ON T1.ID = T2.ID WHERE T2.Diagnosis = 'SJS' AND T2.Birthday IS NOT NULL AND T1.Date = T2.`First Date` ORDER BY T2.Birthday ASC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1169, "question": "What is the ratio of male to female patients among all those with abnormal uric acid counts?", "db_id": "thrombosis_prediction", "evidence": "male refers to SEX = 'M'; female refers to SEX = 'F'; abnormal uric acid refers to UA < = '8.0' where SEX = 'M', UA < = '6.5' where SEX = 'F'; calculation = DIVIDE(SUM(UA <= '8.0' and SEX = 'M'), SUM(UA <= '6.5 and SEX = 'F'))", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if necessary columns exist\n if 'SEX' not in patient_df.columns or 'UA' not in laboratory_df.columns or 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns:\n return None\n\n # Merge DataFrames on ID\n merged_df = pd.merge(patient_df, laboratory_df, on='ID', how='inner')\n\n # Handle NULL values in SEX and UA\n merged_df['SEX'] = merged_df['SEX'].fillna('Unknown')\n merged_df['UA'] = pd.to_numeric(merged_df['UA'], errors='coerce')\n\n # Calculate counts for male and female with abnormal uric acid\n male_count = merged_df[(merged_df['UA'] <= 8.0) & (merged_df['SEX'] == 'M')].shape[0]\n female_count = merged_df[(merged_df['UA'] <= 6.5) & (merged_df['SEX'] == 'F')].shape[0]\n\n # Avoid division by zero\n if female_count == 0:\n return None\n\n # Calculate ratio\n ratio = male_count / female_count\n return ratio\n\n# Example usage - assuming dataframes are loaded from CSV files or other sources\n# patient_df = pd.read_csv('Patient.csv')\n# laboratory_df = pd.read_csv('Laboratory.csv')\n# result = solve_query(patient_df, laboratory_df)\n# print(result)\n\n# Function call with placeholder dataframes\nresult = solve_query(pd.DataFrame({'ID': [1, 2], 'SEX': ['M', 'F']}), pd.DataFrame({'ID': [1, 2], 'UA': [7.5, 6.0]}))\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN T2.UA <= 8.0 AND T1.SEX = 'M' THEN 1 ELSE 0 END) AS REAL) / SUM(CASE WHEN T2.UA <= 6.5 AND T1.SEX = 'F' THEN 1 ELSE 0 END) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID", "difficulty": "challenging" }, { "question_id": 1170, "question": "How many patients hadn't undergone a medical examination until at least a year following their initial hospital visit?", "db_id": "thrombosis_prediction", "evidence": "hadn't undergone a medical examination until at least a year refers to SUBTRACT(year(`Examination Date`), year(`First Date`)) > = 1", "code": "import pandas as pd\n\n# Merge Patient and Examination tables\nmerged = pd.merge(Patient, Examination, on='ID')\n\n# Filter for admitted patients\nfiltered = merged[merged['Admission'] == '+']\n\n# Convert dates to datetime\nfiltered['First Date'] = pd.to_datetime(filtered['First Date'])\nfiltered['Examination Date'] = pd.to_datetime(filtered['Examination Date'])\n\n# Calculate year difference\nfiltered['year_diff'] = filtered['Examination Date'].dt.year - filtered['First Date'].dt.year\n\n# Filter patients with examination at least 1 year after first visit\nqualifying_patients = filtered[filtered['year_diff'] >= 1]\n\n# Count distinct patient IDs\nresult = qualifying_patients['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 LEFT JOIN Examination AS T2 ON T1.ID = T2.ID WHERE (JULIANDAY(T2.`Examination Date`) - JULIANDAY(T1.`First Date`) >= 365 OR T2.ID IS NULL)", "difficulty": "moderate" }, { "question_id": 1171, "question": "How many underage patients were examined during the course of the three-year period from 1990 to 1993?", "db_id": "thrombosis_prediction", "evidence": "underage patients refers to year(Birthday) < 18; three-year period from 1990 to 1993 refers to year(`Examination Date`) between '1990' and '1993'", "code": "import pandas as pd\nimport numpy as np\n\n# Merge Patient and Examination tables\nmerged = pd.merge(Patient, Examination, on='ID')\n\n# Convert dates to datetime\nmerged['Birthday'] = pd.to_datetime(merged['Birthday'])\nmerged['Examination Date'] = pd.to_datetime(merged['Examination Date'])\n\n# Filter for examination dates between 1990 and 1993\nfiltered = merged[(merged['Examination Date'].dt.year >= 1990) & (merged['Examination Date'].dt.year <= 1993)]\n\n# Calculate age at examination\nfiltered['age_at_exam'] = (filtered['Examination Date'].dt.year - filtered['Birthday'].dt.year)\n\n# Filter for underage patients (age < 18)\nunderage = filtered[filtered['age_at_exam'] < 18]\n\n# Count distinct patients\nresult = underage['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE STRFTIME('%Y', T2.`Examination Date`) BETWEEN '1990' AND '1993' AND STRFTIME('%Y', T2.`Examination Date`) - STRFTIME('%Y', T1.Birthday) < 18", "difficulty": "challenging" }, { "question_id": 1172, "question": "How many male patients have elevated total bilirubin count?", "db_id": "thrombosis_prediction", "evidence": "male refers to SEX = 'M'; elevated means above the normal range; total bilirubin above the normal range refers to `T-BIL` >= '2.0'", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for male patients with elevated T-BIL\nfiltered = merged[(merged['SEX'] == 'M') & (merged['T-BIL'] >= 2.0)]\n\n# Count distinct patient IDs\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.`T-BIL` >= 2.0 AND T1.SEX = 'M'", "difficulty": "simple" }, { "question_id": 1173, "question": "What is the most common illness that doctors identified among the patients whose lab work was done between 1/1/1985, and 12/31/1995?", "db_id": "thrombosis_prediction", "evidence": "the most common illness refers to MAX(COUNT(Diagnosis)); lab work between 1/1/1985 and 12/31/1995 refers to `Examination Date` between '1985-01-01' and '1995-12-31 '", "code": "import pandas as pd\n\ndef solve_query(examination_data, patient_data):\n # Ensure 'Examination Date' is in datetime format\n examination_data['Examination Date'] = pd.to_datetime(examination_data['Examination Date'], errors='coerce')\n\n # Filter data for the specified date range\n filtered_data = examination_data[(examination_data['Examination Date'] >= '1985-01-01') & (examination_data['Examination Date'] <= '1995-12-31')]\n\n # Group by Diagnosis and count occurrences\n diagnosis_counts = filtered_data.groupby('Diagnosis').size().reset_index(name='Count')\n\n # Find the most common diagnosis\n if not diagnosis_counts.empty:\n most_common_diagnosis = diagnosis_counts.loc[diagnosis_counts['Count'].idxmax()]['Diagnosis']\n else:\n most_common_diagnosis = None\n\n return most_common_diagnosis\n\n# Example function call with dummy dataframes\n# Replace these with actual dataframes loaded from your source\nexamination_df = pd.DataFrame({\n 'ID': [1, 2, 3],\n 'Examination Date': ['1986-05-01', '1987-06-01', '1994-07-01'],\n 'Diagnosis': ['Flu', 'Cold', 'Flu']\n})\npatient_df = pd.DataFrame({\n 'ID': [1, 2, 3],\n 'SEX': ['M', 'F', 'M']\n})\n\nresult = solve_query(examination_df, patient_df)\nprint(result)", "sql": "SELECT T1.Diagnosis FROM Examination AS T1 INNER JOIN Patient AS T2 ON T1.ID = T2.ID WHERE T1.`Examination Date` BETWEEN '1985-01-01' AND '1995-12-31' GROUP BY T1.Diagnosis ORDER BY COUNT(T1.Diagnosis) DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1174, "question": "What is the average age of patients as of year 1999 examined in the laboratory for the October of the year 1991?", "db_id": "thrombosis_prediction", "evidence": "average age of patients as of year 1999 refers to AVG(SUBTRACT('1999', year(Birthday))); October of 1991 refers to Date BETWEEN '1991-10-01' AND '1991-10-30'", "code": "import pandas as pd\nimport numpy as np\n\n# Filter Laboratory records for October 1991\nlab_filtered = Laboratory[(Laboratory['Date'] >= '1991-10-01') & (Laboratory['Date'] <= '1991-10-30')]\n\n# Merge with Patient data\nmerged = pd.merge(lab_filtered, Patient, on='ID')\n\n# Calculate age as of 1999\nmerged['Birthday'] = pd.to_datetime(merged['Birthday'])\nmerged['birth_year'] = merged['Birthday'].dt.year\nmerged['age_1999'] = 1999 - merged['birth_year']\n\n# Calculate average age\nresult = merged['age_1999'].mean()", "sql": "SELECT AVG(1999 - CAST(STRFTIME('%Y', T2.Birthday) AS INTEGER)) FROM Laboratory AS T1 INNER JOIN Patient AS T2 ON T1.ID = T2.ID WHERE T1.Date BETWEEN '1991-10-01' AND '1991-10-30'", "difficulty": "moderate" }, { "question_id": 1175, "question": "How old was the patient who had the highest hemoglobin count at the time of the examination, and what is the doctor's diagnosis?", "db_id": "thrombosis_prediction", "evidence": "How old the patient refers to SUBTRACT(year(`Examination Date`), year(Birthday)); the highest hemoglobin count refers to MAX(HGB)How old the patient refers to SUBTRACT(year(`Laboratory.Date`), year(Birthday)); Diagnosis refers to T1.Diagnosis", "code": "import pandas as pd\nimport numpy as np\n\n# Merge tables with proper date alignment\nmerged = pd.merge(Patient, Laboratory, on='ID')\nmerged = pd.merge(merged, Examination, left_on=['ID', 'Date'], right_on=['ID', 'Examination Date'])\n\n# Calculate age using date fields\nmerged['age'] = pd.to_datetime(merged['Date']).dt.year - pd.to_datetime(merged['Birthday']).dt.year\n\n# Find patient with max HGB and extract required fields\nmax_hgb_idx = merged['HGB'].idxmax()\nresult = merged.loc[[max_hgb_idx], ['age', 'Diagnosis_y']].rename(columns={'Diagnosis_y': 'Diagnosis'})", "sql": "SELECT (STRFTIME('%Y', T3.`Examination Date`) - STRFTIME('%Y', T1.Birthday)) AS age, T3.Diagnosis FROM Patient T1 INNER JOIN Laboratory T2 ON T1.ID = T2.ID INNER JOIN Examination T3 ON T1.ID = T3.ID AND T2.Date = T3.`Examination Date` ORDER BY T2.HGB DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1176, "question": "What was the anti-nucleus antibody concentration level for the patient id 3605340 on 1996/12/2?", "db_id": "thrombosis_prediction", "evidence": "anti-nucleus antibody refers to ANA; 1996/12/2 refers to `Examination Date` = '1996-12-02'", "code": "import pandas as pd\n\ndef solve_query(examination_df):\n try:\n # Ensure the required columns exist in the DataFrame\n if 'ID' not in examination_df.columns or 'Examination Date' not in examination_df.columns or 'ANA' not in examination_df.columns:\n return pd.DataFrame(columns=['ANA'])\n\n # Convert 'Examination Date' to datetime if it's not already\n examination_df['Examination Date'] = pd.to_datetime(examination_df['Examination Date'], errors='coerce')\n\n # Filter the DataFrame based on the conditions\n result_df = examination_df[(examination_df['ID'] == 3605340) & (examination_df['Examination Date'] == '1996-12-02')]\n\n # Return only the 'ANA' column as a DataFrame\n return result_df[['ANA']]\n except Exception as e:\n return pd.DataFrame(columns=['ANA'])\n\n# Example usage\n# Assuming `examination_data` is a DataFrame containing the 'Examination' table data\n# result = solve_query(examination_data)\n# print(result)", "sql": "SELECT ANA FROM Examination WHERE ID = 3605340 AND `Examination Date` = '1996-12-02'", "difficulty": "simple" }, { "question_id": 1177, "question": "Was the total cholesterol status for the patient id 2927464 on 1995-9-4 at the normal level?", "db_id": "thrombosis_prediction", "evidence": "N is less than 250 in the database;", "code": "import pandas as pd\nimport numpy as np\n\n# Filter Laboratory data for patient ID 2927464 on date 1995-09-04\nfiltered = Laboratory[(Laboratory['ID'] == 2927464) & (Laboratory['Date'] == '1995-09-04')]\n\n# Check if T-CHO is less than 250 and assign status\nif len(filtered) > 0:\n t_cho_value = filtered['T-CHO'].iloc[0]\n if pd.isna(t_cho_value):\n result = 'No data'\n elif t_cho_value < 250:\n result = 'Normal'\n else:\n result = 'Abnormal'\nelse:\n result = 'No data'\n\nresult", "sql": "SELECT CASE WHEN `T-CHO` < 250 THEN 'Normal' ELSE 'Abnormal' END FROM Laboratory WHERE ID = 2927464 AND Date = '1995-09-04'", "difficulty": "simple" }, { "question_id": 1178, "question": "What was the gender of the first AORTITIS diagnosed patient?", "db_id": "thrombosis_prediction", "evidence": "gender means SEX; 'AORTITIS' refers to Diagnosis;", "code": "import pandas as pd\nfiltered = Patient[Patient['Diagnosis'] == 'AORTITIS']\nfiltered = filtered[filtered['First Date'].notna()]\nfiltered = filtered.sort_values('First Date', ascending=True)\nresult = filtered.iloc[0]['SEX']", "sql": "SELECT Patient.SEX FROM Patient JOIN Examination ON Patient.ID = Examination.ID WHERE Examination.Diagnosis = 'AORTITIS' ORDER BY Examination.`Examination Date` ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1179, "question": "For the patient who was diagnosed with SLE on 1994/2/19, what was his/her anti-Cardiolipin antibody concentration status on 1993/11/12?", "db_id": "thrombosis_prediction", "evidence": "diagnosed with SLE refers to Diagnosis = 'SLE'; 1994/2/19 refers to Description = '1994-02-19'; anti-Cardiolipin refers to aCL IgM; 1993/11/12 refers to Examination Date = '1993/11/12'", "code": "import pandas as pd\n\n# Filter Patient table for SLE diagnosis on specific date\npatient_filtered = Patient[(Patient['Diagnosis'] == 'SLE') & (Patient['Description'] == '1994-02-19')]\n\n# Get the patient IDs\npatient_ids = patient_filtered['ID'].tolist()\n\n# Filter Examination table for these patients on specific examination date\nexam_filtered = Examination[(Examination['ID'].isin(patient_ids)) & (Examination['Examination Date'] == '1993-11-12')]\n\n# Select the anti-Cardiolipin antibody columns\nresult = exam_filtered[['aCL IgA', 'aCL IgG', 'aCL IgM']]", "sql": "SELECT `aCL IgA`, `aCL IgG`, `aCL IgM` FROM Examination WHERE ID IN ( SELECT ID FROM Patient WHERE Diagnosis = 'SLE' AND `First Date` = '1994-02-19' ) AND `Examination Date` = '1993-11-12'", "difficulty": "moderate" }, { "question_id": 1180, "question": "Was the patient a man or a women whose ALT glutamic pylvic transaminase status got 9 on 1992-6-12?", "db_id": "thrombosis_prediction", "evidence": "man refers to SEX = 'M'; women refers to SEX = 'F'; ALT glutamic pylvic transaminase status got 9 GPT = '9'; 1992/6/12 refers to Date = '1992-06-12'", "code": "import pandas as pd\n\n# Assume Patient and Laboratory DataFrames exist\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['GPT'] == 9.0) & (merged['Date'] == '1992-06-12')]\nresult = filtered[['SEX']]", "sql": "SELECT T1.SEX FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GPT = 9.0 AND T2.Date = '1992-06-12'", "difficulty": "moderate" }, { "question_id": 1181, "question": "For the patient who got the laboratory test of uric acid level as 8.4 on 1991-10-21, how old was he/she at that time?", "db_id": "thrombosis_prediction", "evidence": "how old at that time refers to SUBTRACT(year(test date), year(Birthday)); uric acid level as 8.4 refers to UA = '8.4'; 1991/10/21 refers to Date = '1991-10-21'", "code": "import pandas as pd\nimport numpy as np\n\n# Filter Laboratory table for the specific condition\nlab_filtered = Laboratory[(Laboratory['UA'] == 8.4) & (Laboratory['Date'] == '1991-10-21')]\n\n# Merge with Patient table to get birthday\nmerged = pd.merge(lab_filtered, Patient, on='ID')\n\n# Calculate age by extracting years and subtracting\nmerged['test_year'] = pd.to_datetime(merged['Date']).dt.year\nmerged['birth_year'] = pd.to_datetime(merged['Birthday']).dt.year\nmerged['age'] = merged['test_year'] - merged['birth_year']\n\n# Get the age result\nresult = merged['age'].iloc[0]", "sql": "SELECT STRFTIME('%Y', T2.Date) - STRFTIME('%Y', T1.Birthday) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.UA = 8.4 AND T2.Date = '1991-10-21'", "difficulty": "moderate" }, { "question_id": 1182, "question": "For the patient who first came to the hospital on 1991/6/13 who was diagnosed with SJS, what is the total number of his/her Laboratory tests in 1995?", "db_id": "thrombosis_prediction", "evidence": "1991/6/13 refers to `First Date` = '1991-06-13'; 'SJS' refers to Diagnosis; total number of his/her Laboratory tests refers to COUNT(ID); 1995 refers to Date", "code": "import pandas as pd\n\n# Find patient ID who first came on 1991-06-13 with SJS diagnosis\npatient_id = Patient[(Patient['First Date'] == '1991-06-13') & (Patient['Diagnosis'] == 'SJS')]['ID'].values[0]\n\n# Count laboratory tests for this patient in 1995\nLaboratory['Date'] = pd.to_datetime(Laboratory['Date'])\nresult = len(Laboratory[(Laboratory['ID'] == patient_id) & (Laboratory['Date'].dt.year == 1995)])", "sql": "SELECT COUNT(*) FROM Laboratory WHERE ID = ( SELECT ID FROM Patient WHERE `First Date` = '1991-06-13' AND Diagnosis = 'SJS' ) AND STRFTIME('%Y', Date) = '1995'", "difficulty": "moderate" }, { "question_id": 1183, "question": "For the patient who was diagnosed SLE on 1997/1/27, what was his/her original diagnose when he/she came to the hospital for the first time?", "db_id": "thrombosis_prediction", "evidence": "'SLE' AND original diagnose refers to diagnosis; 1997/1/27 refer to `Examination Date` = '1997-01-27'; first came to the hospital refers to patient.`First Date`", "code": "import pandas as pd\n\n# Find patient ID diagnosed with SLE on 1997-01-27\nsle_patient = Examination[Examination['Examination Date'] == '1997-01-27']\nsle_patient = sle_patient[sle_patient['Diagnosis'] == 'SLE']\npatient_id = sle_patient['ID'].iloc[0]\n\n# Get patient's first date\npatient_info = Patient[Patient['ID'] == patient_id]\nfirst_date = patient_info['First Date'].iloc[0]\n\n# Find diagnosis on first visit\nfirst_exam = Examination[(Examination['ID'] == patient_id) & (Examination['Examination Date'] == first_date)]\nresult = first_exam[['Diagnosis']]", "sql": "SELECT T1.Diagnosis FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.ID = ( SELECT ID FROM Examination WHERE `Examination Date` = '1997-01-27' AND Diagnosis = 'SLE' ) AND T2.`Examination Date` = T1.`First Date`", "difficulty": "challenging" }, { "question_id": 1184, "question": "For the patient whose birthday was 1959/3/1, what symptoms did he/she have during the examination on 1993/9/27?", "db_id": "thrombosis_prediction", "evidence": "", "code": "import pandas as pd\n\n# Merge Patient and Examination tables on ID\nmerged = pd.merge(Patient, Examination, on='ID')\n\n# Filter for the specific patient birthday and examination date\nfiltered = merged[(merged['Birthday'] == '1959-03-01') & (merged['Examination Date'] == '1993-09-27')]\n\n# Get the symptoms\nresult = filtered['Symptoms'].values[0] if len(filtered) > 0 else None", "sql": "SELECT T2.Symptoms FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.Birthday = '1959-03-01' AND T2.`Examination Date` = '1993-09-27'", "difficulty": "simple" }, { "question_id": 1185, "question": "For the patient who was born on 1959/2/18, what is the decrease rate for his/her total cholesterol from November to December in 1981?", "db_id": "thrombosis_prediction", "evidence": "born on 1959/2/18 refers to Birthday = '1959-02-18'; calculation = SUBTRACT(SUM(Birthday = '1959-02-18' and Date like '1981-11-%' THEN `T-CHO`), SUM(Birthday = '1959-02-18' and Date like '1981-12-%' THEN `T-CHO`))", "code": "import pandas as pd\nimport numpy as np\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for patient born on 1959-02-18\nfiltered = merged[merged['Birthday'] == '1959-02-18']\n\n# Convert Date to datetime for filtering\nfiltered['Date'] = pd.to_datetime(filtered['Date'])\n\n# Calculate November 1981 total cholesterol\nnov_data = filtered[(filtered['Date'].dt.year == 1981) & (filtered['Date'].dt.month == 11)]\nnov_total = nov_data['T-CHO'].sum()\n\n# Calculate December 1981 total cholesterol\ndec_data = filtered[(filtered['Date'].dt.year == 1981) & (filtered['Date'].dt.month == 12)]\ndec_total = dec_data['T-CHO'].sum()\n\n# Calculate decrease rate\nresult = (nov_total - dec_total) / dec_total", "sql": "SELECT CAST((SUM(CASE WHEN T2.Date LIKE '1981-11-%' THEN T2.`T-CHO` ELSE 0 END) - SUM(CASE WHEN T2.Date LIKE '1981-12-%' THEN T2.`T-CHO` ELSE 0 END)) AS REAL) / SUM(CASE WHEN T2.Date LIKE '1981-12-%' THEN T2.`T-CHO` ELSE 0 END) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Birthday = '1959-02-18'", "difficulty": "challenging" }, { "question_id": 1186, "question": "Lists all patients by ID who were diagnosed with Behcet's and had their exams between 01/01/197 and 12/31/1997.", "db_id": "thrombosis_prediction", "evidence": "'Behcet' refers to diagnosis; exam between 01/01/1997 and 12/31/1997 refers to YEAR(Description) > = '1997-1-1' AND YEAR(Description) < '1998-1-1'exam between 01/01/1997 and 12/31/1997 refers to `Examination Date` BETWEEN '1997-01-01' AND '1997-12-31'", "code": "import pandas as pd\nresult = Examination[(Examination['Examination Date'].between('1997-01-01', '1997-12-31')) & (Examination['Diagnosis'] == 'Behcet')]['ID']", "sql": "SELECT ID FROM Examination WHERE `Examination Date` BETWEEN '1997-01-01' AND '1997-12-31' AND Diagnosis = 'Behcet'", "difficulty": "moderate" }, { "question_id": 1187, "question": "How many patients who were examined between 1987/7/6 and 1996/1/31 had a GPT level greater than 30 and an ALB level less than 4? List them by their ID.", "db_id": "thrombosis_prediction", "evidence": "examined between 1987/7/6 and 1996/1/31 refers to Date BETWEEN '1987-07-06' AND '1996-01-31'; GPT level greater than 30 refers to GPT > 30; ALB level less than 4 ALB < 4", "code": "import pandas as pd\n\n# Filter Laboratory data for patients examined between 1987/7/6 and 1996/1/31 with GPT > 30 and ALB < 4\nfiltered = Laboratory[(Laboratory['Date'] >= '1987-07-06') & (Laboratory['Date'] <= '1996-01-31') & (Laboratory['GPT'] > 30) & (Laboratory['ALB'] < 4)]\n\n# Get unique patient IDs\nresult = filtered[['ID']].drop_duplicates()", "sql": "SELECT DISTINCT ID FROM Laboratory WHERE Date BETWEEN '1987-07-06' AND '1996-01-31' AND GPT > 30 AND ALB < 4", "difficulty": "moderate" }, { "question_id": 1188, "question": "How many female patients born in 1964 were admitted to the hospital? List them by ID.", "db_id": "thrombosis_prediction", "evidence": "female refers to SEX = 'F'; born in 1964 refers to YEAR(Birthday) = 1964; admitted to the hospital refers to Admission = '+'", "code": "import pandas as pd\n\ndef solve_query(patient_data):\n # Ensure the required columns exist\n required_columns = ['ID', 'SEX', 'Birthday', 'Admission']\n for col in required_columns:\n if col not in patient_data.columns:\n return pd.DataFrame(columns=['ID']) # Return empty DataFrame with 'ID' column\n\n # Convert Birthday to datetime, handle errors by coercing invalid dates to NaT\n patient_data['Birthday'] = pd.to_datetime(patient_data['Birthday'], errors='coerce')\n\n # Filter rows based on conditions\n filtered_data = patient_data[\n (patient_data['Birthday'].dt.year == 1964) & \n (patient_data['SEX'] == 'F') & \n (patient_data['Admission'] == '+')\n ]\n\n # Select only the 'ID' column and reset index for cleaner output\n result = filtered_data[['ID']].reset_index(drop=True)\n return result\n\n# Example usage\ndata = {\n 'ID': [1, 2, 3],\n 'SEX': ['F', 'M', 'F'],\n 'Birthday': ['1964-05-12', '1970-08-23', '1964-03-15'],\n 'Admission': ['+', '-', '+']\n}\npatient_df = pd.DataFrame(data)\nresult = solve_query(patient_df)\nprint(result)", "sql": "SELECT ID FROM Patient WHERE STRFTIME('%Y', Birthday) = '1964' AND SEX = 'F' AND Admission = '+'", "difficulty": "simple" }, { "question_id": 1189, "question": "What number of patients with a degree of thrombosis level 2 and ANA pattern of only S, have a level of anti-Cardiolip in antibody (IgM) 20% higher than average?", "db_id": "thrombosis_prediction", "evidence": "thrombosis level 2 refers to Thrombosis = 2; ANA pattern of only S refers to ANA = 'S'; average anti-Cardiolip in antibody (IgM) refers to AVG(`aCL IgM`); calculation = MULTIPLY(AVG + AVG, 0.2)", "code": "import pandas as pd\nimport numpy as np\n\n# Filter for thrombosis level 2 and ANA pattern 'S'\nfiltered_exam = Examination[(Examination['Thrombosis'] == 2) & (Examination['ANA Pattern'] == 'S')]\n\n# Calculate the average aCL IgM for this group\navg_acl_igm = filtered_exam['aCL IgM'].mean()\n\n# Calculate 20% higher than average (which is average * 1.2)\nthreshold = avg_acl_igm * 1.2\n\n# Count patients with aCL IgM higher than the threshold\nresult = len(filtered_exam[filtered_exam['aCL IgM'] > threshold])", "sql": "SELECT COUNT(*) FROM Examination WHERE Thrombosis = 2 AND `ANA Pattern` = 'S' AND `aCL IgM` > (SELECT AVG(`aCL IgM`) * 1.2 FROM Examination WHERE Thrombosis = 2 AND `ANA Pattern` = 'S')", "difficulty": "challenging" }, { "question_id": 1190, "question": "What percentage of patients with a proteinuria level within the normal range have a uric acid level below the normal range?", "db_id": "thrombosis_prediction", "evidence": "proteinuria level within the normal range refers to `U-PRO` > 0 AND `U-PRO` < 30; uric acid level below the normal range refers to UA < = 6.5; calculation = MULTIPLY(DIVIDE(UA < = 6.5, `U-PRO` > 0 AND `U-PRO` < 30),100)", "code": "import pandas as pd\n\n# 读取Laboratory表数据\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# 将U-PRO列转换为数值类型,无法转换的值设为NaN\nlaboratory_df['U-PRO'] = pd.to_numeric(laboratory_df['U-PRO'], errors='coerce')\n\n# 筛选出蛋白尿水平在正常范围内的患者 (0 < U-PRO < 30)\nnormal_proteinuria_df = laboratory_df[(laboratory_df['U-PRO'] > 0) & (laboratory_df['U-PRO'] < 30)]\n\n# 计算这些患者中尿酸水平低于正常范围 (UA <= 6.5) 的数量\nlow_uric_acid_count = normal_proteinuria_df[normal_proteinuria_df['UA'] <= 6.5].shape[0]\n\n# 计算总患者数量\ntotal_patients = normal_proteinuria_df.shape[0]\n\n# 计算百分比\npercentage = (low_uric_acid_count / total_patients) * 100 if total_patients > 0 else 0\n\n# 输出结果\nprint(percentage)", "sql": "SELECT CAST(SUM(CASE WHEN UA <= 6.5 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(ID) FROM Laboratory WHERE CAST(`U-PRO` AS REAL) > 0 AND CAST(`U-PRO` AS REAL) < 30", "difficulty": "challenging" }, { "question_id": 1191, "question": "What percentage of male patients who first presented to the hospital in 1981 were diagnosed with BEHCET?", "db_id": "thrombosis_prediction", "evidence": "male refers to SEX = 'M'; first presented to the hospital in 1981 refers to YEAR(`FIRST DATE`) = '1981'; BEHCET refers to diagnosis; calculation = DIVIDE(SUM(DIAGNOSIS = 'BEHCET') where YEAR(`FIRST DATE`) = '1981', MULTIPLY(COUNT(YEAR(`FIRST DATE`) = '1981')), 100)first presented to the hospital in 1981 refers to STRFTIME('%Y', `First Date`) = '1981'", "code": "import pandas as pd\nPatient['First Date'] = pd.to_datetime(Patient['First Date'])\nfiltered = Patient[(Patient['First Date'].dt.year == 1981) & (Patient['SEX'] == 'M')]\nresult = (filtered[filtered['Diagnosis'] == 'BEHCET'].shape[0] / filtered.shape[0] * 100) if filtered.shape[0] > 0 else 0", "sql": "SELECT CAST(SUM(CASE WHEN Diagnosis = 'BEHCET' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(ID) FROM Patient WHERE STRFTIME('%Y', `First Date`) = '1981' AND SEX = 'M';", "difficulty": "challenging" }, { "question_id": 1192, "question": "List all patients who were followed up at the outpatient clinic who underwent a laboratory test in October 1991 and had a total blood bilirubin level within the normal range.", "db_id": "thrombosis_prediction", "evidence": "followed up at the outpatient clinic refers to Admission = '-'; laboratory test in April 1981 refers to Date like '1991-10%'; blood bilirubin level within the normal range refers to T-BIL < 2.0; ", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if required columns exist\n if 'Admission' not in patient_df.columns or 'T-BIL' not in laboratory_df.columns or 'Date' not in laboratory_df.columns:\n return pd.DataFrame(columns=['ID'])\n\n # Filter Patient table for outpatients\n outpatient_patients = patient_df[patient_df['Admission'] == '-']\n\n # Ensure Date column is datetime and filter for October 1991\n laboratory_df['Date'] = pd.to_datetime(laboratory_df['Date'], errors='coerce')\n oct_1991_labs = laboratory_df[(laboratory_df['Date'].dt.year == 1991) & (laboratory_df['Date'].dt.month == 10)]\n\n # Filter for normal bilirubin levels\n normal_bilirubin = oct_1991_labs[oct_1991_labs['T-BIL'] < 2.0]\n\n # Merge patient and lab data on ID\n merged_data = pd.merge(outpatient_patients, normal_bilirubin, on='ID', how='inner')\n\n # Return distinct patient IDs\n return merged_data[['ID']].drop_duplicates()\n\n# Example function call\n# Assuming patient_df and laboratory_df are loaded DataFrames\n# result = solve_query(patient_df, laboratory_df)\n# print(result)", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Admission = '-' AND T2.`T-BIL` < 2.0 AND T2.Date LIKE '1991-10-%'", "difficulty": "challenging" }, { "question_id": 1193, "question": "Excluding all P only ANA Pattern patients, how many of the remainder are women born between 1980 and 1989?", "db_id": "thrombosis_prediction", "evidence": "Excluding all P only ANA Pattern refers to `ANA Pattern`! = 'P'; women refers to SEX = 'F'; born between 1980 and 1989 refers to BIRTHDAY", "code": "import pandas as pd\n\n# 读取Examination和Patient表数据\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\n\n# 将Birthday列转换为日期类型\npatient_df['Birthday'] = pd.to_datetime(patient_df['Birthday'], errors='coerce')\n\n# 筛选出ANA Pattern不为'P'的患者\nfiltered_examination_df = examination_df[examination_df['ANA Pattern'] != 'P']\n\n# 合并Examination和Patient表\nmerged_df = pd.merge(filtered_examination_df, patient_df, on='ID')\n\n# 筛选出女性且出生在1980-1989年之间的患者\nfiltered_patients = merged_df[(merged_df['SEX'] == 'F') & (merged_df['Birthday'].dt.year >= 1980) & (merged_df['Birthday'].dt.year <= 1989)]\n\n# 计算符合条件的患者数量\nresult_count = filtered_patients.shape[0]\n\n# 输出结果\nprint(result_count)", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T2.`ANA Pattern` != 'P' AND STRFTIME('%Y', T1.Birthday) BETWEEN '1980' AND '1989' AND T1.SEX = 'F'", "difficulty": "moderate" }, { "question_id": 1194, "question": "What sex is the patient who in a medical examination was diagnosed with PSS and in a laboratory examination had a blood level of C-reactive protein de 2+, createnine 1 and LDH 123?", "db_id": "thrombosis_prediction", "evidence": "PSS' refers to diagnosis; blood level of C-reactive protein de 2+refers to CRP > 2; createnine 1 refers to CRE = 1; LDH 123 refers to LDH = 123", "code": "import pandas as pd\n\npatient_df = pd.read_csv('Patient.csv')\nexamination_df = pd.read_csv('Examination.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\nmerged_df = pd.merge(patient_df, examination_df, on='ID')\nmerged_df = pd.merge(merged_df, laboratory_df, on='ID')\n\nfiltered_df = merged_df[\n (merged_df['Diagnosis_y'] == 'PSS') &\n (merged_df['CRP'] == '2+') &\n (merged_df['CRE'] == 1.0) &\n (merged_df['LDH'] == 123)\n]\n\nresult = filtered_df[['SEX']]\nresult = result.drop_duplicates().reset_index(drop=True)", "sql": "SELECT T1.SEX FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID INNER JOIN Laboratory AS T3 ON T3.ID = T2.ID WHERE T2.Diagnosis = 'PSS' AND T3.CRP = '2+' AND T3.CRE = 1.0 AND T3.LDH = 123", "difficulty": "challenging" }, { "question_id": 1195, "question": "What is the average blood albumin level for female patients with a PLT greater than 400 who have been diagnosed with SLE?", "db_id": "thrombosis_prediction", "evidence": "average blood albumin level refers to AVG(ALB); female refers to SEX = 'F'; PLT greater than 400 refers to PLT > 400; diagnosed with SLE refers to Diagnosis= 'SLE'", "code": "import pandas as pd\n\n# Filter female patients\nfemale_patients = Patient[Patient['SEX'] == 'F']\n\n# Get patients diagnosed with SLE from Patient table\nsle_patients_from_patient = Patient[Patient['Diagnosis'] == 'SLE'][['ID']]\n\n# Get patients diagnosed with SLE from Examination table\nsle_patients_from_exam = Examination[Examination['Diagnosis'] == 'SLE'][['ID']]\n\n# Combine SLE patient IDs from both sources\nsle_patient_ids = pd.concat([sle_patients_from_patient, sle_patients_from_exam])['ID'].unique()\n\n# Filter female patients who have SLE\nfemale_sle_patients = female_patients[female_patients['ID'].isin(sle_patient_ids)]\n\n# Merge with Laboratory data\nmerged = pd.merge(female_sle_patients[['ID']], Laboratory, on='ID')\n\n# Filter PLT > 400 and ALB not null\nfiltered = merged[(merged['PLT'] > 400) & (merged['ALB'].notna())]\n\n# Calculate average ALB\nresult = filtered['ALB'].mean()", "sql": "SELECT AVG(AlbData.ALB) FROM (SELECT T2.ALB FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND T2.PLT > 400 AND EXISTS (SELECT 1 FROM Examination WHERE ID = T1.ID AND Diagnosis = 'SLE' UNION ALL SELECT 1 WHERE T1.Diagnosis = 'SLE')) AS AlbData", "difficulty": "moderate" }, { "question_id": 1196, "question": "What is the most common sign of patients with SLE disease?", "db_id": "thrombosis_prediction", "evidence": "the most common sign refers to MAX(symptoms); 'SLE' refers to diagnosis", "code": "import pandas as pd\n\ndef solve_query(examination_data):\n # Ensure the required columns are present\n if 'Symptoms' not in examination_data.columns or 'Diagnosis' not in examination_data.columns:\n return pd.DataFrame({'Symptoms': []})\n\n # Filter rows where Diagnosis is 'SLE'\n sle_data = examination_data[examination_data['Diagnosis'] == 'SLE']\n\n # Handle possible null values in Symptoms\n sle_data = sle_data.dropna(subset=['Symptoms'])\n\n # Group by Symptoms and count occurrences\n symptom_counts = sle_data.groupby('Symptoms').size().reset_index(name='Count')\n\n # Sort by Count descending and Symptoms ascending to break ties\n most_common_symptom = symptom_counts.sort_values(by=['Count', 'Symptoms'], ascending=[False, True])\n\n # Return the most common symptom\n return most_common_symptom[['Symptoms']].head(1)\n\n# Example usage with placeholder data\n# Replace this with actual data loading from CSV or database\nif __name__ == '__main__':\n examination_data = pd.DataFrame({\n 'ID': [1, 2, 3, 4],\n 'Symptoms': ['Fever', 'Fatigue', 'Fever', None],\n 'Diagnosis': ['SLE', 'SLE', 'SLE', 'Other']\n })\n result = solve_query(examination_data)\n print(result)", "sql": "SELECT Symptoms FROM Examination WHERE Diagnosis = 'SLE' GROUP BY Symptoms ORDER BY COUNT(Symptoms) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1197, "question": "When was the medical information on patient number 48473 first documented, and what disease did she have?", "db_id": "thrombosis_prediction", "evidence": "medical information first documented refers to Description; disease refers to diagnosis; patient number refers to idmedical information first documented refers to First Date", "code": "import pandas as pd\n\n# Read the Patient table\npatient_df = pd.read_csv('Patient.csv')\n\n# Filter the DataFrame for the specific patient ID\npatient_48473 = patient_df[patient_df['ID'] == 48473]\n\n# Extract the required information\nresult = patient_48473[['First Date', 'Diagnosis']]\n\n# Print the result\nprint(result)", "sql": "SELECT `First Date`, Diagnosis FROM Patient WHERE ID = 48473", "difficulty": "simple" }, { "question_id": 1198, "question": "How many female patients were given an APS diagnosis?", "db_id": "thrombosis_prediction", "evidence": "female refers to SEX = 'F'; APS diagnosis refers to Diagnosis='APS'", "code": "import pandas as pd\n\ndef solve_query(patient_df):\n # Check if required columns exist\n required_columns = ['SEX', 'Diagnosis', 'ID']\n for col in required_columns:\n if col not in patient_df.columns:\n raise ValueError(f\"Missing required column: {col}\")\n\n # Filter data where SEX is 'F' and Diagnosis is 'APS'\n filtered_df = patient_df[(patient_df['SEX'] == 'F') & (patient_df['Diagnosis'] == 'APS')]\n\n # Count the number of IDs\n result_count = filtered_df['ID'].count()\n\n return result_count\n\n# Example function call with a sample DataFrame\n# Replace `patient_data` with actual DataFrame when using this code\nif __name__ == \"__main__\":\n # Sample DataFrame for testing\n data = {\n 'ID': [1, 2, 3, 4],\n 'SEX': ['F', 'M', 'F', 'F'],\n 'Birthday': ['1990-01-01', '1985-05-20', '1970-12-01', '1999-08-15'],\n 'Description': ['2023-01-01', '2023-02-01', '2023-03-01', None],\n 'First Date': ['2022-01-01', '2022-06-01', None, '2022-09-01'],\n 'Admission': ['A', 'B', 'C', 'D'],\n 'Diagnosis': ['APS', 'Other', 'APS', 'Other']\n }\n patient_data = pd.DataFrame(data)\n\n # Call the function and print the result\n result = solve_query(patient_data)\n print(result)", "sql": "SELECT COUNT(ID) FROM Patient WHERE SEX = 'F' AND Diagnosis = 'APS'", "difficulty": "simple" }, { "question_id": 1199, "question": "How many patients who underwent testing in 1997 had protein levels outside the normal range?", "db_id": "thrombosis_prediction", "evidence": "underwent testing in 1997 refers to YEAR(DATE) = '1997'; protein levels within the normal range refers to tp > 6 and tp < 8.5", "code": "import pandas as pd\\n\\n# 读取数据表为DataFrame\\nlaboratory_df = pd.read_csv('Laboratory.csv')\\n\\n# 将Date列转换为日期类型\\nlaboratory_df['Date'] = pd.to_datetime(laboratory_df['Date'])\\n\\n# 筛选出1997年的记录\\nlaboratory_1997 = laboratory_df[laboratory_df['Date'].dt.year == 1997]\\n\\n# 筛选出TP不在正常范围内的记录 (TP < 6.0 或 TP > 8.5)\\nlaboratory_outside_normal_range = laboratory_1997[(laboratory_1997['TP'] < 6.0) | (laboratory_1997['TP'] > 8.5)]\\n\\n# 计算符合条件的不同患者的数量\\nresult = laboratory_outside_normal_range['ID'].nunique()\\n\\n# 输出结果\\nprint(result)", "sql": "SELECT COUNT(DISTINCT ID) FROM Laboratory WHERE (TP < 6.0 OR TP > 8.5) AND STRFTIME('%Y', Date) = '1997' AND TP IS NOT NULL", "difficulty": "simple" }, { "question_id": 1200, "question": "What proportion of patients who had signs of thrombocytopenia had SLE diagnosed?", "db_id": "thrombosis_prediction", "evidence": "thrombocytopenia' refers to symptoms; 'SLE' refers to diagnosis; calculation = DIVIDE(SUM(DIAGNOSIS LIKE '%ITP%'), SUM(DIAGNOSIS LIKE '%SLE%')) MULTIPLY 100", "code": "import pandas as pd\nimport numpy as np\n\n# Filter examination records where symptoms indicate thrombocytopenia\nthrombocytopenia_patients = Examination[Examination['Symptoms'] == 'thrombocytopenia']\n\n# Calculate the proportion of SLE diagnosed among thrombocytopenia patients\nsle_count = (thrombocytopenia_patients['Diagnosis'] == 'SLE').sum()\ntotal_count = len(thrombocytopenia_patients)\n\n# Calculate percentage\nresult = (sle_count / total_count) * 100 if total_count > 0 else 0", "sql": "SELECT CAST(SUM(CASE WHEN Diagnosis = 'SLE' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(ID) FROM Examination WHERE Symptoms = 'thrombocytopenia'", "difficulty": "moderate" }, { "question_id": 1201, "question": "What percentage of patients who were born in 1980 and were diagnosed with RA are women?", "db_id": "thrombosis_prediction", "evidence": "born in 1980 refers to YEAR(BIRTHDAY) = '1980'; 'RA' refers to Diagnosis='RA' ; women refers to SEX = 'F'; calculation = DIVIDE(SUM(SEX = 'F'), COUNT(SEX)) * 100", "code": "import pandas as pd\n\ndef solve_query(patient_data):\n # Ensure 'Birthday' column is in datetime format\n if 'Birthday' in patient_data.columns:\n patient_data['Birthday'] = pd.to_datetime(patient_data['Birthday'], errors='coerce')\n\n # Filter patients born in 1980 and diagnosed with RA\n filtered_data = patient_data[\n (patient_data['Diagnosis'] == 'RA') & \n (patient_data['Birthday'].dt.year == 1980)\n ]\n\n # Calculate percentage of women among the filtered data\n if not filtered_data.empty:\n total_count = filtered_data.shape[0]\n female_count = filtered_data[filtered_data['SEX'] == 'F'].shape[0]\n percentage = (female_count / total_count) * 100 if total_count > 0 else 0\n else:\n percentage = 0\n\n return percentage\n\n# Example function call\n# Assuming `patient_data` is a DataFrame containing the Patient table\ndata = {\n 'ID': [1, 2, 3],\n 'SEX': ['F', 'M', 'F'],\n 'Birthday': ['1980-05-15', '1980-07-20', '1981-03-10'],\n 'Diagnosis': ['RA', 'RA', 'RA']\n}\npatient_data = pd.DataFrame(data)\nresult = solve_query(patient_data)\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN p.SEX = 'F' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(p.ID) \nFROM Patient p\nJOIN Examination e ON p.ID = e.ID\nWHERE e.Diagnosis = 'RA' \n AND STRFTIME('%Y', p.Birthday) = '1980'", "difficulty": "moderate" }, { "question_id": 1202, "question": "How many male patients who underwent testing between 1995 and 1997 and were subsequently diagnosed with Behcet disease did not stay in the hospital for treatment?", "db_id": "thrombosis_prediction", "evidence": "male refers to SEX = 'M'; underwent testing between 1995 and 1997 refers to `Examination Date` between '1995' and '1997'; Behcet refers to diagnosis; did not stay in the hospital refers to Admission = '-'", "code": "import pandas as pd\n\ndef solve_query(patient_df, examination_df):\n # Ensure required columns exist\n required_patient_cols = {'ID', 'SEX', 'Admission'}\n required_examination_cols = {'ID', 'Diagnosis', 'Examination Date'}\n\n if not required_patient_cols.issubset(patient_df.columns) or not required_examination_cols.issubset(examination_df.columns):\n return 0\n\n # Filter Patient data for males who did not stay in the hospital\n patient_filtered = patient_df[(patient_df['SEX'] == 'M') & (patient_df['Admission'] == '-')]\n\n # Convert 'Examination Date' to datetime, handling possible errors\n examination_df['Examination Date'] = pd.to_datetime(examination_df['Examination Date'], errors='coerce')\n\n # Filter Examination data for Behcet diagnosis and years 1995-1997\n examination_filtered = examination_df[\n (examination_df['Diagnosis'] == 'Behcet') & \n (examination_df['Examination Date'].dt.year >= 1995) & \n (examination_df['Examination Date'].dt.year <= 1997)\n ]\n\n # Merge filtered DataFrames on 'ID'\n merged_df = pd.merge(patient_filtered, examination_filtered, on='ID', how='inner')\n\n # Count distinct IDs in the result\n return merged_df['ID'].nunique()\n\n# Example function call with placeholder DataFrames\n# Replace these with actual DataFrames loaded from your data source\npatient_df = pd.DataFrame({\n 'ID': [1, 2, 3],\n 'SEX': ['M', 'F', 'M'],\n 'Admission': ['-', 'Y', '-']\n})\nexamination_df = pd.DataFrame({\n 'ID': [1, 2, 3],\n 'Diagnosis': ['Behcet', 'Other', 'Behcet'],\n 'Examination Date': ['1996-05-01', '1994-06-01', '1997-07-01']\n})\n\nresult = solve_query(patient_df, examination_df)\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T2.Diagnosis = 'Behcet' AND T1.SEX = 'M' AND STRFTIME('%Y', T2.`Examination Date`) BETWEEN '1995' AND '1997' AND T1.Admission = '-'", "difficulty": "challenging" }, { "question_id": 1203, "question": "How many patients who were female got white blood cells that were below 3.5?", "db_id": "thrombosis_prediction", "evidence": "female refers to SEX = 'F'; white blood cells that were below 3.5 refers to WBC < 3.5", "code": "import pandas as pd\n\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\nmerged_df = pd.merge(patient_df, laboratory_df, on='ID')\nfiltered_df = merged_df[(merged_df['SEX'] == 'F') & (merged_df['WBC'] < 3.5)]\nresult = len(filtered_df[['ID']].drop_duplicates())", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.WBC < 3.5 AND T1.SEX = 'F'", "difficulty": "simple" }, { "question_id": 1204, "question": "How long did it take after patient number 821298 arrived at the hospital for the first time before her evaluation began?", "db_id": "thrombosis_prediction", "evidence": "DATEDIFF(`Examination Date`, `First Date`)", "code": "import pandas as pd\nmerged = pd.merge(Patient, Examination, on='ID')\nfiltered = merged[merged['ID'] == 821298]\nfiltered['First Date'] = pd.to_datetime(filtered['First Date'])\nfiltered['Examination Date'] = pd.to_datetime(filtered['Examination Date'])\nresult = (filtered['Examination Date'] - filtered['First Date']).dt.days", "sql": "SELECT JULIANDAY(T3.`Examination Date`) - JULIANDAY(T1.`First Date`) FROM Patient AS T1 INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T1.ID = 821298", "difficulty": "simple" }, { "question_id": 1205, "question": "Was the patient with the number 57266's uric acid within a normal range?", "db_id": "thrombosis_prediction", "evidence": "SEX equals 'M' in the database; SEX equals 'F' in the database; UA is greater than 8 in the database; UA is greater than 6 in the database;", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[merged['ID'] == 57266]\nmax_date = filtered['Date'].max()\nlatest = filtered[filtered['Date'] == max_date]\nresult = ((latest['SEX'].iloc[0] == 'F' and 3.5 <= latest['UA'].iloc[0] <= 6.5) or (latest['SEX'].iloc[0] == 'M' and 4.0 <= latest['UA'].iloc[0] <= 8.0))", "sql": "SELECT CASE WHEN (T1.SEX = 'F' AND T2.UA BETWEEN 3.5 AND 6.5) OR (T1.SEX = 'M' AND T2.UA BETWEEN 4.0 AND 8.0) THEN true ELSE false END AS UA_Normal FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.ID = 57266 AND T2.Date = (SELECT MAX(Date) FROM Laboratory WHERE ID = 57266)", "difficulty": "moderate" }, { "question_id": 1206, "question": "When is the laboratory examination of patient '48473' where his/her AST glutamic oxaloacetic transaminase (GOT) index is above the normal range.", "db_id": "thrombosis_prediction", "evidence": "AST glutamic oxaloacetic transaminase (GOT) index is above the normal range refers to GOT > = 60; when refers to DATE", "code": "import pandas as pd\n\ndef solve_query(laboratory_data):\n # Ensure the necessary columns exist\n if 'ID' not in laboratory_data.columns or 'GOT' not in laboratory_data.columns or 'Date' not in laboratory_data.columns:\n return pd.DataFrame(columns=['Date'])\n\n # Convert Date column to datetime format\n laboratory_data['Date'] = pd.to_datetime(laboratory_data['Date'], errors='coerce')\n\n # Filter data based on conditions\n filtered_data = laboratory_data[(laboratory_data['ID'] == 48473) & (laboratory_data['GOT'] >= 60)]\n\n # Return only the required column\n return filtered_data[['Date']].reset_index(drop=True)\n\n# Example function call with assumed input data\n# Replace 'laboratory_data' with actual DataFrame when using\ndata = {\n 'ID': [48473, 48473, 12345],\n 'Date': ['2023-01-01', '2023-02-01', '2023-03-01'],\n 'GOT': [65, 50, 70]\n}\nlaboratory_data = pd.DataFrame(data)\nresult = solve_query(laboratory_data)\nprint(result)", "sql": "SELECT Date FROM Laboratory WHERE ID = 48473 AND GOT >= 60", "difficulty": "simple" }, { "question_id": 1207, "question": "List all patients with their sex and date of birthday, whose AST glutamic oxaloacetic transaminase (GOT) index is within normal range for loboratory examination in 1994.", "db_id": "thrombosis_prediction", "evidence": "AST glutamic oxaloacetic transaminase (GOT) index is within normal range refers to GOT < 60; examination in 1994 refers to year(Date) = 1994", "code": "import pandas as pd\n\n# 读取数据表为DataFrame\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# 处理可能存在的NULL值,将它们转换为NaN\nlaboratory_df['GOT'] = laboratory_df['GOT'].replace({None: pd.NA})\n\n# 将Date列转换为日期格式\nlaboratory_df['Date'] = pd.to_datetime(laboratory_df['Date'], errors='coerce')\n\n# 筛选出1994年的记录\nlaboratory_1994_df = laboratory_df[laboratory_df['Date'].dt.year == 1994]\n\n# 使用pd.merge进行JOIN操作\nmerged_df = pd.merge(patient_df, laboratory_1994_df, left_on='ID', right_on='ID', how='inner')\n\n# 筛选出符合条件的数据\nfiltered_df = merged_df.query('GOT < 60')\n\n# 选择需要的列并去重\nresult = filtered_df[['SEX', 'Birthday']].drop_duplicates()\n\n# 输出结果\nprint(result)", "sql": "SELECT DISTINCT T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GOT < 60 AND STRFTIME('%Y', T2.Date) = '1994'", "difficulty": "moderate" }, { "question_id": 1208, "question": "Provide IDs for male patients with ALT glutamic pylvic transaminase (GPT) that have history of ALT glutamic pylvic transaminase (GPT) exceed the normal range.", "db_id": "thrombosis_prediction", "evidence": "male refers to SEX = 'M'; ALT glutamic pylvic transaminase (GPT) exceed the normal range refers to GPT > = 60", "code": "import pandas as pd\nresult = pd.merge(Patient[Patient['SEX'] == 'M'], Laboratory[Laboratory['GPT'] >= 60], on='ID')[['ID']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'M' AND T2.GPT >= 60", "difficulty": "moderate" }, { "question_id": 1209, "question": "Please provide the diagnosis of patients with ALT glutamic pylvic transaminase beyond the normal range by ascending order of their date of birth.", "db_id": "thrombosis_prediction", "evidence": "ALT glutamic pylvic transaminase beyond the normal range refers to GPT > 60; The larger the birthday value, the younger the person is, and vice versa; ", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_Patient = pd.read_csv('Patient.csv')\\ndf_Laboratory = pd.read_csv('Laboratory.csv')\\ndf_Examination = pd.read_csv('Examination.csv')\\n\\n# Merge frpm and Patient Laboratory on CDSCode\\nmerged_df = pd.merge(df_Patient, df_Laboratory, on='ID', suffixes=('_Patient', '_Laboratory'))\\n\\n# Filter for GPT>60\\nfiltered_df = merged_df[merged_df['GPT'] > 60] # filter repeate Diagnosis and Birthday\\ndistinct_df = filtered_df[['Diagnosis', 'Birthday']].drop_duplicates()\\n\\n# sort by Birthday\\nsorted_df = distinct_df.sort_values(by='Birthday', ascending=True)\\n\\n# choose Diagnosis\\nresult = sorted_df[['Diagnosis']]\\n\\nprint(result)\\n", "sql": "SELECT Diagnosis FROM ( SELECT DISTINCT T1.Diagnosis, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GPT > 60) AS SubQuery ORDER BY Birthday ASC", "difficulty": "moderate" }, { "question_id": 1210, "question": "What is the average index of the lactate dehydrogenase (LDH) for all patients with lactate dehydrogenase (LDH) within the normal range.", "db_id": "thrombosis_prediction", "evidence": "average index of the lactate dehydrogenase (LDH) refers to AVG(LDH); (LDH) within the normal range refers to LDH < 500", "code": "import pandas as pd\n\n# Filter Laboratory data for LDH within normal range (< 500)\nfiltered_lab = Laboratory[Laboratory['LDH'] < 500]\n\n# Calculate average LDH\nresult = filtered_lab['LDH'].mean()", "sql": "SELECT AVG(LDH) FROM Laboratory WHERE LDH < 500", "difficulty": "simple" }, { "question_id": 1211, "question": "Provide the ID and age of patient with lactate dehydrogenase (LDH) between 100-300 index above the normal range.", "db_id": "thrombosis_prediction", "evidence": "age refers to SUBTRACT(year(current_timestamp), year(Birthday)); lactate dehydrogenase (LDH) between 100-300 index above the normal range refers to LDH between 600 and 800;", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID', how='inner')\nfiltered = merged[(merged['LDH'] >= 600) & (merged['LDH'] <= 800)]\ncurrent_year = pd.Timestamp.now().year\nfiltered['Age'] = current_year - pd.to_datetime(filtered['Birthday']).dt.year\nresult = filtered[['ID', 'Age']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.LDH BETWEEN 600 AND 800", "difficulty": "moderate" }, { "question_id": 1212, "question": "For patients with alkaliphophatase (ALP) within normal range, were they treated as inpatient or outpatient?", "db_id": "thrombosis_prediction", "evidence": "alkaliphophatase (ALP) within normal range refers to ALP < 300; inpatient refers to admission = '+'; outpatient refers to admission = '-'", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n try:\n # Ensure the required columns exist in dataframes\n if 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns:\n return pd.DataFrame({'Admission': []})\n\n if 'ALP' not in laboratory_df.columns or 'Admission' not in patient_df.columns:\n return pd.DataFrame({'Admission': []})\n\n # Filter rows where ALP is within normal range (< 300)\n filtered_laboratory = laboratory_df[laboratory_df['ALP'] < 300]\n\n # Merge Patient and Laboratory tables on ID\n merged_data = pd.merge(patient_df, filtered_laboratory, on='ID', how='inner')\n\n # Select the Admission column\n result = merged_data[['Admission']]\n\n return result\n\n except Exception as e:\n return pd.DataFrame({'Admission': []})\n\n# Example usage with sample dataframes\ndata_patient = {'ID': [1, 2, 3], 'Admission': ['+', '-', '+'], 'SEX': ['M', 'F', 'M']}\ndata_lab = {'ID': [1, 2, 3], 'ALP': [250, 350, 280], 'Date': ['2021-01-01', '2021-01-02', '2021-01-03']}\n\npatient_df = pd.DataFrame(data_patient)\nlaboratory_df = pd.DataFrame(data_lab)\n\n# Call the function\nresult = solve_query(patient_df, laboratory_df)", "sql": "SELECT T1.Admission FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.ALP < 300", "difficulty": "moderate" }, { "question_id": 1213, "question": "Name the ID of the patient who is born on the April 1st, 1982. Is his/her alkaliphophatase (ALP) within normal range?", "db_id": "thrombosis_prediction", "evidence": "ALP is less than 300 in the database;ALP normal range refers to less than 300", "code": "import pandas as pd\nimport numpy as np\n# Filter patients born on 1982-04-01\npatient_filtered = Patient[Patient['Birthday'] == '1982-04-01'][['ID']]\n# Get latest lab dates per patient\nlab_max_date = Laboratory.groupby('ID', as_index=False)['Date'].max()\n# Merge to get latest ALP values\nlatest_lab = pd.merge(Laboratory, lab_max_date, on=['ID', 'Date'], how='inner')[['ID', 'ALP']]\n# Join patient and lab data\nmerged = pd.merge(patient_filtered, latest_lab, on='ID', how='inner')\n# Determine ALP status\nresult = merged.assign(Status=np.where(merged['ALP'] < 300, 'normal', 'abNormal'))[['ID', 'Status']]", "sql": "SELECT T1.ID, CASE WHEN latest_lab.ALP < 300 THEN 'normal' ELSE 'abNormal' END \nFROM Patient AS T1 \nINNER JOIN (\n SELECT ID, ALP \n FROM Laboratory \n WHERE (ID, Date) IN (\n SELECT ID, MAX(Date) \n FROM Laboratory \n GROUP BY ID\n )\n) AS latest_lab ON T1.ID = latest_lab.ID \nWHERE T1.Birthday = '1982-04-01'", "difficulty": "moderate" }, { "question_id": 1214, "question": "List ID, sex and date of birth of patient whose total protein (TP) below the lower range of the normal index.", "db_id": "thrombosis_prediction", "evidence": "TP is less than 6 in the database;", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for TP < 6.0\nfiltered = merged[merged['TP'] < 6.0]\n\n# Select distinct ID, SEX, Birthday\nresult = filtered[['ID', 'SEX', 'Birthday']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.TP < 6.0", "difficulty": "simple" }, { "question_id": 1215, "question": "For all female patient with total protein (TP) beyond the normal index, what is the deviation of their TP idex from the normal.", "db_id": "thrombosis_prediction", "evidence": "female refers to SEX = 'F'; total protein (TP) beyond the normal index refers to TP > 8.5; deviation of TP index from normal refers to SUBTRACT(TP, 8.5)", "code": "import pandas as pd\nmerged = pd.merge(Patient[Patient['SEX'] == 'F'], Laboratory[Laboratory['TP'] > 8.5], on='ID')\nresult = merged['TP'] - 8.5", "sql": "SELECT T2.TP - 8.5 FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND T2.TP > 8.5", "difficulty": "moderate" }, { "question_id": 1216, "question": "Sort in descending order all patients by birthday for male patient with albumin not within range.", "db_id": "thrombosis_prediction", "evidence": "male = SEX = 'M'; albumin not within range refers to ALB < = 3.5 or ALB > = 5.5", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for male patients with albumin not within range\nfiltered = merged[(merged['SEX'] == 'M') & ((merged['ALB'] <= 3.5) | (merged['ALB'] >= 5.5))]\n\n# Get unique patient IDs\nunique_patients = filtered[['ID', 'Birthday']].drop_duplicates(subset=['ID'])\n\n# Sort by Birthday in descending order\nresult = unique_patients.sort_values('Birthday', ascending=False)['ID']", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'M' AND (T2.ALB <= 3.5 OR T2.ALB >= 5.5) ORDER BY T1.Birthday DESC", "difficulty": "simple" }, { "question_id": 1217, "question": "For all patient born in 1982, state if their albumin is within normal range.", "db_id": "thrombosis_prediction", "evidence": "Year(Birthday) = '1982'; albumin is within normal range refers to ALB between 3.5 and 5.5", "code": "import pandas as pd\nimport numpy as np\n# Filter patients born in 1982 with proper datetime conversion\nfiltered_patients = Patient[pd.to_datetime(Patient['Birthday']).dt.year == 1982]\n# Left join with Laboratory table on ID\nmerged = pd.merge(filtered_patients, Laboratory, on='ID', how='left')\n# Create result DataFrame with ALB status\nresult = merged[['ID']].copy()\nresult['Albumin Status'] = np.where((merged['ALB'] >= 3.5) & (merged['ALB'] <= 5.5), 'normal', 'abnormal')", "sql": "SELECT T1.ID, CASE WHEN T2.ALB BETWEEN 3.5 AND 5.5 THEN 'normal' ELSE 'abnormal' END FROM Patient AS T1 LEFT JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE STRFTIME('%Y', T1.Birthday) = '1982'", "difficulty": "moderate" }, { "question_id": 1218, "question": "What is the percentage of the female patient whose uric acid (UA) beyond the normal range?", "db_id": "thrombosis_prediction", "evidence": "uric acid (UA) beyond the normal range refers to UA > 8.0 and SEX = 'M' or UA > 6.5 and SEX = 'F'; female refers to Sex = 'F'", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for female patients\nfemale_patients = merged[merged['SEX'] == 'F']\n\n# Count total female patients\ntotal_female = len(female_patients)\n\n# Count female patients with UA > 6.5\nfemale_high_ua = len(female_patients[female_patients['UA'] > 6.5])\n\n# Calculate percentage\nresult = (female_high_ua / total_female) * 100 if total_female > 0 else 0", "sql": "SELECT CAST(SUM(CASE WHEN T2.UA > 6.5 THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F'", "difficulty": "moderate" }, { "question_id": 1219, "question": "For all patients with normal uric acid (UA), what is the average UA index based on their latest laboratory examination result?", "db_id": "thrombosis_prediction", "evidence": "uric acid (UA) with normal range refers to UA < 8.0 and SEX = 'M' or UA < 6.5 and SEX = 'F'; average UA index refers to AVG(UA)", "code": "import pandas as pd\n\n# Get the latest laboratory date for each patient\nlatest_dates = Laboratory.groupby('ID')['Date'].max().reset_index()\nlatest_dates.columns = ['ID', 'MaxDate']\n\n# Get the latest laboratory records\nlatest_lab = pd.merge(Laboratory, latest_dates, left_on=['ID', 'Date'], right_on=['ID', 'MaxDate'])\n\n# Join with Patient table to get sex information\nmerged = pd.merge(latest_lab, Patient[['ID', 'SEX']], on='ID')\n\n# Filter for normal UA values based on sex\nnormal_ua = merged[((merged['SEX'] == 'F') & (merged['UA'] < 6.5)) | \n ((merged['SEX'] == 'M') & (merged['UA'] < 8.0))]\n\n# Calculate average UA\nresult = normal_ua['UA'].mean()", "sql": "SELECT AVG(T2.UA) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE ((T2.UA < 6.5 AND T1.SEX = 'F') OR (T2.UA < 8.0 AND T1.SEX = 'M')) AND T2.Date = (SELECT MAX(Date) FROM Laboratory WHERE ID = T1.ID)", "difficulty": "moderate" }, { "question_id": 1220, "question": "Provide all ID, sex and birthday of patients whose urea nitrogen (UN) just within the borderline of passing?", "db_id": "thrombosis_prediction", "evidence": "urea nitrogen (UN) just within the borderline of passing refers to UN = 29; ", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory[Laboratory['UN'] == 29][['ID']], on='ID')\nresult = merged[['ID', 'SEX', 'Birthday']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.UN = 29", "difficulty": "simple" }, { "question_id": 1221, "question": "Provide the ID, sex, birthday of all patients diagnosed with 'RA' that are within the UN normal index.", "db_id": "thrombosis_prediction", "evidence": "within the UN normal index refers to UN < 30; Diagnosis = 'RA'", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for patients with UN < 30 and Diagnosis = 'RA'\nfiltered = merged[(merged['UN'] < 30) & (merged['Diagnosis'] == 'RA')]\n\n# Select distinct ID, SEX, Birthday\nresult = filtered[['ID', 'SEX', 'Birthday']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.UN < 30 AND T1.Diagnosis = 'RA';", "difficulty": "simple" }, { "question_id": 1222, "question": "How many male patients are are with creatinine index out of the normal range?", "db_id": "thrombosis_prediction", "evidence": "creatinine (CRE) out of the normal range refers to CRE > = 1.5; Male refers to Sex = 'M'", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_Patient = pd.read_csv('Patient.csv')\\ndf_Laboratory = pd.read_csv('Laboratory.csv')\\ndf_Examination = pd.read_csv('Examination.csv')\\n\\nmerged_df = pd.merge(df_Patient,df_Laboratory,on='ID',suffixes=('_patient', '_lab'))\\n\\nmale_patients = merged_df[merged_df['SEX'] == 'M']\\n\\nabnormal_cre = male_patients[male_patients['CRE'] >= 1.5]\\n\\nresult = abnormal_cre['ID'].nunique()\\n\\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'M' AND T2.CRE >=1.5", "difficulty": "simple" }, { "question_id": 1223, "question": "Are there more male patients with creatinine not within the normal range than female? True or False?", "db_id": "thrombosis_prediction", "evidence": "creatinine (CRE) not within the normal range refers to CRE > = 1.5; male refers to Sex = 'M'; female refers to Sex = 'F'; calculation = (SUM(SEX = 'M') > SUM(SEX = 'F')) where CRE > = 1.5", "code": "import pandas as pd\nimport numpy as np\n\n# Assume Patient and Laboratory are already loaded as DataFrames\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[merged['CRE'] >= 1.5]\nmale_count = (filtered['SEX'] == 'M').sum()\nfemale_count = (filtered['SEX'] == 'F').sum()\nresult = 'True' if male_count > female_count else 'False'", "sql": "SELECT CASE WHEN SUM(CASE WHEN T1.SEX = 'M' THEN 1 ELSE 0 END) > SUM(CASE WHEN T1.SEX = 'F' THEN 1 ELSE 0 END) THEN 'True' ELSE 'False' END FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.CRE >= 1.5", "difficulty": "challenging" }, { "question_id": 1224, "question": "What is the highest total bilirubin level recorded? List out the patient details with ID, sex and birthday with that index.", "db_id": "thrombosis_prediction", "evidence": "the highest total bilirubin refers to MAX(T-BIL)", "code": "import pandas as pd\n\n# Find the maximum T-BIL value\nmax_tbil = Laboratory['T-BIL'].max()\n\n# Filter Laboratory records with maximum T-BIL\nmax_tbil_records = Laboratory[Laboratory['T-BIL'] == max_tbil]\n\n# Merge with Patient table to get patient details\nresult = pd.merge(Patient[['ID', 'SEX', 'Birthday']], max_tbil_records[['ID', 'T-BIL']], on='ID')\n\n# Reorder columns to match expected output\nresult = result[['T-BIL', 'ID', 'SEX', 'Birthday']]", "sql": "SELECT T2.`T-BIL`, T1.ID, T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.`T-BIL` = (SELECT MAX(`T-BIL`) FROM Laboratory)", "difficulty": "simple" }, { "question_id": 1225, "question": "List and group all patients by sex for total bilirubin (T-BIL) level not within the normal range.", "db_id": "thrombosis_prediction", "evidence": "List refers to GROUP_CONCAT(DISTINCT ID); total bilirubin (T-BIL) not within normal range refers to T-BIL > = 2.0", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if required columns exist\n if 'ID' not in patient_df.columns or 'SEX' not in patient_df.columns:\n return pd.DataFrame(columns=['ID', 'SEX'])\n if 'ID' not in laboratory_df.columns or 'T-BIL' not in laboratory_df.columns:\n return pd.DataFrame(columns=['ID', 'SEX'])\n\n # Filter Laboratory data where T-BIL >= 2.0\n abnormal_bilirubin = laboratory_df[laboratory_df['T-BIL'] >= 2.0]\n\n # Merge Patient and filtered Laboratory data on 'ID'\n merged_data = pd.merge(patient_df, abnormal_bilirubin, on='ID', how='inner')\n\n # Group by SEX and ID, then select distinct IDs\n grouped_result = merged_data.groupby(['SEX', 'ID']).first().reset_index()\n\n # Return only the required columns\n return grouped_result[['ID', 'SEX']]\n\n# Example function call with placeholder DataFrames\ndata_patient = pd.DataFrame({'ID': [1, 2, 3], 'SEX': ['M', 'F', 'M'], 'Birthday': ['1990-01-01', '1985-05-05', None]})\ndata_laboratory = pd.DataFrame({'ID': [1, 2, 4], 'Date': ['2023-01-01', '2023-01-02', '2023-01-03'], 'T-BIL': [2.5, 1.8, 3.0]})\nresult = solve_query(data_patient, data_laboratory)\nprint(result)", "sql": "SELECT T1.ID,T1.SEX FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.`T-BIL` >= 2.0 GROUP BY T1.SEX,T1.ID", "difficulty": "moderate" }, { "question_id": 1226, "question": "Who is the oldest patient with the highest total cholesterol (T-CHO). State the patient ID and T-CHO index.", "db_id": "thrombosis_prediction", "evidence": "oldest patient refers to MIN(birthday); highest total cholesterol refers to MAX(T-CHO);highest total cholesterol refers to MAX(T-CHO); oldest patient refers to MIN(birthday); when multiple patients have the same highest T-CHO, the oldest patient is selected by MIN(birthday)", "code": "import pandas as pd\nmerged = pd.merge(Laboratory, Patient, on='ID')\nmax_tcho = Laboratory['T-CHO'].max()\nresult = merged[merged['T-CHO'] == max_tcho].sort_values('Birthday')[['ID', 'T-CHO']].head(1)", "sql": "SELECT T1.ID, T2.`T-CHO` FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.`T-CHO` = (SELECT MAX(`T-CHO`) FROM Laboratory) ORDER BY T1.Birthday ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1227, "question": "What is the average age of the male patient with high cholesterol?", "db_id": "thrombosis_prediction", "evidence": "average age = DIVIDE(SUM(SUBTRACT(YEAR(NOW()), YEAR(birthday))), COUNT(ID)); male patient refers to sex = 'M'; high cholesterol refers to `T-CHO` > = 250;", "code": "import pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for male patients with high cholesterol\nfiltered = merged[(merged['SEX'] == 'M') & (merged['T-CHO'] >= 250)]\n\n# Calculate age for each record\ncurrent_year = datetime.now().year\nfiltered['age'] = current_year - pd.to_datetime(filtered['Birthday']).dt.year\n\n# Calculate average age\nresult = filtered['age'].mean()", "sql": "SELECT AVG(STRFTIME('%Y', date('NOW')) - STRFTIME('%Y', T1.Birthday)) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.`T-CHO` >= 250 AND T1.SEX = 'M'", "difficulty": "moderate" }, { "question_id": 1228, "question": "Provide list of patients and their diagnosis with triglyceride (TG) index greater than 100 of the normal range?", "db_id": "thrombosis_prediction", "evidence": "triglyceride (TG) index greater than 100 of the normal range refers to TG > 300;", "code": "import pandas as pd\n\n# Read the tables from CSV files\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter laboratory DataFrame for TG > 300\nhigh_tg_laboratory = laboratory_df[laboratory_df['TG'] > 300]\n\n# Merge high_tg_laboratory with patient_df on ID to get patient details\npatient_details = pd.merge(high_tg_laboratory, patient_df, on='ID')\n\n# Select the required columns: Patient ID and Diagnosis\nresult = patient_details[['ID', 'Diagnosis']]\n\n# Print the final result\nprint(result)", "sql": "SELECT T1.ID, T1.Diagnosis FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.TG > 300", "difficulty": "simple" }, { "question_id": 1229, "question": "For all patients with triglyceride (TG) level beyond the normal range, how many are age more than 50 years?", "db_id": "thrombosis_prediction", "evidence": "triglyceride (TG) level beyond the normal range refers to TG > = 200; more than 50 years of age = SUBTRACT(year(current_timestamp), year(Birthday)) > 50; Should consider DISTINCT in the final result;", "code": "import pandas as pd\nfrom datetime import datetime\n\n# Get current year\ncurrent_year = datetime.now().year\n\n# Filter patients with TG >= 200\nhigh_tg = Laboratory[Laboratory['TG'] >= 200][['ID']]\n\n# Get unique patient IDs with high TG\nunique_patients = high_tg['ID'].unique()\n\n# Filter Patient table for these IDs\npatients_with_high_tg = Patient[Patient['ID'].isin(unique_patients)]\n\n# Calculate age and filter for age > 50\npatients_with_high_tg['Birthday'] = pd.to_datetime(patients_with_high_tg['Birthday'])\npatients_with_high_tg['age'] = current_year - patients_with_high_tg['Birthday'].dt.year\npatients_over_50 = patients_with_high_tg[patients_with_high_tg['age'] > 50]\n\n# Count distinct patients\nresult = len(patients_over_50['ID'].unique())", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.TG >= 200 AND STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) > 50", "difficulty": "moderate" }, { "question_id": 1230, "question": "List all outpatient within normal range of creatinine phosphokinase. Give me the distinct ids.", "db_id": "thrombosis_prediction", "evidence": "outpatient refers to Admission = '-'; normal range of creatinine phosphokinase refers to CPK < 250;", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if required columns exist\n if 'Admission' not in patient_df.columns or 'CPK' not in laboratory_df.columns or 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns:\n return pd.DataFrame({'ID': []})\n\n # Filter outpatients and normal CPK range\n try:\n filtered_patient = patient_df[patient_df['Admission'] == '-']\n filtered_lab = laboratory_df[laboratory_df['CPK'] < 250]\n\n # Merge DataFrames on ID\n merged_df = pd.merge(filtered_patient, filtered_lab, on='ID')\n\n # Select distinct IDs\n result = merged_df['ID'].drop_duplicates().reset_index(drop=True)\n return result\n except Exception as e:\n return pd.DataFrame({'ID': []})\n\n# Example usage with placeholder dataframes\ndata1 = pd.DataFrame({'ID': [1, 2, 3], 'Admission': ['-', 'Y', '-'], 'SEX': ['M', 'F', 'M']})\ndata2 = pd.DataFrame({'ID': [1, 2, 3], 'Date': ['2023-01-01', '2023-01-02', '2023-01-03'], 'CPK': [200, 300, 150]})\n\nresult = solve_query(data1, data2)\nprint(result)", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.CPK < 250 AND T1.Admission = '-'", "difficulty": "simple" }, { "question_id": 1231, "question": "For patient born between 1936-1956, how many male patients have creatinine phosphokinase beyond the normal range?", "db_id": "thrombosis_prediction", "evidence": "born between 1936-1956 refers to year(Birthday) BETWEEN '1936' AND '1956'; male patients refers to sex = 'M'; creatinine phosphokinase beyond the normal range refers to CPK > = 250; Should consider DISTINCT in the final result;", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n try:\n # Ensure 'Birthday' is datetime type\n if 'Birthday' in patient_df.columns:\n patient_df['Birthday'] = pd.to_datetime(patient_df['Birthday'], errors='coerce')\n\n # Filter patients born between 1936 and 1956\n filtered_patients = patient_df[\n (patient_df['Birthday'].notna()) & \n (patient_df['Birthday'].dt.year.between(1936, 1956)) & \n (patient_df['SEX'] == 'M')\n ]\n\n # Merge with Laboratory data on ID\n if 'ID' in filtered_patients.columns and 'ID' in laboratory_df.columns:\n merged_data = pd.merge(filtered_patients, laboratory_df, on='ID', how='inner')\n\n # Filter for CPK >= 250\n if 'CPK' in merged_data.columns:\n result = merged_data[merged_data['CPK'] >= 250]\n\n # Count distinct IDs\n return result['ID'].nunique()\n\n except Exception as e:\n print(f\"Error: {e}\")\n\n return 0\n\n# Example function call with placeholder DataFrames\n# Replace these with actual data when calling the function\npatient_data = pd.DataFrame({\n 'ID': [1, 2, 3],\n 'SEX': ['M', 'F', 'M'],\n 'Birthday': ['1940-05-01', '1960-01-01', '1950-08-15']\n})\nlaboratory_data = pd.DataFrame({\n 'ID': [1, 2, 3],\n 'CPK': [300, 200, 400]\n})\nresult = solve_query(patient_data, laboratory_data)\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE STRFTIME('%Y', T1.Birthday) BETWEEN '1936' AND '1956' AND T1.SEX = 'M' AND T2.CPK >= 250", "difficulty": "challenging" }, { "question_id": 1232, "question": "Provide ID, sex and age of patient who has blood glucose (GLU) not within normal range but with total cholesterol(T-CHO) within normal range.", "db_id": "thrombosis_prediction", "evidence": "age = SUBTRACT(year(current_timestamp), year(Birthday)); blood glucose (GLU) not within normal range refers to GLU > = 180; total cholesterol(T-CHO) within normal range refers to `T-CHO` < 250; ", "code": "import pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for GLU >= 180 and T-CHO < 250\nfiltered = merged[(merged['GLU'] >= 180) & (merged['T-CHO'] < 250)]\n\n# Calculate age\ncurrent_year = datetime.now().year\nfiltered['Age'] = current_year - pd.to_datetime(filtered['Birthday']).dt.year\n\n# Select distinct ID, SEX, Age\nresult = filtered[['ID', 'SEX', 'Age']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, T1.SEX, STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) AS Age FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GLU >= 180 AND T2.`T-CHO` < 250", "difficulty": "challenging" }, { "question_id": 1233, "question": "List each patient's ID and blood glucose (GLU) index that were within normal range for patient's whose data was first recorded in 1991.", "db_id": "thrombosis_prediction", "evidence": "blood glucose (GLU) index that were within normal range refers to GLU < 180; data that was first recorded in 1991 refers to year(Description) = 1991;", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_Patient = pd.read_csv('Patient.csv')\\ndf_Laboratory = pd.read_csv('Laboratory.csv')\\ndf_Examination = pd.read_csv('Examination.csv')\\n\\n# Convert 'First Date' column to datetime format for year extraction\\ndf_Patient['First Date'] = pd.to_datetime(df_Patient['First Date'])\\n\\n# Extract year from 'First Date' and compare to 1991\\npatients_1991 = df_Patient[df_Patient['First Date'].dt.year == 1991]\\n\\nmerged_data = pd.merge(patients_1991,df_Laboratory,on='ID',suffixes=('_patient', '_lab'))\\n\\nnormal_glu = merged_data[merged_data['GLU'] < 180]\\n\\nresult = normal_glu[['ID', 'GLU']].drop_duplicates()\\nprint(result)", "sql": "SELECT DISTINCT T1.ID, T2.GLU FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE YEAR(T1.`First Date`) = 1991 AND T2.GLU < 180", "difficulty": "moderate" }, { "question_id": 1234, "question": "List the patient ID, sex and birthday who has abnormal white blood cell count. Group them by sex and list the patient by age in ascending order.", "db_id": "thrombosis_prediction", "evidence": "abnormal white blood cell count refers to WBC < = 3.5 or WBC > = 9.0;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for abnormal WBC (<=3.5 or >=9.0)\nabnormal_wbc = merged[(merged['WBC'] <= 3.5) | (merged['WBC'] >= 9.0)]\n\n# Get unique patients with their info\nunique_patients = abnormal_wbc[['ID', 'SEX', 'Birthday']].drop_duplicates()\n\n# Sort by SEX first (for grouping display), then by Birthday (age ascending)\nresult = unique_patients.sort_values(['SEX', 'Birthday'])", "sql": "SELECT DISTINCT T1.ID, T1.SEX, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.WBC <= 3.5 OR T2.WBC >= 9.0 ORDER BY T1.Birthday DESC", "difficulty": "moderate" }, { "question_id": 1235, "question": "What are the patient's diagnosis for those who has lower red blood blood cell? State their ID and age.", "db_id": "thrombosis_prediction", "evidence": "patient's diagnosis refers to Diagnosis; lower red blood cell refers to RBC < 3.5; age = SUBTRACT(year(current_timestamp), year(Birthday)); ", "code": "import pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\n# Merge Patient and Laboratory tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for RBC < 3.5\nfiltered = merged[merged['RBC'] < 3.5]\n\n# Calculate age\ncurrent_year = datetime.now().year\nfiltered['age'] = current_year - pd.to_datetime(filtered['Birthday']).dt.year\n\n# Select distinct values\nresult = filtered[['Diagnosis', 'ID', 'age']].drop_duplicates()", "sql": "SELECT DISTINCT T1.Diagnosis, T1.ID , STRFTIME('%Y', CURRENT_TIMESTAMP) -STRFTIME('%Y', T1.Birthday) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.RBC < 3.5", "difficulty": "moderate" }, { "question_id": 1236, "question": "For all the female patient age 50 and above, who has abnormal red blood cell count. State if they were admitted to hospital.", "db_id": "thrombosis_prediction", "evidence": "female patient refers to Sex = 'F'; age 50 and above = SUBTRACT(year(current_timestamp), year(Birthday)) > = 50; abnormal red blood cell count refers to RBC < = 3.5 or RBC > = 6.0; Admission = '+' means the patient was admitted to the hospital; Admission = '-' means the patient was not admitted to the hospital;", "code": "import pandas as pd\nfrom datetime import datetime\n\n# Calculate age for female patients\nPatient['Age'] = pd.to_datetime('today').year - pd.to_datetime(Patient['Birthday']).dt.year\n\n# Filter female patients age 50 and above\nfemale_50_plus = Patient[(Patient['SEX'] == 'F') & (Patient['Age'] >= 50)]\n\n# Filter laboratories with abnormal RBC\nabnormal_rbc = Laboratory[(Laboratory['RBC'] <= 3.5) | (Laboratory['RBC'] >= 6.0)]\n\n# Merge to find female patients 50+ with abnormal RBC\nmerged = pd.merge(female_50_plus[['ID', 'Admission']], abnormal_rbc[['ID']], on='ID')\n\n# Get distinct patient ID and admission status\nresult = merged[['ID', 'Admission']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, T1.Admission FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND (T2.RBC <= 3.5 OR T2.RBC >= 6.0) AND (STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) >= 50) AND T1.Admission IN ('+', '-')", "difficulty": "challenging" }, { "question_id": 1237, "question": "Among all outpatients, list out those have low hemoglobin level. State the different IDs and their sex.", "db_id": "thrombosis_prediction", "evidence": "outpatients refers to Admission = '-'; low hemoglobin level refers to HBG < 10;", "code": "import pandas as pd\n\n# 假设数据已存在\n# Patient DataFrame\n# Laboratory DataFrame\n\n# 筛选门诊病人(Admission = '-')\noutpatients = Patient[Patient['Admission'] == '-']\n\n# 筛选低血红蛋白水平(HGB < 10)的实验室记录\nlow_hgb_labs = Laboratory[Laboratory['HGB'] < 10]\n\n# 合并两个DataFrame\nmerged = pd.merge(outpatients, low_hgb_labs, on='ID')\n\n# 选择ID和SEX列并去重\nresult = merged[['ID', 'SEX']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID, T1.SEX FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.HGB < 10 AND T1.Admission = '-'", "difficulty": "simple" }, { "question_id": 1238, "question": "Among the patients who were diagnosed with SLE, who is the oldest with normal hemoglobin level. Provide the ID and sex.", "db_id": "thrombosis_prediction", "evidence": "diagnosed with SLE refers to Diagnosis = 'SLE'; The larger the birthday value, the younger the person is, and vice versa; normal hemoglobin level refers to 10 < HGB < 17;", "code": "import pandas as pd\n\n# Filter patients diagnosed with SLE\nsle_patients = Patient[Patient['Diagnosis'] == 'SLE']\n\n# Merge with Laboratory data\nmerged = pd.merge(sle_patients, Laboratory, on='ID')\n\n# Filter for normal hemoglobin levels (between 10 and 17)\nnormal_hgb = merged[(merged['HGB'] > 10) & (merged['HGB'] < 17)]\n\n# Group by patient to get unique patients\npatient_groups = normal_hgb.groupby(['ID', 'SEX', 'Birthday']).size().reset_index(name='count')\n\n# Sort by Birthday ascending (oldest first - smaller birthday values mean older)\npatient_groups = patient_groups.sort_values('Birthday')\n\n# Get the oldest patient\nresult = patient_groups[['ID', 'SEX']].head(1)", "sql": "SELECT P.ID, P.SEX FROM Patient P JOIN Laboratory L ON P.ID = L.ID WHERE P.Diagnosis = 'SLE' AND L.HGB BETWEEN 10.1 AND 16.9 GROUP BY P.ID HAVING MIN(P.Birthday) ORDER BY P.Birthday ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1239, "question": "Name the ID and age of patient with two or more laboratory examinations which show their hematoclit level exceeded the normal range.", "db_id": "thrombosis_prediction", "evidence": "age = SUBTRACT(year(current_timestamp), year(Birthday)); patient with two or more laboratory examinations refers to COUNT(ID) > 2; hematoclit level exceeded the normal range refers to HCT > = 52;patient with two or more laboratory examinations refers to COUNT(ID) >= 2", "code": "import pandas as pd\nvalid_lab = Laboratory[Laboratory['HCT'] >= 52]\nid_counts = valid_lab.groupby('ID').size().reset_index(name='count')\nvalid_ids = id_counts[id_counts['count'] >= 2]['ID']\nfiltered_patient = Patient[Patient['ID'].isin(valid_ids)].copy()\nfiltered_patient['Birthday'] = pd.to_datetime(filtered_patient['Birthday'])\ncurrent_year = pd.Timestamp.now().year\nfiltered_patient['Age'] = current_year - filtered_patient['Birthday'].dt.year\nresult = filtered_patient[['ID', 'Age']]", "sql": "SELECT T1.ID, STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) AS Age FROM Patient AS T1 WHERE T1.ID IN ( SELECT ID FROM Laboratory WHERE HCT >= 52 GROUP BY ID HAVING COUNT(*) >= 2 )", "difficulty": "challenging" }, { "question_id": 1240, "question": "From laboratory examinations in 1991, what is the average hematoclit level that is lower than the normal range.", "db_id": "thrombosis_prediction", "evidence": "laboratory examinations in 1991 refers to Date like '1991%'; average hematoclit level = AVG(HCT); hematoclit level that is lower than the normal range refers to HCT < 29;", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Ensure the Date column is in datetime format\n laboratory_df['Date'] = pd.to_datetime(laboratory_df['Date'], errors='coerce')\n\n # Filter rows for year 1991 and HCT < 29\n filtered_data = laboratory_df[(laboratory_df['Date'].dt.year == 1991) & (laboratory_df['HCT'] < 29)]\n\n # Calculate the average HCT value\n avg_hct = filtered_data['HCT'].mean()\n\n return avg_hct\n\n# Example function call with dummy dataframes\n# Replace patient_df and laboratory_df with actual dataframes\ndata1 = {'ID': [1, 2, 3], 'SEX': ['M', 'F', 'M'], 'Birthday': ['1990-01-01', '1985-05-05', '1970-06-06']}\ndata2 = {'ID': [1, 2, 3], 'Date': ['1991-05-01', '1991-07-01', '1992-01-01'], 'HCT': [25, 28, 30]}\npatient_df = pd.DataFrame(data1)\nlaboratory_df = pd.DataFrame(data2)\n\nresult = solve_query(patient_df, laboratory_df)\nprint(result)", "sql": "SELECT AVG(T2.HCT) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.HCT < 29 AND STRFTIME('%Y', T2.Date) = '1991'", "difficulty": "moderate" }, { "question_id": 1241, "question": "For patients with abnormal platelet level, state the number of patients with lower than normal range. How is it compare to the number of patients with higher than normal range?", "db_id": "thrombosis_prediction", "evidence": "abnormal platelet level refers to PLT <= 100 or PLT >= 400; platelet level lower than normal range refers to PLT < 100; calculation = SUBTRACT(SUM(PLT < 100), SUM(PLT > 400)); platelet level higher than normal range refers to PLT > 400;", "code": "import pandas as pd\npatient_flags = Laboratory.groupby('ID').agg(low_plt_flag=('PLT', lambda x: (x < 100).any().astype(int)), high_plt_flag=('PLT', lambda x: (x > 400).any().astype(int)))\nresult = patient_flags.low_plt_flag.sum() - patient_flags.high_plt_flag.sum()", "sql": "SELECT\n SUM(low_plt_flag) - SUM(high_plt_flag)\nFROM (\n SELECT\n ID,\n MAX(CASE WHEN PLT < 100 THEN 1 ELSE 0 END) AS low_plt_flag,\n MAX(CASE WHEN PLT > 400 THEN 1 ELSE 0 END) AS high_plt_flag\n FROM Laboratory\n GROUP BY ID\n) AS patient_flags", "difficulty": "challenging" }, { "question_id": 1242, "question": "For laboratory examinations take in 1984, list all patients below 50 years old with normal platelet level.", "db_id": "thrombosis_prediction", "evidence": "laboratory examinations take in 1984 refers to YEAR(Date) = '1984'; below 50 years old = SUBTRACT(year(current_timestamp), year(Birthday)) < 50; normal platelet level refers to PLT between 100 and 400; ", "code": "import pandas as pd\nimport numpy as np\nPatient['Birthday'] = pd.to_datetime(Patient['Birthday'])\nLaboratory['Date'] = pd.to_datetime(Laboratory['Date'])\nmerged = pd.merge(Patient, Laboratory, on='ID')\nmerged['age_at_exam'] = (merged['Date'].dt.year - merged['Birthday'].dt.year)\nfiltered = merged[(merged['Date'].dt.year == 1984) & (merged['age_at_exam'] < 50) & (merged['PLT'] >= 100) & (merged['PLT'] <= 400)]\nresult = filtered[['ID']].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.PLT BETWEEN 100 AND 400 AND T2.PLT IS NOT NULL AND (julianday(T2.Date) - julianday(T1.Birthday)) / 365.25 < 50 AND STRFTIME('%Y', T2.Date) = '1984';", "difficulty": "challenging" }, { "question_id": 1243, "question": "For all patients who are older than 55 years old, what is the percentage of female who has abnormal prothrombin time (PT)?", "db_id": "thrombosis_prediction", "evidence": "older than 55 years old = SUBTRACT(year(current_timestamp), year(Birthday)) > 55; abnormal prothrombin time (PT) refers to PT > = 14; percentage = DIVIDE(SUM(PT > = 14 AND SEX = 'F'), SUM(PT > = 14)) * 100; female refers to sex = 'F'; ", "code": "import pandas as pd\nimport numpy as np\n# Convert Birthday to datetime\nPatient['Birthday'] = pd.to_datetime(Patient['Birthday'])\nnow = pd.Timestamp.now()\n# Filter patients older than 55\nover_55 = Patient[\n ((now.year - Patient['Birthday'].dt.year) > 55) |\n (((now.year - Patient['Birthday'].dt.year) == 55) & \n (Patient['Birthday'].dt.strftime('%m-%d') <= now.strftime('%m-%d')))\n]\n# Merge with Laboratory and filter abnormal PT\nmerged = pd.merge(over_55, Laboratory, on='ID')\nabnormal_pt = merged[merged['PT'] >= 14]\n# Calculate counts\nfemale_count = (abnormal_pt['SEX'] == 'F').sum()\ntotal_count = len(abnormal_pt)\n# Compute percentage with null handling\npercentage = female_count * 100.0 / total_count if total_count > 0 else np.nan\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(SUM(CASE WHEN T2.PT >= 14 AND T1.SEX = 'F' THEN 1 ELSE 0 END) AS REAL) * 100 / NULLIF(SUM(CASE WHEN T2.PT >= 14 THEN 1 ELSE 0 END), 0) AS percentage FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday)) > 55 OR (STRFTIME('%Y', CURRENT_TIMESTAMP) - STRFTIME('%Y', T1.Birthday) = 55 AND STRFTIME('%m-%d', T1.Birthday) <= STRFTIME('%m-%d', CURRENT_TIMESTAMP))", "difficulty": "challenging" }, { "question_id": 1244, "question": "List all patients who first came to the hospital after year 1992 with prothrombin time (PT) level that are normal.", "db_id": "thrombosis_prediction", "evidence": "first came to the hospital after year 1992 refers to year(`First Date`) > 1992; prothrombin time (PT) level that are normal refers to PT < 14;", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\ndf_Examination = pd.read_csv('Examination.csv')\\n\\n# Convert date columns to datetime format\\ndf_patient['Birthday'] = pd.to_datetime(df_patient['Birthday'])\\ndf_laboratory['Date'] = pd.to_datetime(df_laboratory['Date'])\\n\\n# Filter laboratory exams from 1984\\nlab_1984 = df_laboratory[df_laboratory['Date'].dt.year == 1984]\\n\\n# Remove records with null or invalid PLT values\\nvalid_plt = lab_1984[(lab_1984['PLT'].notnull()) &(lab_1984['PLT'].between(100, 400))]\\n\\nmerged_data = pd.merge(valid_plt,df_patient,on='ID',suffixes=('_patient', '_lab'))\\n\\nmerged_data['Age_at_Exam'] = (merged_data['Date'] - merged_data['Birthday']).dt.days // 365\\n\\nunder_50 = merged_data[merged_data['Age_at_Exam'] < 50]\\nresult = under_50[['ID']].drop_duplicates()\\nprint(result)", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE YEAR(T1.`First Date`) > 1992 AND T2.PT < 14;", "difficulty": "moderate" }, { "question_id": 1245, "question": "For the examinations done after 1997/1/1, how many of them have the result of an inactivated partial prothrom bin time?", "db_id": "thrombosis_prediction", "evidence": "examinations done after 1997/1/1 refers to `Examination Date` > '1997-01-01'; normal activated partial prothrom bin time refesr to APTT < 45;examinations done after 1997/1/1 refers to `Examination Date` > '1997-01-01'; normal activated partial prothrom bin time refers to APTT < 45; inactivated partial prothrom bin time refers to APTT >= 45", "code": "import pandas as pd\nresult = pd.merge(Examination, Laboratory, on='ID')\nresult = result[(result['Examination Date'] > '1997-01-01') & (result['APTT'] >= 45)]['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.`Examination Date` > '1997-01-01' AND T2.APTT >= 45", "difficulty": "moderate" }, { "question_id": 1246, "question": "For the patients with an abnormal activated partial prothrom bin time, how many of them does not have thrombosis?", "db_id": "thrombosis_prediction", "evidence": "abnormal activated partial prothrom bin time refers to APTT > 45; does not have thrombosis refers to Thrombosis = 0; Only count ones without repetitive.", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df, examination_df):\n # Check if necessary columns exist\n if 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns or 'ID' not in examination_df.columns:\n return pd.DataFrame({'count': [0]})\n\n if 'APTT' not in laboratory_df.columns or 'Thrombosis' not in examination_df.columns:\n return pd.DataFrame({'count': [0]})\n\n # Filter APTT > 45 and Thrombosis = 0\n filtered_lab = laboratory_df[laboratory_df['APTT'] > 45]\n filtered_exam = examination_df[examination_df['Thrombosis'] == 0]\n\n # Merge dataframes on ID\n merged_df = pd.merge(patient_df, filtered_lab, on='ID', how='inner')\n merged_df = pd.merge(merged_df, filtered_exam, on='ID', how='inner')\n\n # Count distinct IDs\n distinct_count = merged_df['ID'].nunique()\n\n return pd.DataFrame({'count': [distinct_count]})\n\n# Load the data (mock CSV file paths for example)\ntry:\n patient_df = pd.read_csv('Patient.csv')\n laboratory_df = pd.read_csv('Laboratory.csv')\n examination_df = pd.read_csv('Examination.csv')\n\n # Call the function and assign the result\n result = solve_query(patient_df, laboratory_df, examination_df)\nexcept Exception as e:\n result = pd.DataFrame({'count': [0]})\n\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T3.ID = T2.ID WHERE T3.Thrombosis = 0 AND T2.APTT > 45", "difficulty": "moderate" }, { "question_id": 1247, "question": "Among the male patients who have a normal level of white blood cells, how many of them have an abnormal fibrinogen level?", "db_id": "thrombosis_prediction", "evidence": "male patients refers to Sex = 'M'; normal level of white blood cells refers to WBC > 3.5 and WBC <9.0; abnormal fibrinogen level refers to FG < = 150 or FG > = 450; Don't compute repetitive ones.", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['SEX'] == 'M') & (merged['WBC'] > 3.5) & (merged['WBC'] < 9.0) & ((merged['FG'] <= 150) | (merged['FG'] >= 450))]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.FG <= 150 OR T2.FG >= 450) AND T2.WBC > 3.5 AND T2.WBC < 9.0 AND T1.SEX = 'M'", "difficulty": "challenging" }, { "question_id": 1248, "question": "How many patients born after 1980/1/1 have an abnormal fibrinogen level?", "db_id": "thrombosis_prediction", "evidence": "born after 1980/1/1 refers to Birthday > '1980-01-01'; normal fibrinogen level refers to FG between 150 and 450; Should return the number of distinct patients.", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['Birthday'] > '1980-01-01') & ((merged['FG'] < 150) | (merged['FG'] > 450))]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.FG < 150 OR T2.FG > 450) AND T1.Birthday > '1980-01-01'", "difficulty": "moderate" }, { "question_id": 1249, "question": "Please list the disease names of the patients that have a proteinuria level higher than normal.", "db_id": "thrombosis_prediction", "evidence": "disease names refers to Diagnosis; proteinuria level higher than normal refers to `U-PRO` > = 30;", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\ndf_examination = pd.read_csv('Examination.csv')\\ndf_laboratory['U-PRO'] = pd.to_numeric(df_laboratory['U-PRO'], errors='coerce')\\n\\nhigh_u_pro = df_laboratory[df_laboratory['U-PRO'] >= 30]\\nresult = pd.merge(df_patient,high_u_pro,on='ID',suffixes=('_patient', '_lab'))\\nresult=result['Diagnosis']\\nprint(result)", "sql": "SELECT T1.Diagnosis FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.`U-PRO` >= 30\n", "difficulty": "simple" }, { "question_id": 1250, "question": "Which patient has a normal proteinuria level and is diagnosed with SLE? Please give his or her patient ID.", "db_id": "thrombosis_prediction", "evidence": "normal proteinuria level refers to 0 < `U-PRO` < 30; diagnosed with SLE refers to Diagnosis = 'SLE';", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\ndf_examination = pd.read_csv('Examination.csv')\\n\\ndf_laboratory['U-PRO'] = pd.to_numeric(df_laboratory['U-PRO'], errors='coerce')\\n\\nnormal_u_pro = df_laboratory[(df_laboratory['U-PRO'] > 0) & (df_laboratory['U-PRO'] < 30)]\\nmerged_data = pd.merge(df_patient, normal_u_pro, on='ID', suffixes=('_patient', '_lab'))\\n\\nsle_patients = merged_data[merged_data['Diagnosis'].str.contains('SLE', case=False, na=False)]\\nresult = sle_patients[['ID']].drop_duplicates()\\n\\nprint(result)", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE CAST(T2.`U-PRO` AS REAL) > 0 AND CAST(T2.`U-PRO` AS REAL) < 30 AND T1.Diagnosis LIKE '%SLE%'", "difficulty": "moderate" }, { "question_id": 1251, "question": "How many patients with an Ig G higher than normal?", "db_id": "thrombosis_prediction", "evidence": "Ig G higher than normal refers to IGG >= 2000; Should consider DISTINCT in the final result;", "code": "import pandas as pd\nresult = Laboratory[Laboratory['IGG'] >= 2000]['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T2.ID) FROM Laboratory AS T2 WHERE T2.IGG >= 2000", "difficulty": "simple" }, { "question_id": 1252, "question": "Among the patients with a normal Ig G level, how many of them have symptoms?", "db_id": "thrombosis_prediction", "evidence": "normal Ig G level refers to IGG > 900 and IGG < 2000; have symptoms refers to Symptoms IS NOT NULL;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\npatient_df = pd.read_csv('Patient.csv')\n\n# Merge the tables on ID\nmerged_df = pd.merge(examination_df, laboratory_df, on='ID')\nmerged_df = pd.merge(merged_df, patient_df, on='ID')\n\n# Filter for normal Ig G level and have symptoms\nnormal_igg = (merged_df['IGG'] > 900) & (merged_df['IGG'] < 2000)\nhave_symptoms = merged_df['Symptoms'].notnull()\n\n# Count the number of patients meeting both conditions\nresult = merged_df[normal_igg & have_symptoms].shape[0]\n\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T3.ID = T2.ID WHERE T2.IGG BETWEEN 900 AND 2000 AND T3.Symptoms IS NOT NULL", "difficulty": "moderate" }, { "question_id": 1253, "question": "For the patient who has the highest Ig A within the normal range, what is his or her diagnosis?", "db_id": "thrombosis_prediction", "evidence": "highest Ig A within the normal range refers to MAX(IGA BETWEEN 80 AND 500);", "code": "import pandas as pd\\n\\n# Read the CSV files\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\ndf_examination = pd.read_csv('Examination.csv')\\n\\nnormal_iga = df_laboratory[(df_laboratory['IGA'] >= 80) & (df_laboratory['IGA'] <= 500)]\\n\\nmax_normal_iga = normal_iga['IGA'].max()\\nhighest_iga_records = normal_iga[normal_iga['IGA'] == max_normal_iga]\\n\\nhighest_id = highest_iga_records[['ID']].drop_duplicates()\\n\\nmerged_data = pd.merge(highest_id, df_patient[['ID', 'Diagnosis']], on='ID')\\nresult = merged_data['Diagnosis']\\n\\nprint(result)", "sql": "SELECT p.Diagnosis FROM Patient p INNER JOIN Laboratory lab ON p.ID = lab.ID WHERE lab.IGA = (SELECT MAX(IGA) FROM Laboratory WHERE IGA >= 80 AND IGA <= 500)AND IGA > 99 AND IGA <= 500", "difficulty": "simple" }, { "question_id": 1254, "question": "How many patients with a normal Ig A level came to the hospital after 1990/1/1?", "db_id": "thrombosis_prediction", "evidence": "normal Ig A level refers to IGA > 80 AND IGA < 500; came to the hospital after 1990/1/1 refers to YEAR(`First Date`) > = 1990;", "code": "import pandas as pd\n# Convert First Date to datetime\nPatient['First Date'] = pd.to_datetime(Patient['First Date'])\n# Merge tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\n# Apply filters and count unique IDs\nresult = merged[(merged['IGA'] > 80) & (merged['IGA'] < 500) & (merged['First Date'].dt.year >= 1990)]['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.IGA > 80 AND T2.IGA < 500) AND strftime('%Y', T1.`First Date`) >= '1990'", "difficulty": "moderate" }, { "question_id": 1255, "question": "For the patients with an abnormal Ig M level, what is the most common disease they are diagnosed with?", "db_id": "thrombosis_prediction", "evidence": "abnormal Ig M level refers to IGM <=40 OR IGM >= 400; most common disease refers to MAX(COUNT(Diagnosis));", "code": "import pandas as pd\n\n# Load the Laboratory table\nlaboratory = pd.read_csv('Laboratory.csv')\n\n# Filter patients with abnormal Ig M level (IGM <= 40 OR IGM >= 400)\nabnormal_igm = laboratory[(laboratory['IGM'] <= 40) | (laboratory['IGM'] >= 400)]\n\n# Merge with the Patient table to get the Diagnosis\npatient = pd.read_csv('Patient.csv')\nmerged_data = pd.merge(abnormal_igm, patient, on='ID')\n\n# Find the most common disease among these patients\nmost_common_disease = merged_data['Diagnosis'].mode()[0]\n\n# Record the final result\nresult = most_common_disease\n\n# Print the final result\nprint(result)", "sql": "SELECT T1.Diagnosis FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.IGM NOT BETWEEN 40 AND 400 GROUP BY T1.Diagnosis ORDER BY COUNT(T1.Diagnosis) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1256, "question": "How many patients with a abnormal C-reactive protein don't have their data recorded?", "db_id": "thrombosis_prediction", "evidence": "abnormal C-reactive protein refers to CRP ='+'; don't have data recorded refers to Description IS NULL;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_patient = pd.read_csv('Patient.csv')\ndf_laboratory = pd.read_csv('Laboratory.csv')\n\n# Merge Patient and Laboratory tables on ID to link Description and CRP\nmerged_data = pd.merge(df_patient, df_laboratory, on='ID')\n\n# Filter data where CRP is '+' and Description is null\nfiltered = merged_data[(merged_data['CRP'] == '+') & (merged_data['Description'].isnull())]\n\n# Calculate the count of matching records\nresult = len(filtered)\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.CRP = '+' ) AND T1.Description IS NULL", "difficulty": "moderate" }, { "question_id": 1257, "question": "Among the patients whose creatinine level is abnormal, how many of them aren't 70 yet?", "db_id": "thrombosis_prediction", "evidence": "creatinine level is abnormal refers to CRE >= 1.5; aren't 70 yet refers to SUBTRACT((YEAR(CURDATE()), YEAR(Birthday))) < 70; ", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\ncurrent_date = pd.Timestamp.now()\nage = current_date.year - pd.to_datetime(merged['Birthday']).dt.year\nage -= (current_date.month * 100 + current_date.day < pd.to_datetime(merged['Birthday']).dt.month * 100 + pd.to_datetime(merged['Birthday']).dt.day).astype(int)\nfiltered = merged[(merged['CRE'] >= 1.5) & (age < 70)]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.CRE >= 1.5 AND (strftime('%Y', 'now') - strftime('%Y', T1.Birthday)) - (strftime('%m-%d', 'now') < strftime('%m-%d', T1.Birthday)) < 70;", "difficulty": "challenging" }, { "question_id": 1258, "question": "How many patients with a normal Rhuematoid Factor has a positive measure of degree of coagulation?", "db_id": "thrombosis_prediction", "evidence": "normal Rhuematoid Factor refers TO RA IN('-', '+-'); positive measure of degree of coagulation refers to KCT = '+'; Should compute the number of distinct ones", "code": "import pandas as pd\n\n# Merge Patient with Laboratory on ID\nmerged1 = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for normal Rheumatoid Factor (RA in ['-', '+-'])\nfiltered = merged1[merged1['RA'].isin(['-', '+-'])]\n\n# Merge with Examination on ID\nmerged2 = pd.merge(filtered, Examination, on='ID')\n\n# Filter for positive measure of degree of coagulation (KCT = '+')\nfinal_filtered = merged2[merged2['KCT'] == '+']\n\n# Count distinct patient IDs\nresult = final_filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE (T2.RA IN ('-', '+-')) AND T3.KCT = '+'", "difficulty": "moderate" }, { "question_id": 1259, "question": "Please list the diseases of the patients born after 1985-1-1 and have a normal Rhuematoid Factor.", "db_id": "thrombosis_prediction", "evidence": "diseases refers to Diagnosis; born after 1985/1/1 refers to YEAR(Birthday) > = 1985; normal Rhuematoid Factor refers to RA IN('-', '+-');born after 1985-01-01 refers to Birthday > '1985-01-01'", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['RA'].isin(['-', '+-'])) & (merged['Birthday'] > '1985-01-01')]\nresult = filtered['Diagnosis'].drop_duplicates()", "sql": "SELECT DISTINCT T1.Diagnosis FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.RA IN ('-', '+-')) AND T1.Birthday >= '1985-01-02'", "difficulty": "moderate" }, { "question_id": 1260, "question": "Please list the ID of the patient whose RF is normal and who is older than 60.", "db_id": "thrombosis_prediction", "evidence": "RF is normal refers to RF < 20; older than 60 = SUBTRACT((YEAR(CURDATE()), YEAR(Birthday))) > 60;", "code": "from datetime import datetime\\nimport pandas as pd\\n\\n# Read the CSV files\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\ndf_examination = pd.read_csv('Examination.csv')\\n#df_laboratory['RF'] = pd.to_numeric(df_laboratory['RF'], errors='coerce')\\ndf_laboratory['RF_cleaned'] = (df_laboratory['RF'].astype(str).str.replace('<', '', regex=False).apply(pd.to_numeric, errors='coerce'))\\n\\nnormal_rf = df_laboratory[(df_laboratory['RF_cleaned'] < 20) & (df_laboratory['RF_cleaned'].notna())]\\n\\nmerged_data = pd.merge(normal_rf, df_patient, on='ID',suffixes=('_patient', '_lab'))\\n\\ncurrent_year = datetime.now().year\\nmerged_data['BirthYear'] = pd.to_datetime(merged_data['Birthday']).dt.year\\nmerged_data['Age'] = current_year - merged_data['BirthYear']\\nfiltered_data = merged_data[merged_data['Age'] > 60]\\n\\n#result = filtered_data[['ID', 'RF']].drop_duplicates()\\nresult = filtered_data[['ID']].drop_duplicates()\\n\\nprint(result)", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE CAST(REGEXP_REPLACE(T2.RF, '[^0-9.]', '') AS REAL) < 20 AND TIMESTAMPDIFF(YEAR, T1.Birthday, CURDATE()) > 60;", "difficulty": "simple" }, { "question_id": 1261, "question": "How many patients with a normal RF don't have thrombosis?", "db_id": "thrombosis_prediction", "evidence": "normal RF refers to RF < 20; don't have thrombosis refers to Thrombosis = '0';", "code": "import pandas as pd\\n\\n# 读取数据\\ndf_lab = pd.read_csv('Laboratory.csv')\\ndf_exam = pd.read_csv('Examination.csv')\\n\\ndf_lab['RF_cleaned'] = (\\n df_lab['RF']\\n .astype(str)\\n .str.replace('<', '', regex=False)\\n .apply(pd.to_numeric, errors='coerce')\\n)\\nnormal_rf_patients = df_lab[(df_lab['RF_cleaned'] < 20) & (df_lab['RF_cleaned'].notna())]\\nno_thrombosis = df_exam[df_exam['Thrombosis']==0]\\nmerged_data = pd.merge(normal_rf_patients, no_thrombosis, on='ID',suffixes=('_patient', '_lab'))\\nresult = merged_data[['ID']].drop_duplicates()\\nprint(len(result))", "sql": "SELECT COUNT(*)FROM (SELECT T2.ID FROM Laboratory AS T2 INNER JOIN Examination T3 ON T2.ID = ROUND(T3.ID, 0)WHERE CAST(REPLACE(T2.RF, '<', '') AS REAL) < 20 GROUP BY T2.ID HAVING MAX(T3.Thrombosis) = 0) AS subquery;", "difficulty": "simple" }, { "question_id": 1262, "question": "How many patients with a normal level of complement 3 have a P pattern observed in the sheet of ANA examination?", "db_id": "thrombosis_prediction", "evidence": "normal level of complement 3 refers to C3 > 35; have a P pattern observed in the sheet of ANA examination refers to ANA Pattern = 'P'; Should compute the number of distinct ones", "code": "import pandas as pd\nimport numpy as np\n\n# Merge Examination and Laboratory tables on ID\nmerged = pd.merge(Examination, Laboratory, on='ID')\n\n# Filter for C3 > 35 and ANA Pattern = 'P'\nfiltered = merged[(merged['C3'] > 35) & (merged['ANA Pattern'] == 'P')]\n\n# Count distinct patient IDs\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.C3 > 35 AND T1.`ANA Pattern` = 'P'", "difficulty": "moderate" }, { "question_id": 1263, "question": "Among the patients whose level of Hematoclit isn't normal, which patient has the highest anti-Cardiolipin antibody concentration? Please list his or her ID.", "db_id": "thrombosis_prediction", "evidence": "Hematoclit is normal refers to 29 < N < 52; highest anti-Cardiolipin antibody concentration refers to MAX(`aCL IgA`);", "code": "import pandas as pd\n\n# Merge the three tables\nmerged = pd.merge(Patient, Examination, on='ID')\nmerged = pd.merge(merged, Laboratory, on='ID')\n\n# Filter for abnormal HCT levels (not between 29 and 52)\nabnormal_hct = merged[(merged['HCT'] >= 52) | (merged['HCT'] <= 29)]\n\n# Sort by aCL IgA in descending order and get the first ID\nresult = abnormal_hct.sort_values('aCL IgA', ascending=False).head(1)[['ID']]", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID INNER JOIN Laboratory AS T3 on T1.ID = T3.ID WHERE (T3.HCT >= 52 OR T3.HCT <= 29) ORDER BY T2.`aCL IgA` DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1264, "question": "Among the patients have blood clots in veins, how many of them have a normal level of complement 4?", "db_id": "thrombosis_prediction", "evidence": "APS will result in Blood Clots in veins; normal level of complement 4 refers to C4 > 10; Should compute the number of different onesDiagnosis refers to APS in Patient table", "code": "import pandas as pd\nmerged = pd.merge(Laboratory, Examination, on='ID')\nfiltered = merged[(merged['Thrombosis'] == 1) & (merged['C4'] > 10)]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.C4 > 10 AND T3.Thrombosis = 1", "difficulty": "moderate" }, { "question_id": 1265, "question": "How many patients have a normal level of anti-ribonuclear protein and have been admitted to the hospital?", "db_id": "thrombosis_prediction", "evidence": "normal level of anti-ribonuclear protein refers to RNP = '-', '+-'; And'-' means 'negative'; '+-' refers to '0'; admitted to the hospital refers to Admission = '+'; Should consider DISTINCT in the final result;", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['RNP'].isin(['-', '+-'])) & (merged['Admission'] == '+')]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.RNP IN ('-', '+-')) AND T1.Admission = '+'", "difficulty": "moderate" }, { "question_id": 1266, "question": "Which is the youngest patient with an abnormal anti-ribonuclear protein level? Please list his or her date of birth.", "db_id": "thrombosis_prediction", "evidence": "youngest patient refers to MAX(Birthday); abnormal anti-ribonuclear protein level refers to RNP NOT IN('-', '+-'); date of birth refers to Birthday;", "code": "import pandas as pd\nresult = pd.merge(Patient, Laboratory, on='ID').query(\"RNP not in ['-', '+-']\").sort_values('Birthday', ascending=False).head(1)[['Birthday']]", "sql": "SELECT T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.RNP NOT IN ('-', '+-') ORDER BY T1.Birthday DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1267, "question": "Among the patients with normal anti-SM, how many of them does not have thrombosis?", "db_id": "thrombosis_prediction", "evidence": "normal anti-SM refers to SM IN('-', '+-'); SM = 'negative' means '-'; SM = '0' means '+-'; SM = '1' means '+'; does not have thrombosis refers to Thrombosis = 0;", "code": "import pandas as pd\nmerged = pd.merge(Examination, Laboratory, on='ID')\nfiltered = merged[(merged['SM'].isin(['negative', '0'])) & (merged['Thrombosis'] == 0)]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.SM IN ('negative','0') AND T1.Thrombosis = 0", "difficulty": "moderate" }, { "question_id": 1268, "question": "For the patients with an abnormal anti-SM, please list the IDs of the three youngest ones.", "db_id": "thrombosis_prediction", "evidence": "abnormal anti-SM refers to SM NOT IN ('negative', '0'); youngest refers to MAX(Birthday);", "code": "import pandas as pd\\n\\n# Load patient and laboratory data\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\n\\n# Convert Birthday to datetime format for proper sorting\\ndf_patient['Birthday'] = pd.to_datetime(df_patient['Birthday'], errors='coerce')\\n\\n# Filter laboratory data for abnormal anti-SM values\\nabnormal_sm = df_laboratory[~df_laboratory['SM'].isin(['negative', '0'])& (df_laboratory['SM'].notna())]\\n\\n# Get unique patient IDs with abnormal anti-SM (to avoid duplicates)\\nunique_abnormal_ids = abnormal_sm['ID'].drop_duplicates()\\n\\n# Filter patient data to include only those with abnormal anti-SM\\npatients_abnormal_sm = df_patient[df_patient['ID'].isin(unique_abnormal_ids) &df_patient['Birthday'].notnull()]\\n\\n# Sort by birthday (newest first) and get top 3 youngest\\nyoungest_patients = patients_abnormal_sm.sort_values(by='Birthday',ascending=False).head(3)\\n\\nprint(youngest_patients['ID'])", "sql": "SELECT ID FROM (SELECT DISTINCT T1.ID, T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.SM NOT IN ('negative','0')ORDER BY T1.Birthday DESC LIMIT 3) AS subquery;", "difficulty": "simple" }, { "question_id": 1269, "question": "Please list the IDs of the patients who had the examination done after 1997/1/1 and had a normal anti-scl70.", "db_id": "thrombosis_prediction", "evidence": "examination done after 1997/1/1 refers to `Examination Date` > 1997-01-01; normal anti-scl70 refers to SC170 IN('negative','0');", "code": "import pandas as pd\n\n# Convert date columns to datetime\nPatient['First Date'] = pd.to_datetime(Patient['First Date'])\nPatient['Birthday'] = pd.to_datetime(Patient['Birthday'])\nPatient['Description'] = pd.to_datetime(Patient['Description'])\nLaboratory['Date'] = pd.to_datetime(Laboratory['Date'])\n\n# Filter Laboratory records after 1997-01-01 with normal anti-scl70\nfiltered_lab = Laboratory[(Laboratory['Date'] > '1997-01-01') & (Laboratory['SC170'].isin(['negative', '0']))]\n\n# Get unique patient IDs\nresult = filtered_lab[['ID']].drop_duplicates()", "sql": "SELECT T1.ID\nFROM Patient AS T1\nINNER JOIN Laboratory AS T2 ON T1.ID = T2.ID\nINNER JOIN Examination AS T3 ON T1.ID = T3.ID\nWHERE T2.SC170 IN ('negative','0')\n AND T3.`Examination Date` > '1997-01-01'", "difficulty": "moderate" }, { "question_id": 1270, "question": "Among the patients who has a normal anti-scl70, how many of them are female and does not have any symptom?", "db_id": "thrombosis_prediction", "evidence": "normal anti-scl70 refers to SC170 IN('negative', '0'); female refers to Sex = 'F'; does not have any symptom refers to symptoms IS NULL; Should consider DISTINCT in the final result;", "code": "import pandas as pd\nlab_valid = Laboratory.groupby('ID').apply(lambda x: (x['SC170'].isin(['negative', '0']) | x['SC170'].isnull()).all()).reset_index(name='valid_lab')\nvalid_lab_ids = lab_valid[lab_valid['valid_lab']]['ID']\nex_valid = Examination.groupby('ID').apply(lambda x: x['Symptoms'].isnull().all()).reset_index(name='valid_ex')\nvalid_ex_ids = ex_valid[ex_valid['valid_ex']]['ID']\ncommon_ids = pd.merge(valid_lab_ids.to_frame(), valid_ex_ids.to_frame(), on='ID')['ID']\nfemale_patients = Patient[Patient['SEX'] == 'F']\nresult = pd.DataFrame({'count': [female_patients[female_patients['ID'].isin(common_ids)]['ID'].nunique()]})", "sql": "SELECT COUNT(DISTINCT P.ID) \nFROM Patient P\nWHERE P.SEX = 'F'\nAND P.ID IN (\n SELECT L.ID\n FROM Laboratory L\n GROUP BY L.ID\n HAVING SUM(CASE WHEN L.SC170 NOT IN ('negative','0') THEN 1 ELSE 0 END) = 0\n)\nAND P.ID IN (\n SELECT E.ID\n FROM Examination E\n GROUP BY E.ID\n HAVING SUM(CASE WHEN E.Symptoms IS NOT NULL THEN 1 ELSE 0 END) = 0\n);", "difficulty": "challenging" }, { "question_id": 1271, "question": "How many patients with a normal anti-SSA came to the hospital before 2000?", "db_id": "thrombosis_prediction", "evidence": "normal anti-SSA refers to SSA IN('-','+-'); came to the hospital before 2000 refers to YEAR(`First Date`) < 2000; Should compute the number of distinct ones", "code": "import pandas as pd\nPatient['First Date'] = pd.to_datetime(Patient['First Date'])\nmerged = pd.merge(Patient, Laboratory, on='ID', how='inner')\nfiltered = merged[merged['SSA'].isin(['-', '+-']) & (merged['First Date'].dt.year < 2000)]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.SSA IN ('-', '+-') AND STRFTIME('%Y', T1.`First Date`) < '2000'", "difficulty": "moderate" }, { "question_id": 1272, "question": "Which patient is the first patient with an abnormal anti-SSA to come to the hospital? Please give his or her ID.", "db_id": "thrombosis_prediction", "evidence": "first patient refers to ID with MIN(`First Date`); abnormal anti-SSA refers to SSA NOT IN('negative', '0');", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients with abnormal anti-SSA\nabnormal_ssa_patients = laboratory_df[laboratory_df['SSA'].isin(['positive', '1'])]\n\n# Merge with patient_df to get the first date\nmerged_df = pd.merge(abnormal_ssa_patients, patient_df[['ID', 'First Date']], on='ID')\n\n# Find the first patient with abnormal anti-SSA\nfirst_patient = merged_df.sort_values(by='First Date').head(1)\n\n# Get the ID of the first patient\nresult = first_patient['ID'].values[0]\n\nprint(result)", "sql": "SELECT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.`First Date` IS NOT NULL AND T2.SSA NOT IN ('negative', '0') ORDER BY T1.`First Date` ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1273, "question": "How many patients have a normal anti-SSB and are diagnosed with SLE in the examination?", "db_id": "thrombosis_prediction", "evidence": "normal anti-SSB refers to SSB IN('-', '+-'); '-' is expressed as 'negative' and '+-' is expressed as '0' in the database ; diagnosed with SLE refers to Diagnosis = 'SLE'; Should compute the number of distinct ones", "code": "import pandas as pd\nmerged = pd.merge(Laboratory, Examination, on='ID')\nfiltered = merged[(merged['SSB'].isin(['negative', '0'])) & (merged['Diagnosis'] == 'SLE')]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE (T2.SSB = 'negative' OR T2.SSB = '0') AND T3.Diagnosis = 'SLE'", "difficulty": "moderate" }, { "question_id": 1274, "question": "For the patients whose anti-SSB are normal, how many of them have other symptoms observed in their examination?", "db_id": "thrombosis_prediction", "evidence": "anti-SSB are normal refers to SSB IN ('negative', '0'); have other symptoms refers to Symptoms IS NOT NULL; Should compute the number of distinct ones", "code": "import pandas as pd\nmerged = pd.merge(Examination, Laboratory, on='ID')\nresult = merged[merged['SSB'].isin(['negative', '0']) & merged['Symptoms'].notna()]['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.SSB IN ('negative', '0') AND T1.Symptoms IS NOT NULL;", "difficulty": "moderate" }, { "question_id": 1275, "question": "Among the patients who has a normal level of anti-centromere and a normal level of anti-SSB, how many of them are male?", "db_id": "thrombosis_prediction", "evidence": "normal level of anti-centromere refers to CENTROMEA IN('-', '+-'); normal level of anti-SSB refers to SSB IN('-', '+-'); male refers to Sex = 'M'; Should consider DISTINCT in the final result;[\"normal_level_anti-centromere mapped_to ('negative', '0') in_addition_to ('-', '+-')\", \"normal_level_anti-SSB mapped_to ('negative', '0') in_addition_to ('-', '+-')\"]", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['CENTROMEA'].isin(['-', '+-'])) & (merged['SSB'].isin(['-', '+-'])) & (merged['SEX'] == 'M')]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.CENTROMEA IN ('-', '+-') AND T2.SSB IN ('-', '+-') AND T1.SEX = 'M'", "difficulty": "moderate" }, { "question_id": 1276, "question": "For the patients who have an abnormal level of anti-DNA, please list the diseases they are diagnosed with.", "db_id": "thrombosis_prediction", "evidence": "abnormal level of anti-DNA refers to DNA > = 8; diseases refers to Diagnosis;", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if required columns exist\n if 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns:\n return pd.DataFrame({'Diagnosis': []})\n if 'DNA' not in laboratory_df.columns or 'Diagnosis' not in patient_df.columns:\n return pd.DataFrame({'Diagnosis': []})\n\n # Filter rows where DNA >= 8\n abnormal_dna = laboratory_df[laboratory_df['DNA'] >= 8]\n\n # Merge Patient and Laboratory DataFrames on ID\n merged_df = pd.merge(patient_df, abnormal_dna, on='ID', how='inner')\n\n # Select distinct Diagnosis\n result_df = merged_df['Diagnosis'].drop_duplicates().reset_index(drop=True)\n\n return result_df\n\n# Example function call (replace with actual dataframes)\n# Assuming patient_df and laboratory_df are loaded from CSV or other sources\n# result = solve_query(patient_df, laboratory_df)\n# print(result)", "sql": "SELECT DISTINCT Diagnosis FROM (SELECT T1.Diagnosis FROM Patient T1 JOIN Laboratory T2 ON T1.ID = T2.ID WHERE CAST(T2.DNA AS INTEGER) >= 8 UNION SELECT E.Diagnosis FROM Patient P JOIN Examination E ON P.ID = E.ID JOIN Laboratory L ON P.ID = L.ID WHERE CAST(L.DNA AS INTEGER) >= 8)", "difficulty": "simple" }, { "question_id": 1277, "question": "How many patients have a normal anti-DNA level, yet their data are not recorded.", "db_id": "thrombosis_prediction", "evidence": "normal anti-DNA level refers to DNA < 8; data are not recorded refers to Description IS NULL; Should compute the number of unique ones", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[merged['DNA'].astype(float) < 8]\nresult = filtered[filtered['Description'].isna()]['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE CAST(T2.DNA AS REAL) < 8 AND T1.Description IS NULL", "difficulty": "moderate" }, { "question_id": 1278, "question": "Of the patients with an normal level of IGG, how many of them admitted to the hospital?", "db_id": "thrombosis_prediction", "evidence": "normal level of IGG refers to 900 < IGG < 2000; admitted to the hospital refers to Admission = '+';", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients with normal level of IGG (900 < IGG < 2000)\nnormal_igg_patients = laboratory_df[(laboratory_df['IGG'] > 900) & (laboratory_df['IGG'] < 2000)]\n\n# Get the IDs of these patients\nnormal_igg_patient_ids = normal_igg_patients['ID']\n\n# Filter patients who were admitted to the hospital\nadmitted_patients = patient_df[patient_df['Admission'] == '+']\n\n# Find the intersection of normal IGG patients and admitted patients\nadmitted_normal_igg_patients = admitted_patients[admitted_patients['ID'].isin(normal_igg_patient_ids)]\n\n# Count the number of such patients\nresult = len(admitted_normal_igg_patients)\n\n# Print the final result\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.IGG > 900 AND T2.IGG <2000 AND T1.Admission = '+'", "difficulty": "simple" }, { "question_id": 1279, "question": "What is the percentage of patient who has a abnormal level of glutamic oxaloacetic transaminase level, yet he or she is diagnosed with SLE?", "db_id": "thrombosis_prediction", "evidence": "abnormal level of glutamic oxaloacetic transaminase refers to GOT > = 60; percentage = MULTIPLY(DIVIDE(COUNT(ID WHERE GOT > = 60 AND Diagnosis = 'SLE'), COUNT(ID WHERE GOT > = 60)), 1.0);", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[merged['GOT'] >= 60]\nsle_count = filtered[filtered['Diagnosis'] == 'SLE']['ID'].nunique()\ntotal_count = filtered['ID'].nunique()\nresult = 1.0 * sle_count / total_count", "sql": "SELECT 1.0 * COUNT(DISTINCT CASE WHEN T1.Diagnosis = 'SLE' THEN T1.ID END) / COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GOT >= 60", "difficulty": "moderate" }, { "question_id": 1280, "question": "How many male patients have their glutamic oxaloacetic transaminase in the normal range?", "db_id": "thrombosis_prediction", "evidence": "male refers to Sex = 'M'; glutamic oxaloacetic transaminase in the normal range refers to GOT < 60;", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[(merged['GOT'] < 60) & (merged['SEX'] == 'M')]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GOT < 60 AND T1.SEX = 'M'", "difficulty": "simple" }, { "question_id": 1281, "question": "Among the patients who have an abnormal level of glutamic oxaloacetic transaminase, when was the youngest of them born?", "db_id": "thrombosis_prediction", "evidence": "abnormal level of glutamic oxaloacetic transaminase refers to GOT > = 60; The larger the birthday value, the younger the person is, and vice versa;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients with abnormal level of glutamic oxaloacetic transaminase (GOT >= 60)\nabnormal_got_patients = laboratory_df[laboratory_df['GOT'] >= 60]\n\n# Merge with patient_df to get the birthdays of these patients\nmerged_df = pd.merge(abnormal_got_patients, patient_df, on='ID')\n\n# Find the youngest patient by finding the maximum birthday (since larger date means younger person)\nyoungest_birthday = merged_df['Birthday'].max()\n\n# Record the final result\nresult = youngest_birthday\n\n# Print the final result\nprint(result)", "sql": "SELECT T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GOT >= 60 ORDER BY T1.Birthday DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1282, "question": "Please list the top three patients' birthdays with the highest glutamic pylvic transaminase in the normal range.", "db_id": "thrombosis_prediction", "evidence": "highest glutamic pylvic transaminase in the normal range refers to MAX(GPT < 60);", "code": "import pandas as pd\\n\\ndf_patient = pd.read_csv('Patient.csv')\\ndf_laboratory = pd.read_csv('Laboratory.csv')\\ndf_examination = pd.read_csv('Examination.csv')\\npatient_max_gpt = df_laboratory.groupby('ID')['GPT'].max().reset_index()\\n\\nnormal_gpt = patient_max_gpt[\\n (patient_max_gpt['GPT'] < 60) &\\n (patient_max_gpt['GPT'].notna())\\n ]\\n\\nnormal_gpt.columns = ['ID', 'MaxGPT'] # Rename column for clarity\\n\\n\\n# Sort patients by their maximum GPT in descending order (highest first)\\nsorted_patients = normal_gpt.sort_values(by='MaxGPT', ascending=False)\\n\\n# Get top 3 patients with highest normal GPT\\ntop3_patients = sorted_patients.head(3)\\n\\nresult = pd.merge(\\n top3_patients,\\n df_patient[['ID', 'Birthday']],\\n on='ID',\\n how='inner'\\n)\\n\\nprint(result[['Birthday']])", "sql": "SELECT T1.Birthday FROM Patient AS T1 JOIN (SELECT ID, MAX(CAST(GPT AS DECIMAL)) AS GPT FROM Laboratory GROUP BY ID HAVING MAX(CAST(GPT AS DECIMAL)) < 60 ) AS T2 ON T1.ID = T2.ID ORDER BY CAST(T2.GPT AS DECIMAL) DESC LIMIT 3", "difficulty": "simple" }, { "question_id": 1283, "question": "For the patients with the normal glutamic pylvic transaminase level, how many of them are male?", "db_id": "thrombosis_prediction", "evidence": "normal glutamic pylvic transaminase level refers to GOT < 60; male refers to Sex = 'M';", "code": "import pandas as pd\n\n# Load the necessary tables\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients with normal glutamic pylvic transaminase level (GOT < 60)\nnormal_got_patients = laboratory_df[laboratory_df['GOT'] < 60]\n\n# Get the IDs of these patients\nnormal_got_patient_ids = normal_got_patients['ID'].unique()\n\n# Filter the patient DataFrame for male patients with normal GOT levels\nmale_normal_got_patients = patient_df[(patient_df['ID'].isin(normal_got_patient_ids)) & (patient_df['SEX'] == 'M')]\n\n# Count the number of male patients with normal GOT levels\nresult = len(male_normal_got_patients)\n\n# Print the result\nprint(result)", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GOT < 60 AND T1.SEX = 'M'", "difficulty": "simple" }, { "question_id": 1284, "question": "For the patient with the highest lactate dehydrogenase in the normal range, when was his or her data first recorded?", "db_id": "thrombosis_prediction", "evidence": "highest lactate dehydrogenase in the normal range refers to MAX(LDH < 500); when the data first recorded refers to MIN(First Date);", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter laboratory data for LDH in the normal range (LDH < 500)\nnormal_ldh_df = laboratory_df[laboratory_df['LDH'] < 500]\n\n# Find the patient with the highest LDH in the normal range\nhighest_ldh_patient_id = normal_ldh_df['ID'].loc[normal_ldh_df['LDH'].idxmax()]\n\n# Get the first date of the patient with the highest LDH\nfirst_date = patient_df.loc[patient_df['ID'] == highest_ldh_patient_id, 'First Date'].iloc[0]\n\n# Record the final result\nresult = first_date\n\n# Print the final result\nprint(result)", "sql": "SELECT T1.`First Date`FROM Patient AS T1 INNER JOIN (SELECT ID, MAX(CAST(LDH AS DECIMAL))AS MaxLDH FROM Laboratory WHERE (CAST(LDH AS DECIMAL))< 500 GROUP BY ID) AS T2 ON T1.ID = T2.ID ORDER BY T2.MaxLDH DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1285, "question": "When is the latest patient's medical data recorded? This patient should have an abnormal level of lactate dehydrogenase.", "db_id": "thrombosis_prediction", "evidence": "latest patient refers to ID with MAX('First Date'); abnormal level of lactate dehydrogenase refers to LDH > = 500;", "code": "import pandas as pd\nmerged = pd.merge(Patient, Laboratory, on='ID')\nfiltered = merged[merged['LDH'] >= 500]\nresult = filtered.sort_values('First Date', ascending=False).head(1)['First Date']", "sql": "SELECT T1.`First Date` FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.LDH >= 500 ORDER BY T1.`First Date` DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1286, "question": "For the patient with an abnormal alkaliphophatase level, how many of them are admitted to the hospital?", "db_id": "thrombosis_prediction", "evidence": "abnormal alkaliphophatase level refers to ALP > = 300; admitted to the hospital refers to Admission = '+';", "code": "import pandas as pd\n\n# Load the Laboratory table\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Load the Patient table\npatient_df = pd.read_csv('Patient.csv')\n\n# Filter patients with abnormal alkaline phosphatase level (ALP >= 300)\nabnormal_alp_patients = laboratory_df[laboratory_df['ALP'] >= 300]\n\n# Merge with Patient table to get admission status\nmerged_df = pd.merge(abnormal_alp_patients, patient_df, on='ID')\n\n# Filter patients who are admitted to the hospital\nadmitted_patients = merged_df[merged_df['Admission'] == '+']\n\n# Count the number of such patients\nresult = admitted_patients.shape[0]\n\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.ALP >= 300 AND T1.Admission = '+'", "difficulty": "simple" }, { "question_id": 1287, "question": "Among the patients followed at the outpatient clinic, how many of them have a normal level of alkaliphophatase?", "db_id": "thrombosis_prediction", "evidence": "followed at the outpatient clinic refers to Admission = '-'; normal level of alkaliphophatase refers to ALP < 300;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients followed at the outpatient clinic\noutpatient_patients = patient_df[patient_df['Admission'] == '-']\n\n# Merge outpatient patients with laboratory data\nmerged_df = pd.merge(outpatient_patients, laboratory_df, on='ID')\n\n# Filter patients with normal level of alkaliphosphatase (ALP < 300)\nnormal_alp_patients = merged_df[merged_df['ALP'] < 300]\n\n# Count the number of such patients\nresult = normal_alp_patients.shape[0]\n\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.ALP < 300 AND T1.Admission = '-'", "difficulty": "moderate" }, { "question_id": 1288, "question": "Please list the diagnosis of the patients whose total protein is lower than normal.", "db_id": "thrombosis_prediction", "evidence": "total protein is lower than normal refers to TP < 6.0;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients with total protein (TP) lower than 6.0\nlow_tp_patients = laboratory_df[laboratory_df['TP'] < 6.0]\n\n# Get the IDs of these patients\nlow_tp_patient_ids = low_tp_patients['ID'].unique()\n\n# Filter the patient DataFrame for these IDs\ndiagnoses = patient_df[patient_df['ID'].isin(low_tp_patient_ids)]['Diagnosis']\n\n# Record the final result\nresult = diagnoses.unique()\n\n# Print the final result\nprint(result)", "sql": "SELECT DISTINCT T1.Diagnosis FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.TP < 6.0\n", "difficulty": "simple" }, { "question_id": 1289, "question": "For the patients who are diagnosed with SJS, how many of them have a normal level of total protein?", "db_id": "thrombosis_prediction", "evidence": "diagnosed with SJS refers to Diagnosis = 'SJS'; normal level of total protein refers to TP > 6.0 and TP < 8.5;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\npatient_df = pd.read_csv('Patient.csv')\n\n# Filter patients diagnosed with SJS\nsjs_patients = patient_df[patient_df['Diagnosis'] == 'SJS']\n\n# Merge SJS patients with their laboratory results\nmerged_df = pd.merge(sjs_patients, laboratory_df, on='ID')\n\n# Filter patients with normal level of total protein (TP > 6.0 and TP < 8.5)\nnormal_tp_patients = merged_df[(merged_df['TP'] > 6.0) & (merged_df['TP'] < 8.5)]\n\n# Count the number of such patients\nresult = normal_tp_patients.shape[0]\n\n# Print the final result\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Diagnosis = 'SJS' AND T2.TP > 6.0 AND T2.TP < 8.5", "difficulty": "moderate" }, { "question_id": 1290, "question": "What is the examination date of the patient whose albumin is the highest in the normal range?", "db_id": "thrombosis_prediction", "evidence": "examination date refers to Date; albumin is the highest in the normal range refers to MAX(ALB > 3.5 and ALB < 5.5);", "code": "import pandas as pd\n\n# Filter Laboratory data for albumin in normal range\nfiltered = Laboratory[(Laboratory['ALB'] > 3.5) & (Laboratory['ALB'] < 5.5)]\n\n# Sort by ALB descending and get the row with highest ALB\nif not filtered.empty:\n max_alb_row = filtered.sort_values('ALB', ascending=False).iloc[0]\n result = max_alb_row['Date']\nelse:\n result = None", "sql": "SELECT e.`Examination Date`\nFROM Laboratory l\nJOIN Patient p ON l.ID = p.ID\nJOIN Examination e ON p.ID = e.ID\nWHERE l.ALB > 3.5 AND l.ALB < 5.5\nORDER BY l.ALB DESC\nLIMIT 1", "difficulty": "simple" }, { "question_id": 1291, "question": "How many male patients have a normal level of both albumin and total protein?", "db_id": "thrombosis_prediction", "evidence": "male refers to Sex = 'M'; normal level of both albumin and total protein refers to ALB > 3.5 and ALB < 5.5 AND TP between 6.0 and 8.5;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Merge Patient and Laboratory tables on ID\nmerged_df = pd.merge(patient_df, laboratory_df, on='ID')\n\n# Filter for male patients with normal levels of albumin and total protein\nnormal_albumin_and_tp = (merged_df['SEX'] == 'M') & (merged_df['ALB'] > 3.5) & (merged_df['ALB'] < 5.5) & (merged_df['TP'] >= 6.0) & (merged_df['TP'] <= 8.5)\n\n# Count the number of such patients\nresult = merged_df[normal_albumin_and_tp].shape[0]\n\n# Print the result\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'M' AND T2.ALB > 3.5 AND T2.ALB < 5.5 AND T2.TP BETWEEN 6.0 AND 8.5", "difficulty": "moderate" }, { "question_id": 1292, "question": "What is the anti Cardiolipin antibody concentration of the female patient with the highest uric acid level in the normal range?", "db_id": "thrombosis_prediction", "evidence": "anti Cardiolipin antibody concentration refers to `aCL IgG`, `aCL IgM`, `aCL IgA`; female patient refers to Sex = F'; highest uric acid level in the normal range refers to MAX(UA > 6.50);", "code": "import pandas as pd\nfemale_data = pd.merge(Patient[Patient['SEX'] == 'F'], Laboratory, on='ID')\nfemale_ua = female_data[female_data['UA'] <= 6.5]\nmerged_exams = pd.merge(female_ua, Examination, left_on=['ID', 'Date'], right_on=['ID', 'Examination Date'])\nsorted_data = merged_exams.sort_values('UA', ascending=False)\nresult = sorted_data.head(1)[['aCL IgG', 'aCL IgM', 'aCL IgA']]", "sql": "SELECT T3.`aCL IgG`, T3.`aCL IgM`, T3.`aCL IgA` FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID AND T2.Date = T3.`Examination Date` WHERE T1.SEX = 'F' AND T2.UA <= 6.5 ORDER BY T2.UA DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1293, "question": "What is the highest anti-nucleus antibody concentration level of a patient with a normal creatinine level?", "db_id": "thrombosis_prediction", "evidence": "highest anti-nucleus antibody concentration level refers to MAX(ANA); normal creatinine level refers to CRE < 1.5;", "code": "import pandas as pd\n\n# Merge Patient with Examination and Laboratory tables\nmerged = pd.merge(Patient, Examination, on='ID')\nmerged = pd.merge(merged, Laboratory, on='ID')\n\n# Filter for normal creatinine level (CRE < 1.5)\nfiltered = merged[merged['CRE'] < 1.5]\n\n# Get the highest ANA value\nresult = filtered['ANA'].max()", "sql": "SELECT T2.ANA FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID INNER JOIN Laboratory AS T3 ON T1.ID = T3.ID WHERE T3.CRE < 1.5 ORDER BY T2.ANA DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1294, "question": "Please list the patient's ID whose creatinine level is normal and whose anti Cardiolipin antibody concentration level is the highest.", "db_id": "thrombosis_prediction", "evidence": "creatinine level is normal refers to CRE < 1.5; anti Cardiolipin antibody concentration level is the highest refers to MAX(aCL IgA);", "code": "import pandas as pd\nmerged = pd.merge(Laboratory[Laboratory['CRE'] < 1.5][['ID']], Examination[['ID', 'aCL IgA']], on='ID')\nresult = merged.sort_values('aCL IgA', ascending=False).head(1)[['ID']]", "sql": "SELECT T2.ID FROM Laboratory AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.CRE < 1.5 ORDER BY T2.`aCL IgA` DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1295, "question": "Among the patients whose total bilirubin is over the normal range, how many of them have a peripheral pattern observed in the sheet of ANA examination?", "db_id": "thrombosis_prediction", "evidence": "total bilirubin is over the normal range refers to `T-BIL` > = 2.0; peripheral pattern is observed in the sheet of ANA examination refers to that ANA Pattern contains 'P';", "code": "import pandas as pd\nmerged = pd.merge(pd.merge(Patient, Laboratory, on='ID'), Examination, on='ID')\nfiltered = merged[(merged['T-BIL'] >= 2) & (merged['ANA Pattern'].str.contains('P'))]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.`T-BIL` >= 2 AND T3.`ANA Pattern` LIKE '%P%'", "difficulty": "challenging" }, { "question_id": 1296, "question": "What is the anti-nucleus antibody concentration of the patient whose total bilirubin is the highest in the normal range?", "db_id": "thrombosis_prediction", "evidence": "anti-nucleus antibody concentration refers to ANA; total bilirubin is the highest in the normal range refers to MAX(`T-BIL` < 2.0);", "code": "import pandas as pd\n\n# Merge the three tables\nmerged = pd.merge(Patient, Laboratory, on='ID')\nmerged = pd.merge(merged, Examination, on='ID')\n\n# Filter for T-BIL < 2.0\nfiltered = merged[merged['T-BIL'] < 2.0]\n\n# Sort by T-BIL in descending order and get the first row\nresult = filtered.sort_values('T-BIL', ascending=False).head(1)['ANA'].values[0]", "sql": "SELECT T3.ANA FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.`T-BIL` < 2.0 ORDER BY T2.`T-BIL` DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1297, "question": "For the patients whose total cholesterol is higher than normal, how many of them have a negative measure of degree of coagulation?", "db_id": "thrombosis_prediction", "evidence": "total cholesterol is higher than normal refers to `T-CHO` > = 250; negative measure of degree of coagulation refers to KCT = '-' ;", "code": "import pandas as pd\nmerged = pd.merge(Laboratory, Examination, on='ID')\nfiltered = merged[(merged['T-CHO'] >= 250) & (merged['KCT'] == '-')]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.`T-CHO` >= 250 AND T3.KCT = '-'", "difficulty": "moderate" }, { "question_id": 1298, "question": "Among the patients whose total cholesterol is within the normal range, how many of them have a P pattern observed in the sheet of ANA examination?", "db_id": "thrombosis_prediction", "evidence": "total cholesterol is within the normal range refers to `T-CHO` < 250; P pattern observed in the sheet of ANA examination refers to ANA Pattern = 'P';", "code": "import pandas as pd\nresult = pd.merge(Laboratory[Laboratory['T-CHO'] < 250], Examination[Examination['ANA Pattern'] == 'P'], on='ID')['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T3.`ANA Pattern` = 'P' AND T2.`T-CHO` < 250", "difficulty": "moderate" }, { "question_id": 1299, "question": "Among the patients with the normal level of triglyceride, how many of them have other symptoms observed?", "db_id": "thrombosis_prediction", "evidence": "normal level of triglyceride refers to TG < 200; have other symptoms refers to Symptoms is not null;", "code": "import pandas as pd\nmerged = pd.merge(Examination, Laboratory, on='ID')\nfiltered = merged[(merged['TG'] < 200) & merged['Symptoms'].notnull()]\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.TG < 200 AND T1.Symptoms IS NOT NULL", "difficulty": "simple" }, { "question_id": 1300, "question": "What is the disease name of the patient who has the highest level of triglyceride within the normal range?", "db_id": "thrombosis_prediction", "evidence": "disease name referse to Diagnosis; highest level of triglyceride within the normal range refers to MAX(TG < 200);disease name refers to Patient.Diagnosis", "code": "import pandas as pd\nmerged = pd.merge(Examination, Laboratory, left_on=['ID', 'Examination Date'], right_on=['ID', 'Date'])\nfiltered = merged[merged['TG'] < 200]\nresult = filtered.sort_values('TG', ascending=False).head(1)['Diagnosis']", "sql": "SELECT T1.Diagnosis FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID AND T1.`Examination Date` = T2.Date WHERE T2.TG < 200 ORDER BY T2.TG DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1301, "question": "Please list the IDs of the patients with no thrombosis and an abnormal level of creatinine phosphokinase.", "db_id": "thrombosis_prediction", "evidence": "no thrombosis refers to Thrombosis = 0 ; abnormal level of creatinine phosphokinase refers to CPK < 250;", "code": "import pandas as pd\nmerged = pd.merge(Laboratory, Examination, on='ID')\nfiltered = merged[(merged['Thrombosis'] == 0) & (merged['CPK'] < 250)]\nresult = filtered['ID'].drop_duplicates()", "sql": "SELECT DISTINCT T1.ID FROM Laboratory AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T2.Thrombosis = 0 AND T1.CPK < 250", "difficulty": "simple" }, { "question_id": 1302, "question": "For the patients with a normal range of creatinine phosphokinase, how many of them have a positive measure of degree of coagulation?", "db_id": "thrombosis_prediction", "evidence": "normal range of creatinine phosphokinase refers to CPK < 250; positive measure of degree of coagulation refers to KCT = '+' or RVVT = '+' or LAC = '+' ;", "code": "import pandas as pd\n\n# Merge Patient with Laboratory on ID\nmerged_pl = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for normal CPK range (CPK < 250)\nfiltered_pl = merged_pl[merged_pl['CPK'] < 250]\n\n# Merge with Examination on ID\nmerged_all = pd.merge(filtered_pl, Examination, on='ID')\n\n# Filter for positive coagulation measures\npositive_coag = merged_all[(merged_all['KCT'] == '+') | (merged_all['RVVT'] == '+') | (merged_all['LAC'] == '+')]\n\n# Count unique patient IDs\nresult = positive_coag['ID'].nunique()", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.CPK < 250 AND (T3.KCT = '+' OR T3.RVVT = '+' OR T3.LAC = '+')", "difficulty": "challenging" }, { "question_id": 1303, "question": "When is the birthday of the oldest patient whose blood glucose is abnormal?", "db_id": "thrombosis_prediction", "evidence": "oldest patient refers to MIN(Birthday); blood glucose is abnormal refers to GLU > 180;", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for abnormal blood glucose (GLU > 180)\nabnormal_glucose = merged[merged['GLU'] > 180]\n\n# Sort by Birthday ascending (oldest first) and get the first row\noldest = abnormal_glucose.sort_values('Birthday').head(1)\n\n# Get the birthday of the oldest patient\nresult = oldest['Birthday'].iloc[0]", "sql": "SELECT T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GLU > 180 ORDER BY T1.Birthday ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1304, "question": "Among the patients with a normal blood glucose, how many of them don't have thrombosis?", "db_id": "thrombosis_prediction", "evidence": "normal blood glucose refers to GLU < 180; don't have thrombosis refers to Thrombosis = 0;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Merge the tables on ID\nmerged_df = pd.merge(examination_df, laboratory_df, on='ID')\n\n# Filter for normal blood glucose (GLU < 180) and no thrombosis (Thrombosis = 0)\nfiltered_df = merged_df[(merged_df['GLU'] < 180) & (merged_df['Thrombosis'] == 0)]\n\n# Count the number of such patients\nresult = filtered_df.shape[0]\n\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.GLU < 180 AND T3.Thrombosis = 0", "difficulty": "moderate" }, { "question_id": 1305, "question": "How many patients accepted to the hospital have a normal level of white blood cells?", "db_id": "thrombosis_prediction", "evidence": "accepted to the hospital refers to Admission = '+'; normal level of white blood cells refers to WBC between 3.5 and 9.0;", "code": "import pandas as pd\n\n# Read the tables\nexamination_df = pd.read_csv('Examination.csv')\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter patients accepted to the hospital\naccepted_patients = patient_df[patient_df['Admission'] == '+']\n\n# Merge accepted patients with laboratory data\nmerged_df = pd.merge(accepted_patients, laboratory_df, on='ID')\n\n# Filter patients with normal level of white blood cells (WBC between 3.5 and 9.0)\nnormal_wbc_patients = merged_df[(merged_df['WBC'] >= 3.5) & (merged_df['WBC'] <= 9.0)]\n\n# Count the number of such patients\nresult = normal_wbc_patients.shape[0]\n\n# Print the result\nprint(result)", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.WBC BETWEEN 3.5 AND 9 AND T1.Admission = '+'", "difficulty": "moderate" }, { "question_id": 1306, "question": "How many patients diagnosed with SLE have a normal white blood cell level?", "db_id": "thrombosis_prediction", "evidence": "diagnosed with SLE refers to Diagnosis = 'SLE'; normal white blood cell level refers to WBC between 3.5 and 9.0;", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for SLE diagnosis and normal WBC range\nfiltered = merged[(merged['Diagnosis'] == 'SLE') & (merged['WBC'] >= 3.5) & (merged['WBC'] <= 9.0)]\n\n# Count unique patient IDs\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Diagnosis = 'SLE' AND T2.WBC BETWEEN 3.5 AND 9", "difficulty": "simple" }, { "question_id": 1307, "question": "Please list the patient's ID if he or she has an abnormal level of red blood cell and is followed at the outpatient clinic.", "db_id": "thrombosis_prediction", "evidence": "RBC < = 3.5 or RBC > = 6.0 means the patient has an abnormal level of red blood cell; 3.5 < RBC < 6.0 means the patient has a normal level of red blood cell; followed at the outpatient clinic refers to Admission = '-';", "code": "import pandas as pd\n\ndef solve_query(patient_df, laboratory_df):\n # Check if required columns exist\n if 'Admission' not in patient_df.columns or 'RBC' not in laboratory_df.columns or 'ID' not in patient_df.columns or 'ID' not in laboratory_df.columns:\n return pd.DataFrame({'ID': []})\n\n # Filter patients with Admission = '-'\n outpatient_patients = patient_df[patient_df['Admission'] == '-']\n\n # Merge Patient and Laboratory tables on ID\n merged_df = pd.merge(outpatient_patients, laboratory_df, on='ID', how='inner')\n\n # Handle possible NaN values in RBC column\n merged_df['RBC'] = pd.to_numeric(merged_df['RBC'], errors='coerce')\n\n # Filter abnormal RBC levels\n abnormal_rbc_patients = merged_df[(merged_df['RBC'] <= 3.5) | (merged_df['RBC'] >= 6.0)]\n\n # Select distinct patient IDs\n result = abnormal_rbc_patients[['ID']].drop_duplicates()\n\n return result\n\n# Example function call assuming data is loaded into DataFrames\n# Replace the loading part with actual data loading logic if needed\ntry:\n patient_data = pd.read_csv('patient.csv')\n laboratory_data = pd.read_csv('laboratory.csv')\n result = solve_query(patient_data, laboratory_data)\n print(result)\nexcept Exception as e:\n print(pd.DataFrame({'ID': []}))", "sql": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE (T2.RBC <= 3.5 OR T2.RBC >= 6) AND T1.Admission = '-'", "difficulty": "challenging" }, { "question_id": 1308, "question": "Among the patients who have a normal platelet level, how many of them have other symptoms observed?", "db_id": "thrombosis_prediction", "evidence": "normal platelet level refers to PLT > 100 and PLT < 400; have other symptoms refers to Diagnosis is not null;", "code": "import pandas as pd\n\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\nmerged_df = pd.merge(patient_df, laboratory_df, on='ID')\nfiltered_df = merged_df[(merged_df['PLT'] > 100) & (merged_df['PLT'] < 400) & (merged_df['Diagnosis'].notna())]\nresult = filtered_df[['ID']].drop_duplicates().count().item()", "sql": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.PLT > 100 AND T2.PLT < 400 AND T1.Diagnosis IS NOT NULL", "difficulty": "moderate" }, { "question_id": 1309, "question": "Please list a patient's platelet level if it is within the normal range and if he or she is diagnosed with MCTD.", "db_id": "thrombosis_prediction", "evidence": "PLT > 100 and PLT < 400 means platelet level is within the normal range; PLT < 100 and PLT > 400 means platelet level is not within the normal range; diagnosed with MCTD refers to Diagnosis = 'MCTD';", "code": "import pandas as pd\n\n# Merge Patient and Laboratory tables on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Filter for MCTD diagnosis and normal platelet range\nfiltered = merged[(merged['Diagnosis'] == 'MCTD') & (merged['PLT'] > 100) & (merged['PLT'] < 400)]\n\n# Select only PLT column\nresult = filtered[['PLT']]", "sql": "SELECT T2.PLT FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Diagnosis = 'MCTD' AND T2.PLT > 100 AND T2.PLT < 400", "difficulty": "moderate" }, { "question_id": 1310, "question": "For the male patients that have a normal prothrombin time, what is their average prothrombin time?", "db_id": "thrombosis_prediction", "evidence": "male refers to Sex = 'M'; normal prothrombin time refer to PT < 14; average prothrombin time = AVG(PT);", "code": "import pandas as pd\n\n# Load the necessary tables\npatient_df = pd.read_csv('Patient.csv')\nlaboratory_df = pd.read_csv('Laboratory.csv')\n\n# Filter male patients with normal prothrombin time (PT < 14)\nmale_patients = patient_df[patient_df['SEX'] == 'M']\nnormal_pt_patients = laboratory_df[laboratory_df['PT'] < 14]\n\n# Merge the filtered patient and laboratory dataframes on ID\nmerged_df = pd.merge(male_patients, normal_pt_patients, on='ID')\n\n# Calculate the average prothrombin time for the filtered patients\naverage_pt = merged_df['PT'].mean()\n\n# Record the final result\nresult = average_pt\n\n# Print the final result\nprint(result)", "sql": "SELECT AVG(T2.PT) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.PT < 14 AND T1.SEX = 'M'", "difficulty": "simple" }, { "question_id": 1311, "question": "How many patients with severe thrombosis have a normal prothrombin time?", "db_id": "thrombosis_prediction", "evidence": "severe thrombosis refers to Thrombosis = 2 or 1; normal prothrombin time refers to PT < 14;", "code": "import pandas as pd\n\n# Merge Patient with Laboratory on ID\nmerged = pd.merge(Patient, Laboratory, on='ID')\n\n# Merge with Examination on ID\nmerged = pd.merge(merged, Examination, on='ID')\n\n# Filter for normal prothrombin time (PT < 14) and severe thrombosis (1 or 2)\nfiltered = merged[(merged['PT'] < 14) & (merged['Thrombosis'] > 0) & (merged['Thrombosis'] < 3)]\n\n# Count unique patients\nresult = filtered['ID'].nunique()", "sql": "SELECT COUNT(T1.ID) FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T2.PT < 14 AND T3.Thrombosis < 3 AND T3.Thrombosis > 0", "difficulty": "moderate" }, { "question_id": 1312, "question": "What's Angela Sanders's major?", "db_id": "student_club", "evidence": "Angela Sanders is the full name; full name refers to first_name, last_name; major refers to major_name.", "code": "import pandas as pd\nresult = pd.merge(member[member['first_name'] == 'Angela'][member['last_name'] == 'Sanders'], major, left_on='link_to_major', right_on='major_id')[['major_name']]", "sql": "SELECT T2.major_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.first_name = 'Angela' AND T1.last_name = 'Sanders'", "difficulty": "simple" }, { "question_id": 1313, "question": "How many students in the Student_Club are from the College of Engineering?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nengineering_members = merged[merged['college'] == 'College of Engineering']\nresult = len(engineering_members)", "sql": "SELECT COUNT(T1.member_id) FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.college = 'College of Engineering'", "difficulty": "simple" }, { "question_id": 1314, "question": "Please list the full names of the students in the Student_Club that come from the Art and Design Department.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name;", "code": "import pandas as pd\nimport numpy as np\n\nresult = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nresult = result[result['department'] == 'Art and Design Department']\nresult = result[['first_name', 'last_name']]", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.department = 'Art and Design Department';", "difficulty": "simple" }, { "question_id": 1315, "question": "How many students of the Student_Club have attended the event \"Women's Soccer\"?", "db_id": "student_club", "evidence": "Women's Soccer is an event name", "code": "import pandas as pd\n\ndef solve_query(event_df, attendance_df):\n # Check if required columns exist\n if 'event_name' not in event_df.columns or 'event_id' not in event_df.columns:\n return 0\n if 'link_to_event' not in attendance_df.columns:\n return 0\n\n # Filter events by name 'Women\\'s Soccer'\n filtered_events = event_df[event_df['event_name'] == \"Women's Soccer\"]\n\n # Merge with attendance DataFrame to link events to attendees\n merged_data = pd.merge(filtered_events, attendance_df, left_on='event_id', right_on='link_to_event', how='inner')\n\n # Count the number of unique attendees\n count_attendees = merged_data['link_to_event'].count()\n\n return count_attendees\n\n# Example function call with placeholder DataFrames (replace with actual data)\nevent_data = pd.DataFrame({\n 'event_id': ['e1', 'e2'],\n 'event_name': [\"Women's Soccer\", 'Other Event']\n})\nattendance_data = pd.DataFrame({\n 'link_to_event': ['e1', 'e1', 'e2'],\n 'link_to_member': ['m1', 'm2', 'm3']\n})\nresult = solve_query(event_data, attendance_data)\nprint(result)", "sql": "SELECT COUNT(T1.event_id) FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'Women''s Soccer'", "difficulty": "simple" }, { "question_id": 1316, "question": "Please list the phone numbers of the students from the Student_Club that has attended the event \"Women's Soccer\".", "db_id": "student_club", "evidence": "Women's Soccer is an event name; phone numbers refers to phone", "code": "import pandas as pd\nmerged = pd.merge(event[event['event_name'] == \"Women's Soccer\"], attendance, left_on='event_id', right_on='link_to_event')\nmerged = pd.merge(merged, member, left_on='link_to_member', right_on='member_id')\nresult = merged[['phone']]", "sql": "SELECT T3.phone FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event INNER JOIN member AS T3 ON T2.link_to_member = T3.member_id WHERE T1.event_name = 'Women''s Soccer'", "difficulty": "moderate" }, { "question_id": 1317, "question": "Among the students from the Student_Club who attended the event \"Women's Soccer\", how many of them want a T-shirt that's in medium size?", "db_id": "student_club", "evidence": "Women's Soccer is an event name; T-shirt that is in medium size refers to t_shirt_size = 'Medium'", "code": "import pandas as pd\n\n# Filter events for Women's Soccer\nwomens_soccer = event[event['event_name'] == \"Women's Soccer\"]\n\n# Join with attendance\nmerged = pd.merge(womens_soccer, attendance, left_on='event_id', right_on='link_to_event')\n\n# Join with member\nmerged = pd.merge(merged, member, left_on='link_to_member', right_on='member_id')\n\n# Filter for medium size t-shirts\nmedium_size = merged[merged['t_shirt_size'] == 'Medium']\n\n# Count the number of students\nresult = len(medium_size)", "sql": "SELECT COUNT(T1.event_id) FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event INNER JOIN member AS T3 ON T2.link_to_member = T3.member_id WHERE T1.event_name = 'Women''s Soccer' AND T3.t_shirt_size = 'Medium'", "difficulty": "moderate" }, { "question_id": 1318, "question": "What is the event that has the highest attendance of the students from the Student_Club?", "db_id": "student_club", "evidence": "count of link_to_event;", "code": "import pandas as pd\nmerged = pd.merge(event, attendance, left_on='event_id', right_on='link_to_event')\ngrouped = merged.groupby('event_name').size().reset_index(name='count')\nresult = grouped.sort_values('count', ascending=False).head(1)['event_name'].iloc[0]", "sql": "SELECT T1.event_name FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event GROUP BY T1.event_id ORDER BY COUNT(T2.link_to_event) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1319, "question": "Which college is the vice president of the Student_Club from?", "db_id": "student_club", "evidence": "Vice President is a position of the Student Club", "code": "import pandas as pd\n\n# Read the required tables\nevent = pd.read_csv('event.csv')\nmajor = pd.read_csv('major.csv')\nzip_code = pd.read_csv('zip_code.csv')\nattendance = pd.read_csv('attendance.csv')\nbudget = pd.read_csv('budget.csv')\nexpense = pd.read_csv('expense.csv')\nincome = pd.read_csv('income.csv')\nmember = pd.read_csv('member.csv')\n\n# Filter members who are Vice Presidents\nvice_presidents = member[member['position'] == 'Vice President']\n\n# Merge with major table to get college information\nresult = pd.merge(vice_presidents, major, left_on='link_to_major', right_on='major_id')\n\n# Select the college column\nresult = result[['college']]\n\n# Print the final result\nprint(result)", "sql": "SELECT T2.college FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.position LIKE 'vice president'", "difficulty": "simple" }, { "question_id": 1320, "question": "Please list the event names of all the events attended by Maya Mclean.", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\n\n# Merge member with attendance\nmerged1 = pd.merge(member[member['first_name'] == 'Maya'][member['last_name'] == 'Mclean'], attendance, left_on='member_id', right_on='link_to_member')\n\n# Merge with event\nmerged2 = pd.merge(merged1, event, left_on='link_to_event', right_on='event_id')\n\n# Get event names\nresult = merged2[['event_name']]", "sql": "SELECT T1.event_name FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event INNER JOIN member AS T3 ON T2.link_to_member = T3.member_id WHERE T3.first_name = 'Maya' AND T3.last_name = 'Mclean'", "difficulty": "simple" }, { "question_id": 1321, "question": "How many events of the Student_Club did Sacha Harrison attend in 2019?", "db_id": "student_club", "evidence": "events attended in 2019 refers to YEAR(event_date) = 2019", "code": "import pandas as pd\n\n# Extract year from event_date and filter for 2019\nevents_2019 = event[event['event_date'].str[:4] == '2019']\n\n# Get Sacha Harrison's member_id\nsacha = member[(member['first_name'] == 'Sacha') & (member['last_name'] == 'Harrison')]\n\n# Join attendance with filtered events\nattended_events = pd.merge(attendance, events_2019, left_on='link_to_event', right_on='event_id')\n\n# Join with member to filter for Sacha Harrison\nattended_by_sacha = pd.merge(attended_events, sacha, left_on='link_to_member', right_on='member_id')\n\n# Count the events\nresult = len(attended_by_sacha)", "sql": "SELECT COUNT(T1.event_id) FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event INNER JOIN member AS T3 ON T2.link_to_member = T3.member_id WHERE T3.first_name = 'Sacha' AND T3.last_name = 'Harrison' AND SUBSTR(T1.event_date, 1, 4) = '2019'", "difficulty": "moderate" }, { "question_id": 1322, "question": "Among the events attended by more than 10 members of the Student_Club, how many of them are meetings?", "db_id": "student_club", "evidence": "meetings events refers to type = 'Meeting'; attended by more than 10 members refers to COUNT(event_id) > 10meetings events refers to type = 'Meeting'; attended by more than 10 members refers to COUNT(link_to_member) > 10", "code": "import pandas as pd\nmerged = pd.merge(event, attendance, left_on='event_id', right_on='link_to_event')\nmeeting_events = merged[merged['type'] == 'Meeting']\nevent_counts = meeting_events.groupby('event_id')['link_to_member'].nunique().reset_index()\nresult = len(event_counts[event_counts['link_to_member'] > 10])", "sql": "SELECT COUNT(*) FROM (SELECT T1.event_id FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event WHERE T1.type = 'Meeting' GROUP BY T1.event_id HAVING COUNT(DISTINCT T2.link_to_member) > 10)", "difficulty": "moderate" }, { "question_id": 1323, "question": "List all the names of events that had an attendance of over 20 students but were not fundraisers.", "db_id": "student_club", "evidence": "name of events refers to event_name; attendance of over 20 students COUNT(event_id) > 20.", "code": "import pandas as pd\n\n# Merge event and attendance tables\nmerged = pd.merge(event, attendance, left_on='event_id', right_on='link_to_event')\n\n# Group by event and count attendance\nevent_attendance = merged.groupby(['event_id', 'event_name', 'type']).size().reset_index(name='attendance_count')\n\n# Filter events with attendance > 20\nhigh_attendance = event_attendance[event_attendance['attendance_count'] > 20]\n\n# Get events that are not fundraisers\nresult = high_attendance[high_attendance['type'] != 'Fundraiser'][['event_name']]", "sql": "SELECT T1.event_name FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event GROUP BY T1.event_id HAVING COUNT(T2.link_to_event) > 20 EXCEPT SELECT T1.event_name FROM event AS T1 WHERE T1.type = 'Fundraiser'", "difficulty": "moderate" }, { "question_id": 1324, "question": "What is the average attendance of meetings in 2020?", "db_id": "student_club", "evidence": "meetings in 2020 refers to type = 'Meeting' where YEAR(event_date) = 2020; average = DIVIDE(COUNT(event_id), COUNT(DISTINCT event_name))", "code": "import pandas as pd\n\n# Read the CSV files\ndf_event = pd.read_csv('event.csv')\ndf_attendance = pd.read_csv('attendance.csv')\n\n# Filter for meetings in 2020\n# SQL: WHERE SUBSTR(T1.event_date, 1, 4) = '2020' AND T1.type = 'Meeting'\ndf_event['event_date'] = df_event['event_date'].astype(str)\nevent_2020 = df_event[(df_event['type'] == 'Meeting') & (df_event['event_date'].str.startswith('2020'))]\n\n# Inner join event and attendance tables\n# SQL: INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event\nmerged = pd.merge(event_2020, df_attendance, left_on='event_id', right_on='link_to_event')\n\n# Calculate the average\n# SQL: CAST(COUNT(T2.link_to_event) AS REAL) / COUNT(DISTINCT T1.event_name)\nnumerator = len(merged)\ndenominator = merged['event_name'].nunique()\n\n# Handle division by zero if necessary, though SQL assumes data exists\nresult = numerator / denominator if denominator != 0 else 0.0\nprint(result)", "sql": "SELECT CAST(COUNT(T2.link_to_event) AS REAL) / COUNT(DISTINCT T1.event_name) FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event WHERE SUBSTR(T1.event_date, 1, 4) = '2020' AND T1.type = 'Meeting'", "difficulty": "moderate" }, { "question_id": 1325, "question": "What is the most expensive item that was spent in support of club events?", "db_id": "student_club", "evidence": "item in support of club events refers to expense_description; most expensive refers to MAX(cost)", "code": "import pandas as pd\nresult = expense.nlargest(1, 'cost')[['expense_description']]", "sql": "SELECT expense_description FROM expense ORDER BY cost DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1326, "question": "How many members of the Student_Club have majored Environmental Engineering?\n", "db_id": "student_club", "evidence": "'Environmental Engineering' is the major name", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[merged['major_name'] == 'Environmental Engineering']\nresult = len(filtered)", "sql": "SELECT COUNT(T1.member_id) FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.major_name = 'Environmental Engineering'", "difficulty": "simple" }, { "question_id": 1327, "question": "List the full name of all the members of the Student_Club who attended the \"Laugh Out Loud\" event.", "db_id": "student_club", "evidence": "full name of members refers to first_name, last_name; 'Laugh Out Loud' is an event name;", "code": "import pandas as pd\n\n# Merge member with attendance\nmerged1 = pd.merge(member, attendance, left_on='member_id', right_on='link_to_member')\n\n# Merge with event\nmerged2 = pd.merge(merged1, event, left_on='link_to_event', right_on='event_id')\n\n# Filter for 'Laugh Out Loud' event\nfiltered = merged2[merged2['event_name'] == 'Laugh Out Loud']\n\n# Select first_name and last_name\nresult = filtered[['first_name', 'last_name']]", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN attendance AS T2 ON T1.member_id = T2.link_to_member INNER JOIN event AS T3 ON T2.link_to_event = T3.event_id WHERE T3.event_name = 'Laugh Out Loud'", "difficulty": "moderate" }, { "question_id": 1328, "question": "List the last name of all the students who majored Law and Constitutional Studies. \n", "db_id": "student_club", "evidence": "'Law and Constitutional Studies' is the major name", "code": "import pandas as pd\nresult = pd.merge(member, major, left_on='link_to_major', right_on='major_id')[lambda x: x['major_name'] == 'Law and Constitutional Studies']['last_name']", "sql": "SELECT T1.last_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.major_name = 'Law and Constitutional Studies'", "difficulty": "simple" }, { "question_id": 1329, "question": "What county did Sherri Ramsey grew up?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nresult = pd.merge(member[member['first_name'] == 'Sherri'][member['last_name'] == 'Ramsey'], zip_code, left_on='zip', right_on='zip_code')[['county']]", "sql": "SELECT T2.county FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T1.first_name = 'Sherri' AND T1.last_name = 'Ramsey'", "difficulty": "simple" }, { "question_id": 1330, "question": "What college offers the major that Tyler Hewitt took?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nresult = pd.merge(member[member['first_name'] == 'Tyler'][member['last_name'] == 'Hewitt'], major, left_on='link_to_major', right_on='major_id')[['college']]", "sql": "SELECT T2.college FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.first_name = 'Tyler' AND T1.last_name = 'Hewitt'", "difficulty": "simple" }, { "question_id": 1331, "question": "What is the amount of the funds that the Vice President received?", "db_id": "student_club", "evidence": "'Vice President' is a position of Student Club; funds received refers to amount.", "code": "import pandas as pd\nresult = pd.merge(member[member['position'] == 'Vice President'], income, left_on='member_id', right_on='link_to_member')[['amount']]", "sql": "SELECT T2.amount FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T1.position = 'Vice President'", "difficulty": "simple" }, { "question_id": 1332, "question": "How much did the Student_Club members spend on food in September Meeting?", "db_id": "student_club", "evidence": "amount spent refers to spent; spend on food in September Meeting refers to category = 'Food' where event_name = 'September Meeting'", "code": "import pandas as pd\n\n# Merge event and budget tables\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\n\n# Filter for September Meeting and Food category\nfiltered = merged[(merged['event_name'] == 'September Meeting') & (merged['category'] == 'Food')]\n\n# Extract month from event_date and filter for September (month 09)\nfiltered = filtered[filtered['event_date'].str[5:7] == '09']\n\n# Get the spent amount\nresult = filtered[['spent']]", "sql": "SELECT T2.spent FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'September Meeting' AND T2.category = 'Food' AND SUBSTR(T1.event_date, 6, 2) = '09'", "difficulty": "moderate" }, { "question_id": 1333, "question": "What city and state did the President of the Student_Club grow up?", "db_id": "student_club", "evidence": "'President' is a position of Student Club;", "code": "import pandas as pd\nresult = pd.merge(member[member['position'] == 'President'], zip_code, left_on='zip', right_on='zip_code')[['city', 'state']]", "sql": "SELECT T2.city, T2.state FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T1.position = 'President'", "difficulty": "simple" }, { "question_id": 1334, "question": "List the full name of the Student_Club members that grew up in Illinois state.", "db_id": "student_club", "evidence": "full name of member refers to first_name, last_name", "code": "import pandas as pd\nresult = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')[lambda x: x['state'] == 'Illinois'][['first_name', 'last_name']]", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T2.state = 'Illinois'", "difficulty": "simple" }, { "question_id": 1335, "question": "How much did the Student_Club members spend on advertisement in September Meeting?", "db_id": "student_club", "evidence": "amount spent refers to spent; spend on food in September Meeting refers to category = 'Advertisement' where event_name = 'September Meeting'", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nfiltered = merged[(merged['event_name'] == 'September Meeting') & (merged['category'] == 'Advertisement') & (merged['event_date'].str[5:7] == '09')]\nresult = filtered[['spent']]", "sql": "SELECT T2.spent FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'September Meeting' AND T2.category = 'Advertisement' AND SUBSTR(T1.event_date, 6, 2) = '09'", "difficulty": "moderate" }, { "question_id": 1336, "question": "What department offers the major that Pierce and Guidi took?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[(merged['last_name'] == 'Pierce') | (merged['last_name'] == 'Guidi')]\nresult = filtered[['department']]", "sql": "SELECT T2.department FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.last_name = 'Pierce' OR T1.last_name = 'Guidi'", "difficulty": "simple" }, { "question_id": 1337, "question": "What is the total budgeted amount for all category in \"October Speaker\" event?", "db_id": "student_club", "evidence": "event_name equals 'October Speaker' in the database; sum of amount;", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nfiltered = merged[merged['event_name'] == 'October Speaker']\nresult = filtered['amount'].sum()", "sql": "SELECT SUM(T2.amount) FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'October Speaker'", "difficulty": "simple" }, { "question_id": 1338, "question": "Was each expense in October Meeting on October 8, 2019 approved?", "db_id": "student_club", "evidence": "event_name equals 'October Meeting' in the database; event_date equals '2019-10-08' in the database;event_date starts with '2019-10-08' in the database", "code": "import pandas as pd\nfiltered_events = event[(event['event_name'] == 'October Meeting') & (event['event_date'].str.startswith('2019-10-08'))]\nmerged_budget = pd.merge(filtered_events, budget, left_on='event_id', right_on='link_to_event')\nmerged_expense = pd.merge(merged_budget, expense, left_on='budget_id', right_on='link_to_budget')\nresult = merged_expense[['approved']]", "sql": "SELECT T3.approved FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget WHERE T1.event_name = 'October Meeting' AND T1.event_date LIKE '2019-10-08%'", "difficulty": "moderate" }, { "question_id": 1339, "question": "Calculate the total average cost that Elijah Allen spent in the events on September and October.", "db_id": "student_club", "evidence": "Elijah Allen is the full name; full name refers to first_name, last_name; The 5th and 6th string of the expense_date in the expense table can refer to month; events in September and October refers to month(expense_date) = 9 OR month(expense_date) = 10", "code": "import pandas as pd\nmerged = pd.merge(member, expense, left_on='member_id', right_on='link_to_member')\nfiltered = merged[(merged['first_name'] == 'Elijah') & (merged['last_name'] == 'Allen') & ((merged['expense_date'].str[5:7] == '09') | (merged['expense_date'].str[5:7] == '10'))]\nresult = filtered['cost'].mean()", "sql": "SELECT AVG(T2.cost) FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T1.last_name = 'Allen' AND T1.first_name = 'Elijah' AND (SUBSTR(T2.expense_date, 6, 2) = '09' OR SUBSTR(T2.expense_date, 6, 2) = '10')", "difficulty": "challenging" }, { "question_id": 1340, "question": "Calculate the difference of the total amount spent in all events by the Student_Club in year 2019 and 2020.", "db_id": "student_club", "evidence": "The first 4 strings of the event_date values in the event table can represent year; The difference of the total amount spent = SUBTRACT(spent where YEAR(event_date) = 2019, spent where YEAR(event_date) = 2020)", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nspent_2019 = merged[merged['event_date'].str[:4] == '2019']['spent'].sum()\nspent_2020 = merged[merged['event_date'].str[:4] == '2020']['spent'].sum()\nresult = pd.DataFrame({'num': [spent_2019 - spent_2020]})", "sql": "SELECT SUM(CASE WHEN SUBSTR(T1.event_date, 1, 4) = '2019' THEN T2.spent ELSE 0 END) - SUM(CASE WHEN SUBSTR(T1.event_date, 1, 4) = '2020' THEN T2.spent ELSE 0 END) AS num FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event", "difficulty": "moderate" }, { "question_id": 1341, "question": "Give the location for \"Spring Budget Review\".", "db_id": "student_club", "evidence": "'Spring Budget Review' is an event name;", "code": "import pandas as pd\n\n# Load the event table\nevent_df = pd.read_csv('event.csv')\n\n# Filter the event with name 'Spring Budget Review'\nspring_budget_review = event_df[event_df['event_name'] == 'Spring Budget Review']\n\n# Get the location of the event\nresult = spring_budget_review['location'].values[0]\n\nprint(result)", "sql": "SELECT location FROM event WHERE event_name = 'Spring Budget Review'", "difficulty": "simple" }, { "question_id": 1342, "question": "What was the cost for the \"Posters\" on 2019/9/4?", "db_id": "student_club", "evidence": "'Poster' is an event description; on 2019/9/14 refers to event_date = '2019-09-04'", "code": "import pandas as pd\nresult = expense[(expense['expense_description'] == 'Posters') & (expense['expense_date'] == '2019-09-04')]['cost']", "sql": "SELECT e.cost FROM expense e JOIN budget b ON e.link_to_budget = b.budget_id JOIN event ev ON b.link_to_event = ev.event_id WHERE ev.event_name = 'Posters' AND ev.event_date = '2019-09-04';", "difficulty": "simple" }, { "question_id": 1343, "question": "With the biggest budget for the \"Food\", what was the remaining of it?", "db_id": "student_club", "evidence": "category equals 'Food' in the database;", "code": "import pandas as pd\nfood_budgets = budget[budget['category'] == 'Food']\nmax_amount = food_budgets['amount'].max()\nresult = food_budgets[food_budgets['amount'] == max_amount]['remaining'].iloc[0]", "sql": "SELECT remaining FROM budget WHERE category = 'Food' AND amount = ( SELECT MAX(amount) FROM budget WHERE category = 'Food' )", "difficulty": "simple" }, { "question_id": 1344, "question": "What was the notes of the fundraising on 2019/9/14?", "db_id": "student_club", "evidence": "source equals 'Fundraising' in the database; date_received equals '2019-09-14' in the database; ratio calculated by dividing 2019 by 9;", "code": "import pandas as pd\n\n# Read the necessary table\nincome_df = pd.read_csv('income.csv')\n\n# Filter the DataFrame for the specific conditions\nfiltered_income = income_df[(income_df['source'] == 'Fundraising') & (income_df['date_received'] == '2019-09-14')]\n\n# Extract the notes\nresult = filtered_income['notes'].values[0] if not filtered_income.empty else None\n\nprint(result)", "sql": "SELECT notes FROM income WHERE source = 'Fundraising' AND date_received = '2019-09-14'", "difficulty": "simple" }, { "question_id": 1345, "question": "How many majors are there in \"College of Humanities and Social Sciences\"?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nresult = major[major['college'] == 'College of Humanities and Social Sciences']['major_name'].count()", "sql": "SELECT COUNT(major_name) FROM major WHERE college = 'College of Humanities and Social Sciences'", "difficulty": "simple" }, { "question_id": 1346, "question": "Tell the phone number of \"Carlo Jacobs\".", "db_id": "student_club", "evidence": "Carlo Jacobs is the full name; full name refers to first_name, last_name;", "code": "import pandas as pd\nresult = member[(member['first_name'] == 'Carlo') & (member['last_name'] == 'Jacobs')]['phone']", "sql": "SELECT phone FROM member WHERE first_name = 'Carlo' AND last_name = 'Jacobs'", "difficulty": "simple" }, { "question_id": 1347, "question": "Tell the hometown county for \"Adela O'Gallagher\".", "db_id": "student_club", "evidence": "hometown county refers to county", "code": "import pandas as pd\nresult = pd.merge(member[member['first_name'] == 'Adela'][member['last_name'] == \"O'Gallagher\"], zip_code, left_on='zip', right_on='zip_code')[['county']]", "sql": "SELECT T2.county FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T1.first_name = 'Adela' AND T1.last_name = 'O''Gallagher'", "difficulty": "simple" }, { "question_id": 1348, "question": "For all the budgets for \"November Meeting\", how many of them had exceeded the budget?", "db_id": "student_club", "evidence": "remaining is less than 0 in the database;", "code": "import pandas as pd\nmerged = pd.merge(budget, event, left_on='link_to_event', right_on='event_id')\nfiltered = merged[(merged['event_name'] == 'November Meeting') & (merged['remaining'] < 0)]\nresult = len(filtered)", "sql": "SELECT COUNT(T2.event_id) FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T2.event_name = 'November Meeting' AND T1.remaining < 0", "difficulty": "simple" }, { "question_id": 1349, "question": "Provide the total number of the budget amount for \"September Speaker\" event.", "db_id": "student_club", "evidence": "'September Speaker' is an event name; total number of budget amount refers to SUM(amount)", "code": "import pandas as pd\nimport numpy as np\n\n# Merge budget and event tables\nmerged = pd.merge(budget, event, left_on='link_to_event', right_on='event_id')\n\n# Filter for 'September Speaker' event\nfiltered = merged[merged['event_name'] == 'September Speaker']\n\n# Calculate the sum of amount\nresult = filtered['amount'].sum()", "sql": "SELECT SUM(T1.amount) FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T2.event_name = 'September Speaker'", "difficulty": "simple" }, { "question_id": 1350, "question": "What is the status of the event which bought \"Post Cards, Posters\" on 2019/8/20?", "db_id": "student_club", "evidence": "'Post Cards, Posters' is an expense description; on 2019/8/20 refers to expense_date = '2019-8-20'; status of event refers to event_status", "code": "import pandas as pd\nfiltered_expense = expense[expense['expense_description'] == 'Post Cards, Posters']\nfiltered_expense = filtered_expense[filtered_expense['expense_date'] == '2019-08-20']\nmerged = pd.merge(filtered_expense, budget, left_on='link_to_budget', right_on='budget_id')\nmerged = pd.merge(merged, event, left_on='link_to_event', right_on='event_id')\nresult = merged[['status']]", "sql": "SELECT T3.status FROM expense AS T2 INNER JOIN budget AS T1 ON T2.link_to_budget = T1.budget_id INNER JOIN event AS T3 ON T1.link_to_event = T3.event_id WHERE T2.expense_description = 'Post Cards, Posters' AND T2.expense_date = '2019-08-20'", "difficulty": "moderate" }, { "question_id": 1351, "question": "What was Brent Thomason's major?", "db_id": "student_club", "evidence": "Brent Thomason is the full name; full name refers to first_name, last_name; major refers to major_name", "code": "import pandas as pd\nmerged = pd.merge(member[member['first_name'] == 'Brent'][member['last_name'] == 'Thomason'], major, left_on='link_to_major', right_on='major_id')\nresult = merged[['major_name']]", "sql": "SELECT T2.major_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.first_name = 'Brent' AND T1.last_name = 'Thomason'", "difficulty": "simple" }, { "question_id": 1352, "question": "For all the club members from \"Business\" major, how many of them wear medium size t-shirt?", "db_id": "student_club", "evidence": "'Business' is a major name; wear medium size t-shirt refers to t_shirt_size = 'Medium'", "code": "import pandas as pd\n\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[(merged['major_name'] == 'Business') & (merged['t_shirt_size'] == 'Medium')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.member_id) FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.major_name = 'Business' AND T1.t_shirt_size = 'Medium'", "difficulty": "moderate" }, { "question_id": 1353, "question": "What's Christof Nielson's zip code type?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\n\n# Merge member and zip_code tables\nmerged = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')\n\n# Filter for Christof Nielson\nfiltered = merged[(merged['first_name'] == 'Christof') & (merged['last_name'] == 'Nielson')]\n\n# Select the type column\nresult = filtered[['type']]", "sql": "SELECT T2.type FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T1.first_name = 'Christof' AND T1.last_name = 'Nielson'", "difficulty": "simple" }, { "question_id": 1354, "question": "State the major name for the Vice President of the club.", "db_id": "student_club", "evidence": "'Vice President' is a position of Student Club", "code": "import pandas as pd\nmerged = pd.merge(member[member['position'] == 'Vice President'], major, left_on='link_to_major', right_on='major_id')\nresult = merged[['major_name']]", "sql": "SELECT T2.major_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.position = 'Vice President'", "difficulty": "simple" }, { "question_id": 1355, "question": "Where is the hometown state for \"Sacha Harrison\"?", "db_id": "student_club", "evidence": "hometown state refers to state;", "code": "import pandas as pd\nmerged = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')\nfiltered = merged[(merged['first_name'] == 'Sacha') & (merged['last_name'] == 'Harrison')]\nresult = filtered[['state']]", "sql": "SELECT T2.state FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T1.first_name = 'Sacha' AND T1.last_name = 'Harrison'", "difficulty": "simple" }, { "question_id": 1356, "question": "Which department was the President of the club in?", "db_id": "student_club", "evidence": "'President' is a position of Student Club", "code": "import pandas as pd\nmerged = pd.merge(member[member['position'] == 'President'], major, left_on='link_to_major', right_on='major_id')\nresult = merged[['department']]", "sql": "SELECT T2.department FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.position = 'President'", "difficulty": "simple" }, { "question_id": 1357, "question": "State the date Connor Hilton paid his/her dues.", "db_id": "student_club", "evidence": "Connor Hilton is the full name; full name refers to first_name, last_name; date the dues was paid refers to date_received where source = 'Dues';", "code": "import pandas as pd\nmerged = pd.merge(member, income, left_on='member_id', right_on='link_to_member')\nfiltered = merged[(merged['first_name'] == 'Connor') & (merged['last_name'] == 'Hilton') & (merged['source'] == 'Dues')]\nresult = filtered[['date_received']]", "sql": "SELECT T2.date_received FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T1.first_name = 'Connor' AND T1.last_name = 'Hilton' AND T2.source = 'Dues'", "difficulty": "simple" }, { "question_id": 1358, "question": "Who was the first one paid his/her dues? Tell the full name.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name; first paid dues refers to MIN(received_date) where source = 'Dues'", "code": "import pandas as pd\nmerged = pd.merge(member, income, left_on='member_id', right_on='link_to_member')\nfiltered = merged[merged['source'] == 'Dues']\nsorted_data = filtered.sort_values('date_received')\nresult = sorted_data[['first_name', 'last_name']].head(1)", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T2.source = 'Dues' ORDER BY T2.date_received LIMIT 1", "difficulty": "simple" }, { "question_id": 1359, "question": "How many times was the budget in Advertisement for \"Yearly Kickoff\" meeting more than \"October Meeting\"?", "db_id": "student_club", "evidence": "category equals 'Advertisement' in the database; event_name equals 'Yearly Kickoff' in the database; event_name equals 'October Meeting' in the database; sum of amount when event_name = 'Yearly Kickoff'; sum of amount when event_name = 'October Meeting';", "code": "import pandas as pd\nmerged = pd.merge(budget, event, left_on='link_to_event', right_on='event_id')\nfiltered = merged[(merged['category'] == 'Advertisement') & (merged['type'] == 'Meeting')]\nyearly = filtered[filtered['event_name'] == 'Yearly Kickoff']['amount'].sum()\noctober = filtered[filtered['event_name'] == 'October Meeting']['amount'].sum()\nresult = pd.DataFrame([yearly / october], columns=['ratio'])", "sql": "SELECT CAST(SUM(CASE WHEN T2.event_name = 'Yearly Kickoff' THEN T1.amount ELSE 0 END) AS REAL) / SUM(CASE WHEN T2.event_name = 'October Meeting' THEN T1.amount ELSE 0 END) FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T1.category = 'Advertisement' AND T2.type = 'Meeting'", "difficulty": "challenging" }, { "question_id": 1360, "question": "What percentage was the budget for Parking to the total budget for the \"November Speaker\"?", "db_id": "student_club", "evidence": "category equals 'Parking' in the database; event_name equals 'November Speaker' in the database; count of event_name = 'November Speaker; sum of amount where category = 'Parking' and event_name = 'November Speaker';", "code": "import pandas as pd\n\nmerged = pd.merge(budget, event, left_on='link_to_event', right_on='event_id')\nnovember_speaker = merged[merged['event_name'] == 'November Speaker']\nparking_amount = november_speaker[november_speaker['category'] == 'Parking']['amount'].sum()\ntotal_amount = november_speaker['amount'].sum()\nresult = (parking_amount * 100) / total_amount", "sql": "SELECT (CAST(SUM(CASE WHEN T1.category = 'Parking' THEN T1.amount ELSE 0 END) AS REAL) * 100) / SUM(T1.amount) FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T2.event_name = 'November Speaker'", "difficulty": "moderate" }, { "question_id": 1361, "question": "What is the total cost of the pizzas for all the events?", "db_id": "student_club", "evidence": "expense_description equals 'Pizza' in the database; sum of cost;", "code": "import pandas as pd\nresult = expense[expense['expense_description'] == 'Pizza']['cost'].sum()", "sql": "SELECT SUM(cost) FROM expense WHERE expense_description = 'Pizza'", "difficulty": "simple" }, { "question_id": 1362, "question": "How many cities are there in Orange County, Virginia?", "db_id": "student_club", "evidence": "Orange County is the county name, Virginia is the state name", "code": "import pandas as pd\nresult = len(zip_code[(zip_code['county'] == 'Orange County') & (zip_code['state'] == 'Virginia')]['city'].unique())", "sql": "SELECT COUNT(city) FROM zip_code WHERE county = 'Orange County' AND state = 'Virginia'", "difficulty": "simple" }, { "question_id": 1363, "question": "List all of the College of Humanities and Social Sciences' departments.", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\n\n# Read the major table from CSV\nmajor_df = pd.read_csv('major.csv')\n\n# Filter the departments in the College of Humanities and Social Sciences\nresult = major_df[major_df['college'] == 'College of Humanities and Social Sciences']['department'].unique()\n\n# Print the result\nprint(result)", "sql": "SELECT department FROM major WHERE college = 'College of Humanities and Social Sciences'", "difficulty": "simple" }, { "question_id": 1364, "question": "Where is Amy Firth's hometown?", "db_id": "student_club", "evidence": "hometown refers to city, county, state", "code": "import pandas as pd\nresult = pd.merge(member[member['first_name'] == 'Amy'][member['last_name'] == 'Firth'], zip_code, left_on='zip', right_on='zip_code')[['city', 'county', 'state']]", "sql": "SELECT T2.city, T2.county, T2.state FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T1.first_name = 'Amy' AND T1.last_name = 'Firth'", "difficulty": "simple" }, { "question_id": 1365, "question": "What are the expenses of the budget with the lowest remaining?", "db_id": "student_club", "evidence": "expense of budget refers to expense_description; lowest remaining refers to MIN(remaining)", "code": "import pandas as pd\n\n# Read the necessary CSV files\nevent_df = pd.read_csv('event.csv')\nmajor_df = pd.read_csv('major.csv')\nzip_code_df = pd.read_csv('zip_code.csv')\nattendance_df = pd.read_csv('attendance.csv')\nbudget_df = pd.read_csv('budget.csv')\nexpense_df = pd.read_csv('expense.csv')\nincome_df = pd.read_csv('income.csv')\nmember_df = pd.read_csv('member.csv')\n\n# Find the budget with the lowest remaining amount\nlowest_remaining_budget = budget_df.loc[budget_df['remaining'].idxmin()]\n\n# Get the link_to_event of the budget with the lowest remaining amount\nlink_to_event_lowest_remaining = lowest_remaining_budget['link_to_event']\n\n# Filter the expense DataFrame to get expenses related to the budget with the lowest remaining amount\nexpenses_lowest_remaining = expense_df[expense_df['link_to_budget'] == lowest_remaining_budget['budget_id']]\n\n# Extract the expense descriptions\nresult = expenses_lowest_remaining['expense_description'].tolist()\n\nprint(result)", "sql": "SELECT T2.expense_description FROM budget AS T1 INNER JOIN expense AS T2 ON T1.budget_id = T2.link_to_budget ORDER BY T1.remaining LIMIT 1", "difficulty": "simple" }, { "question_id": 1366, "question": "List all the members who attended the event \"October Meeting\".", "db_id": "student_club", "evidence": "'October Meeting' is an event name;", "code": "import pandas as pd\n\n# Merge event with attendance on event_id\nmerged = pd.merge(event[event['event_name'] == 'October Meeting'], attendance, left_on='event_id', right_on='link_to_event')\n\n# Merge with member table to get member details\nresult = pd.merge(merged, member[['member_id']], left_on='link_to_member', right_on='member_id')[['member_id']].drop_duplicates()", "sql": "SELECT DISTINCT T3.member_id FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event INNER JOIN member AS T3 ON T2.link_to_member = T3.member_id WHERE T1.event_name = 'October Meeting'", "difficulty": "simple" }, { "question_id": 1367, "question": "Which college do most of the members go to?", "db_id": "student_club", "evidence": "count of major.college;", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\ncollege_counts = merged.groupby('college').size().reset_index(name='count')\nresult = college_counts.sort_values('count', ascending=False).head(1)['college'].iloc[0]", "sql": "SELECT T2.college FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id GROUP BY T2.major_id ORDER BY COUNT(T2.college) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1368, "question": "What does the person with the phone number \"809-555-3360\" major in?", "db_id": "student_club", "evidence": "major in refers to major_name", "code": "import pandas as pd\n\n# Merge member and major tables\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\n\n# Filter for the specific phone number\nfiltered = merged[merged['phone'] == '809-555-3360']\n\n# Select the major_name\nresult = filtered[['major_name']]", "sql": "SELECT T2.major_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.phone = '809-555-3360'", "difficulty": "simple" }, { "question_id": 1369, "question": "Which event has the highest budget amount?", "db_id": "student_club", "evidence": "event refers to event_name; highest budget amount refers to MAX(amount)", "code": "import pandas as pd\nimport numpy as np\n\n# Merge budget with event table\nmerged = pd.merge(budget, event, left_on='link_to_event', right_on='event_id')\n\n# Sort by amount in descending order and get the first row\nresult = merged.sort_values('amount', ascending=False).head(1)[['event_name']]", "sql": "SELECT T2.event_name FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id ORDER BY T1.amount DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1370, "question": "List all the expenses incurred by the vice president.", "db_id": "student_club", "evidence": "expense refers to expense_description; 'Vice President' is a position of the Student Club", "code": "import pandas as pd\nmerged = pd.merge(member[member['position'] == 'Vice President'], expense, left_on='member_id', right_on='link_to_member')\nresult = merged[['expense_id', 'expense_description']]", "sql": "SELECT T2.expense_id, T2.expense_description FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T1.position = 'Vice President'", "difficulty": "simple" }, { "question_id": 1371, "question": "How many members attended the \"Women's Soccer\" event?", "db_id": "student_club", "evidence": "'Women's Soccer' is the event name;", "code": "import pandas as pd\nresult = pd.merge(event[event['event_name'] == \"Women's Soccer\"], attendance, left_on='event_id', right_on='link_to_event')['link_to_member'].count()", "sql": "SELECT COUNT(T2.link_to_member) FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'Women''s Soccer'", "difficulty": "simple" }, { "question_id": 1372, "question": "When did the member, Casey Mason, received the income?", "db_id": "student_club", "evidence": "when the income was received refers to date_received", "code": "import pandas as pd\nfiltered_member = member[(member['first_name'] == 'Casey') & (member['last_name'] == 'Mason')]\nmerged = pd.merge(filtered_member, income, left_on='member_id', right_on='link_to_member')\nresult = merged[['date_received']]", "sql": "SELECT T2.date_received FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T1.first_name = 'Casey' AND T1.last_name = 'Mason'", "difficulty": "simple" }, { "question_id": 1373, "question": "How many of the members' hometowns are from Maryland state?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')\nmaryland_members = merged[merged['state'] == 'Maryland']\nresult = len(maryland_members)", "sql": "SELECT COUNT(T2.member_id) FROM zip_code AS T1 INNER JOIN member AS T2 ON T1.zip_code = T2.zip WHERE T1.state = 'Maryland'", "difficulty": "simple" }, { "question_id": 1374, "question": "How many events did the member with the phone number \"954-555-6240\" attend?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\n\n# Filter member with phone number '954-555-6240'\nmember_filtered = member[member['phone'] == '954-555-6240']\n\n# Merge with attendance table\nmerged = pd.merge(member_filtered, attendance, left_on='member_id', right_on='link_to_member')\n\n# Count the number of events attended\nresult = len(merged)", "sql": "SELECT COUNT(T2.link_to_event) FROM member AS T1 INNER JOIN attendance AS T2 ON T1.member_id = T2.link_to_member WHERE T1.phone = '954-555-6240'", "difficulty": "simple" }, { "question_id": 1375, "question": "List all the members of the \"School of Applied Sciences, Technology and Education\" department.", "db_id": "student_club", "evidence": "list all members means to list all the full name; full name refers to first_name, last_name;", "code": "import pandas as pd\n\n# Read tables\nevent = pd.read_csv('event.csv')\nmajor = pd.read_csv('major.csv')\nzip_code = pd.read_csv('zip_code.csv')\nattendance = pd.read_csv('attendance.csv')\nbudget = pd.read_csv('budget.csv')\nexpense = pd.read_csv('expense.csv')\nincome = pd.read_csv('income.csv')\nmember = pd.read_csv('member.csv')\n\n# Filter members by department\ndepartment_name = \"School of Applied Sciences, Technology and Education\"\nfiltered_members = member[member['link_to_major'].isin(major[major['department'] == department_name]['major_id'])]\n\n# Select first_name and last_name\nresult = filtered_members[['first_name', 'last_name']]\n\nprint(result)", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.department = 'School of Applied Sciences, Technology and Education'", "difficulty": "moderate" }, { "question_id": 1376, "question": "Among all the closed events, which event has the highest spend-to-budget ratio?", "db_id": "student_club", "evidence": "closed events refers to event_name where status = 'Closed'; highest spend-to budget ratio refers to MAX(DIVIDE(spent, amount))", "code": "import pandas as pd\n# Merge budget and event tables\nmerged = pd.merge(budget, event, left_on='link_to_event', right_on='event_id')\n# Filter closed events\nclosed_events = merged[merged['status'] == 'Closed']\n# Group by event and calculate sums\ngrouped = closed_events.groupby(['event_id', 'event_name']).agg(total_spent=('spent', 'sum'), total_amount=('amount', 'sum')).reset_index()\n# Calculate ratio\ngrouped['ratio'] = grouped['total_spent'] / grouped['total_amount']\n# Get highest ratio event\nresult = grouped.sort_values('ratio', ascending=False).head(1)[['event_name', 'ratio']]", "sql": "SELECT T2.event_name, (SUM(T1.spent)/SUM(T1.amount)) AS ratio FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T2.status = 'Closed' GROUP BY T2.event_id ORDER BY ratio DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1377, "question": "How many student have the position of president?", "db_id": "student_club", "evidence": "'President' is a position of Student Club", "code": "import pandas as pd\nresult = len(member[member['position'] == 'President'])", "sql": "SELECT COUNT(member_id) FROM member WHERE position = 'President'", "difficulty": "simple" }, { "question_id": 1378, "question": "What is the highest amount of budget spend for an event?", "db_id": "student_club", "evidence": "highest amount of budget spend refers to MAX(spent)", "code": "import pandas as pd\nresult = budget['spent'].max()", "sql": "SELECT MAX(spent) FROM budget", "difficulty": "simple" }, { "question_id": 1379, "question": "How many meeting events were held in 2020?", "db_id": "student_club", "evidence": "meeting events refers to type = 'Meeting'; held in 2020 refers to YEAR(event_date) = 2020", "code": "import pandas as pd\nimport numpy as np\n\n# Filter for Meeting events in 2020\nmeeting_events_2020 = event[(event['type'] == 'Meeting') & (event['event_date'].str[:4] == '2020')]\n\n# Count the number of meeting events\nresult = len(meeting_events_2020)", "sql": "SELECT COUNT(event_id) FROM event WHERE type = 'Meeting' AND SUBSTR(event_date, 1, 4) = '2020'", "difficulty": "simple" }, { "question_id": 1380, "question": "What is the total amount of money spent for food?", "db_id": "student_club", "evidence": "total amount of money spent refers to SUM(spent); spent for food refers to category = 'Food'", "code": "import pandas as pd\nresult = budget[budget['category'] == 'Food']['spent'].sum()", "sql": "SELECT SUM(spent) FROM budget WHERE category = 'Food'", "difficulty": "simple" }, { "question_id": 1381, "question": "List the name of students that have attended more than 7 events.", "db_id": "student_club", "evidence": "name of students means the full name; full name refers to first_name, last_name; attended more than 7 events refers to COUNT(link_to_event) > 7", "code": "import pandas as pd\nmerged = pd.merge(member, attendance, left_on='member_id', right_on='link_to_member')\ngrouped = merged.groupby(['link_to_member', 'first_name', 'last_name'])['link_to_event'].count().reset_index()\nresult = grouped[grouped['link_to_event'] > 7][['first_name', 'last_name']]", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN attendance AS T2 ON T1.member_id = T2.link_to_member GROUP BY T2.link_to_member HAVING COUNT(T2.link_to_event) > 7", "difficulty": "moderate" }, { "question_id": 1382, "question": "Among the students majored in interior design, who have attended the Community Theater event?", "db_id": "student_club", "evidence": "majored in music refers to major_name = 'Interior Design'; 'Community Theater' is the event name;", "code": "import pandas as pd\n\n# Merge major with member to get students with their majors\nstudents_with_major = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\n\n# Filter for Interior Design students\ninterior_design_students = students_with_major[students_with_major['major_name'] == 'Interior Design']\n\n# Merge with attendance to get events attended by these students\nstudents_attendance = pd.merge(interior_design_students, attendance, left_on='member_id', right_on='link_to_member')\n\n# Merge with event to get event details\nstudents_events = pd.merge(students_attendance, event, left_on='link_to_event', right_on='event_id')\n\n# Filter for Community Theater event\ncommunity_theater_attendees = students_events[students_events['event_name'] == 'Community Theater']\n\n# Select only first_name and last_name\nresult = community_theater_attendees[['first_name', 'last_name']]", "sql": "SELECT T2.first_name, T2.last_name FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major INNER JOIN attendance AS T3 ON T2.member_id = T3.link_to_member INNER JOIN event AS T4 ON T3.link_to_event = T4.event_id WHERE T4.event_name = 'Community Theater' AND T1.major_name = 'Interior Design'", "difficulty": "moderate" }, { "question_id": 1383, "question": "State the name of students from Georgetown, South Carolina.", "db_id": "student_club", "evidence": "name of students means the full name; full name refers to first_name, last_name; Georgetown is a city; South Carolina is a state", "code": "import pandas as pd\n\nresult = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')\nresult = result[(result['city'] == 'Georgetown') & (result['state'] == 'South Carolina')]\nresult = result[['first_name', 'last_name']]", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN zip_code AS T2 ON T1.zip = T2.zip_code WHERE T2.city = 'Georgetown' AND T2.state = 'South Carolina'", "difficulty": "simple" }, { "question_id": 1384, "question": "How many income generated by Grant Gilmour?", "db_id": "student_club", "evidence": "income generated refers to income.amount", "code": "import pandas as pd\nmerged = pd.merge(member, income, left_on='member_id', right_on='link_to_member')\nfiltered = merged[(merged['first_name'] == 'Grant') & (merged['last_name'] == 'Gilmour')]\nresult = filtered['amount']", "sql": "SELECT T2.amount FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T1.first_name = 'Grant' AND T1.last_name = 'Gilmour'", "difficulty": "simple" }, { "question_id": 1385, "question": "Which student was able to generate income more than $40?", "db_id": "student_club", "evidence": "name of students means the full name; full name refers to first_name, last_name; generate income more than $50 refers to income.amount > 40", "code": "import pandas as pd\nmerged = pd.merge(member, income, left_on='member_id', right_on='link_to_member')\nfiltered = merged[merged['amount'] > 40]\nresult = filtered[['first_name', 'last_name']]", "sql": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T2.amount > 40", "difficulty": "simple" }, { "question_id": 1386, "question": "What is the total expense for the Yearly Kickoff?", "db_id": "student_club", "evidence": "'Yearly Kickoff' is an event name; total expense refers to SUM(cost)", "code": "import pandas as pd\n\n# Merge event with budget\nmerged1 = pd.merge(event[event['event_name'] == 'Yearly Kickoff'], budget, left_on='event_id', right_on='link_to_event')\n\n# Merge with expense\nmerged2 = pd.merge(merged1, expense, left_on='budget_id', right_on='link_to_budget')\n\n# Calculate total expense\nresult = merged2['cost'].sum()", "sql": "SELECT SUM(T3.cost) FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget WHERE T1.event_name = 'Yearly Kickoff'", "difficulty": "simple" }, { "question_id": 1387, "question": "Which student has been entrusted to manage the budget for the Yearly Kickoff?", "db_id": "student_club", "evidence": "name of students means the full name; full name refers to first_name, last_name;'Yearly Kickoff' is an event name;link_to_member in expense refers to member entrusted with managing budget", "code": "import pandas as pd\nmerged1 = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nmerged2 = pd.merge(merged1, expense, left_on='budget_id', right_on='link_to_budget')\nmerged3 = pd.merge(merged2, member, left_on='link_to_member', right_on='member_id')\nfiltered = merged3[merged3['event_name'] == 'Yearly Kickoff']\nresult = filtered[['first_name', 'last_name']]", "sql": "SELECT T4.first_name, T4.last_name FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget INNER JOIN member AS T4 ON T3.link_to_member = T4.member_id WHERE T1.event_name = 'Yearly Kickoff'", "difficulty": "moderate" }, { "question_id": 1388, "question": "Which students manage to generate the highest income. State his/her full name along with the income source.", "db_id": "student_club", "evidence": "name of students means the full name; full name refers to first_name, last_name; generate the highest income refers to MAX(income.amount);", "code": "import pandas as pd\n\n# Merge member and income tables\nmerged = pd.merge(member, income, left_on='member_id', right_on='link_to_member')\n\n# Group by first_name, last_name, and source, then sum the amounts\ngrouped = merged.groupby(['first_name', 'last_name', 'source'])['amount'].sum().reset_index()\n\n# Sort by amount in descending order and get the top record\nresult = grouped.sort_values('amount', ascending=False).head(1)", "sql": "SELECT T1.first_name, T1.last_name, T2.source FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T2.amount = (SELECT MAX(amount) FROM income WHERE link_to_member = T1.member_id) ORDER BY T2.amount DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1389, "question": "Which event has the lowest cost?", "db_id": "student_club", "evidence": "event refers to event_name; lowest cost means MIN(cost)total cost refers to sum of expense.cost; event refers to event_name", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nmerged = pd.merge(merged, expense, left_on='budget_id', right_on='link_to_budget')\nresult = merged.groupby('event_name')['cost'].sum().reset_index(name='total_cost').sort_values('total_cost').head(1)", "sql": "SELECT T1.event_name, SUM(T3.cost) AS total_cost FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget GROUP BY T1.event_id ORDER BY total_cost LIMIT 1", "difficulty": "simple" }, { "question_id": 1390, "question": "Based on the total cost for all event, what is the percentage of cost for Yearly Kickoff event?", "db_id": "student_club", "evidence": "event_name equals 'Yearly Kickoff' in the database; sum of cost where event_name = 'Yearly Kickoff'; sum of cost;", "code": "import pandas as pd\n\n# Merge event with budget\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\n\n# Merge with expense\nmerged = pd.merge(merged, expense, left_on='budget_id', right_on='link_to_budget')\n\n# Calculate total cost for Yearly Kickoff\nyearly_kickoff_cost = merged[merged['event_name'] == 'Yearly Kickoff']['cost'].sum()\n\n# Calculate total cost for all events\ntotal_cost = merged['cost'].sum()\n\n# Calculate percentage\nresult = (yearly_kickoff_cost * 100.0) / total_cost", "sql": "SELECT (SUM(CASE WHEN T1.event_name = 'Yearly Kickoff' THEN T3.cost ELSE 0 END) * 100.0) / SUM(T3.cost) FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget", "difficulty": "moderate" }, { "question_id": 1391, "question": "What is the ratio between students majored in finance and physics?", "db_id": "student_club", "evidence": "major_name equals 'Finance' in the database; major_name equals 'Physics' in the database; sum of major_name = 'Finance'; sum of major_name = 'Physics';", "code": "import pandas as pd\nimport numpy as np\n\n# Merge member and major tables\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\n\n# Count students in Finance and Physics\nfinance_count = len(merged[merged['major_name'] == 'Finance'])\nphysics_count = len(merged[merged['major_name'] == 'Physics'])\n\n# Calculate ratio\nif physics_count > 0:\n ratio = finance_count / physics_count\nelse:\n ratio = np.nan\n\nresult = pd.DataFrame({'ratio': [ratio]})", "sql": "SELECT \n SUM(CASE WHEN mjr.major_name = 'Finance' THEN 1 ELSE 0 END) * 1.0 /\n SUM(CASE WHEN mjr.major_name = 'Physics' THEN 1 ELSE 0 END) AS ratio\nFROM member m\nJOIN major mjr ON m.link_to_major = mjr.major_id", "difficulty": "simple" }, { "question_id": 1392, "question": "Indicate the top source of funds received in September 2019 based on their amount.", "db_id": "student_club", "evidence": "top source funds refers to MAX(source); September 2019 means date_received BETWEEN '2019-09-01' and '2019-09-30'", "code": "import pandas as pd\n\n# Filter income for September 2019\nfiltered_income = income[(income['date_received'] >= '2019-09-01') & (income['date_received'] <= '2019-09-30')]\n\n# Group by source and sum the amounts\nsource_totals = filtered_income.groupby('source')['amount'].sum().reset_index()\n\n# Sort by amount in descending order and get the top source\nresult = source_totals.sort_values('amount', ascending=False).head(1)['source'].iloc[0]", "sql": "SELECT source FROM income WHERE date_received BETWEEN '2019-09-01' and '2019-09-30' ORDER BY source DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1393, "question": "Provide the full name and email address of the Student_Club's Secretary.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name; 'Secretary' is a position of Student Club", "code": "import pandas as pd\nresult = member[member['position'] == 'Secretary'][['first_name', 'last_name', 'email']]", "sql": "SELECT first_name, last_name, email FROM member WHERE position = 'Secretary'", "difficulty": "simple" }, { "question_id": 1394, "question": "How many members of the Student_Club have major in 'Physics Teaching'?", "db_id": "student_club", "evidence": "'Physics Teaching' is the major_name;", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[merged['major_name'] == 'Physics Teaching']\nresult = len(filtered)", "sql": "SELECT COUNT(T2.member_id) FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major WHERE T1.major_name = 'Physics Teaching'", "difficulty": "simple" }, { "question_id": 1395, "question": "How many members did attend the event 'Community Theater' in 2019?", "db_id": "student_club", "evidence": "event_name equals 'Community Theater' in the database;", "code": "import pandas as pd\n\n# Filter events for 'Community Theater' in 2019\nfiltered_events = event[(event['event_name'] == 'Community Theater') & (event['event_date'].str[:4] == '2019')]\n\n# Join with attendance table\nmerged = pd.merge(filtered_events, attendance, left_on='event_id', right_on='link_to_event')\n\n# Count the number of members who attended\nresult = len(merged['link_to_member'])", "sql": "SELECT COUNT(T2.link_to_member) FROM event AS T1 INNER JOIN attendance AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'Community Theater' AND SUBSTR(T1.event_date, 1, 4) = '2019'", "difficulty": "moderate" }, { "question_id": 1396, "question": "Provide the number of events attended by Luisa Guidi. What is her major?", "db_id": "student_club", "evidence": "major refers to major_name;", "code": "import pandas as pd\n\n# Merge member with attendance to get events attended by Luisa Guidi\nmerged = pd.merge(member[member['first_name'] == 'Luisa'][member['last_name'] == 'Guidi'], attendance, left_on='member_id', right_on='link_to_member')\n\n# Count the number of events\nevent_count = len(merged)\n\n# Get the major information\nmerged_with_major = pd.merge(member[member['first_name'] == 'Luisa'][member['last_name'] == 'Guidi'], major, left_on='link_to_major', right_on='major_id')\n\n# Create result with event count and major name\nresult = pd.DataFrame({'event_count': [event_count], 'major_name': [merged_with_major['major_name'].iloc[0] if len(merged_with_major) > 0 else None]})", "sql": "SELECT COUNT(T3.link_to_event), T1.major_name FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major INNER JOIN attendance AS T3 ON T2.member_id = T3.link_to_member WHERE T2.first_name = 'Luisa' AND T2.last_name = 'Guidi'", "difficulty": "simple" }, { "question_id": 1397, "question": "On average, how much did the Student_Club spend on food for the typical event in the past?", "db_id": "student_club", "evidence": "category equals 'Food' in the database; event_status equals 'Closed' in the database; count of spent; sum of spent;", "code": "import pandas as pd\n\ndef solve_query(budget_df):\n try:\n # Check if required columns exist\n required_columns = ['category', 'event_status', 'spent']\n for col in required_columns:\n if col not in budget_df.columns:\n raise KeyError(f\"Missing column: {col}\")\n\n # Filter rows where category is 'Food' and event_status is 'Closed'\n filtered_df = budget_df[(budget_df['category'] == 'Food') & (budget_df['event_status'] == 'Closed')]\n\n # Handle NULL values in 'spent' column\n filtered_df = filtered_df.dropna(subset=['spent'])\n\n # Calculate average spending\n if filtered_df.empty:\n return None # Return None for empty result set\n\n total_spent = filtered_df['spent'].sum()\n count_spent = filtered_df['spent'].count()\n average_spent = total_spent / count_spent if count_spent > 0 else 0\n\n return average_spent\n\n except Exception as e:\n print(f\"Error: {e}\")\n return None\n\n# Example usage with a sample DataFrame\nif __name__ == \"__main__\":\n # Create an example DataFrame (replace this with actual data loading)\n data = {\n 'category': ['Food', 'Supplies', 'Food', 'Transport'],\n 'event_status': ['Closed', 'Open', 'Closed', 'Closed'],\n 'spent': [120.5, None, 80.0, 50.75]\n }\n budget_df = pd.DataFrame(data)\n\n # Call the function\n result = solve_query(budget_df)\n print(result)", "sql": "SELECT SUM(spent) / COUNT(spent) FROM budget WHERE category = 'Food' AND event_status = 'Closed'", "difficulty": "simple" }, { "question_id": 1398, "question": "Name the event with the highest amount spent on advertisement.", "db_id": "student_club", "evidence": "Name of event refers to event_name; highest amount spent on advertisement refers to MAX(spent) where category = 'Advertisement'", "code": "import pandas as pd\n\ndef solve_query(budget_df, event_df):\n # Filter rows where category is 'Advertisement'\n advertisement_df = budget_df[budget_df['category'] == 'Advertisement']\n\n # Handle potential empty results after filtering\n if advertisement_df.empty:\n return pd.DataFrame(columns=['event_name'])\n\n # Merge with event table to get event_name\n merged_df = pd.merge(advertisement_df, event_df, left_on='link_to_event', right_on='event_id', how='inner')\n\n # Check if 'spent' column exists before sorting\n if 'spent' not in merged_df.columns:\n return pd.DataFrame(columns=['event_name'])\n\n # Sort by spent in descending order and select the top record\n top_event = merged_df.sort_values(by='spent', ascending=False).head(1)\n\n # Select only the event_name column\n result = top_event[['event_name']]\n return result\n\n# Example function call with placeholder dataframes\nbudget_data = {'budget_id': ['b1', 'b2'], 'category': ['Advertisement', 'Advertisement'], 'spent': [500.0, 800.0], 'link_to_event': ['e1', 'e2']}\nevent_data = {'event_id': ['e1', 'e2'], 'event_name': ['Event A', 'Event B']}\nbudget_df = pd.DataFrame(budget_data)\nevent_df = pd.DataFrame(event_data)\nresult = solve_query(budget_df, event_df)\nprint(result)", "sql": "SELECT T2.event_name FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T1.category = 'Advertisement' ORDER BY T1.spent DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1399, "question": "Did Maya Mclean attend the 'Women's Soccer' event?", "db_id": "student_club", "evidence": "Maya Mclean is the full name; full name refers to first_name, last_name; 'Women's Soccer' is an event_name", "code": "import pandas as pd\n# 假设所有表已作为DataFrame存在\n# 先内连接member和attendance\nmerged = pd.merge(member, attendance, left_on='member_id', right_on='link_to_member')\n# 再内连接event\nmerged = pd.merge(merged, event, left_on='link_to_event', right_on='event_id')\n# 筛选Maya Mclean和Women's Soccer事件\nfiltered = merged[(merged['first_name'] == 'Maya') & (merged['last_name'] == 'Mclean') & (merged['event_name'] == 'Women\\'s Soccer')]\n# 判断是否存在记录\nresult = 'YES' if not filtered.empty else 'NO'", "sql": "SELECT COALESCE(MAX(CASE WHEN T3.event_name = 'Women''s Soccer' THEN 'YES' END), 'NO') AS result FROM member AS T1 INNER JOIN attendance AS T2 ON T1.member_id = T2.link_to_member INNER JOIN event AS T3 ON T2.link_to_event = T3.event_id WHERE T1.first_name = 'Maya' AND T1.last_name = 'Mclean' AND T3.event_name = 'Women''s Soccer'", "difficulty": "moderate" }, { "question_id": 1400, "question": "Among all events hold by the Student_Club in 2019, find the percentage share of events related to 'Community Service'", "db_id": "student_club", "evidence": "type equals 'Community Service' in the database; count of event_id; sum of type = 'Community Service';", "code": "import pandas as pd\n\n# Filter events from 2019\nevents_2019 = event[event['event_date'].str[:4] == '2019']\n\n# Calculate the percentage of Community Service events\ncommunity_service_count = (events_2019['type'] == 'Community Service').sum()\ntotal_count = len(events_2019)\npercentage = (community_service_count / total_count) * 100\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(SUM(CASE WHEN type = 'Community Service' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(type) FROM event WHERE SUBSTR(event_date, 1, 4) = '2019'", "difficulty": "moderate" }, { "question_id": 1401, "question": "Indicate the cost of posters for 'September Speaker' event.", "db_id": "student_club", "evidence": "'Posters' is the expense description; 'September Speaker' is an event name", "code": "import pandas as pd\n\n# Load the necessary tables\nevent_df = pd.read_csv('event.csv')\nbudget_df = pd.read_csv('budget.csv')\nexpense_df = pd.read_csv('expense.csv')\n\n# Filter the event DataFrame for 'September Speaker'\nseptember_speaker_event = event_df[event_df['event_name'] == 'September Speaker']\n\n# Get the budget_id for the 'September Speaker' event\nbudget_id_for_september_speaker = budget_df[budget_df['link_to_event'] == september_speaker_event['event_id'].values[0]]['budget_id']\n\n# Filter the expense DataFrame for 'Posters' and the budget_id of 'September Speaker'\nposters_expense = expense_df[(expense_df['expense_description'] == 'Posters') & (expense_df['link_to_budget'].isin(budget_id_for_september_speaker))]\n\n# Get the cost of the posters\nresult = posters_expense['cost'].values[0] if not posters_expense.empty else None\n\nprint(result)", "sql": "SELECT T3.cost FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget WHERE T1.event_name = 'September Speaker' AND T3.expense_description = 'Posters'", "difficulty": "moderate" }, { "question_id": 1402, "question": "What is the most popular size of t-shirt ordered by the club members?", "db_id": "student_club", "evidence": "count of t_shirt_size;", "code": "import pandas as pd\nimport numpy as np\n\nresult = member.groupby('t_shirt_size').size().reset_index(name='count').sort_values('count', ascending=False).head(1)['t_shirt_size'].iloc[0]", "sql": "SELECT t_shirt_size FROM member GROUP BY t_shirt_size ORDER BY COUNT(t_shirt_size) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1403, "question": "Indicate the name of the closed event whose cost has exceeded the budget the most.", "db_id": "student_club", "evidence": "closed events refers to event_name where status = 'Closed'; exceed the budget the most refers to MIN(remaining) where remaining < 0", "code": "import pandas as pd\nmerged = pd.merge(budget[budget['remaining'] < 0], event[event['status'] == 'Closed'], left_on='link_to_event', right_on='event_id')\nresult = merged.sort_values('remaining').head(1)[['event_name']]", "sql": "SELECT T2.event_name FROM budget AS T1 INNER JOIN event AS T2 ON T2.event_id = T1.link_to_event WHERE T2.status = 'Closed' AND T1.remaining < 0 ORDER BY T1.remaining LIMIT 1", "difficulty": "moderate" }, { "question_id": 1404, "question": "Identify the type of expenses and their total value approved for 'October Meeting' event.", "db_id": "student_club", "evidence": "total value refers to SUM(cost); 'October Meeting' is an event name;", "code": "import pandas as pd\n# 合并事件和预算表,基于事件ID关联\nmerged_event_budget = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\n# 合并预算和费用表,基于预算ID关联\nmerged_all = pd.merge(merged_event_budget, expense, left_on='budget_id', right_on='link_to_budget')\n# 筛选目标事件和已批准的费用\nfiltered = merged_all[(merged_all['event_name'] == 'October Meeting') & (merged_all['approved'] == 'Yes')]\n# 按类别分组计算总费用\ngrouped = filtered.groupby('category').agg(total_value=('cost', 'sum')).reset_index()\n# 重命名列以匹配输出要求\nresult = grouped.rename(columns={'category': 'expense_type'})", "sql": "SELECT T2.category AS expense_type, SUM(T3.cost) FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget WHERE T1.event_name = 'October Meeting' AND T3.approved = 'Yes' GROUP BY T2.category", "difficulty": "moderate" }, { "question_id": 1405, "question": "Calculate the amount budgeted for 'April Speaker' event. List all the budgeted categories for said event in an ascending order based on their amount budgeted.", "db_id": "student_club", "evidence": "'April Speaker' is an event name; amount budgeted refers to SUM(amount); budget categories refers to category", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nfiltered = merged[merged['event_name'] == 'April Speaker']\ngrouped = filtered.groupby('category')['amount'].sum().reset_index()\nresult = grouped.sort_values('amount', ascending=True)", "sql": "SELECT T2.category, SUM(T2.amount) FROM event AS T1 JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'April Speaker' GROUP BY T2.category ORDER BY SUM(T2.amount) ASC", "difficulty": "moderate" }, { "question_id": 1406, "question": "Among the budgets for Food, which one has the highest budgeted amount?", "db_id": "student_club", "evidence": "category equals 'Food' in the database;", "code": "import pandas as pd\nfood_budgets = budget[budget['category'] == 'Food']\nmax_amount = food_budgets['amount'].max()\nresult = food_budgets[food_budgets['amount'] == max_amount]['budget_id']", "sql": "SELECT budget_id FROM budget WHERE category = 'Food' AND amount = ( SELECT MAX(amount) FROM budget )", "difficulty": "simple" }, { "question_id": 1407, "question": "Among the budgets for Advertising, list out top three which have the most budgeted amount?", "db_id": "student_club", "evidence": "category equals 'Advertisement' in the database;category equals 'Advertisement' in the database; amount refers to budgeted amount", "code": "import pandas as pd\nfiltered_budget = budget[budget['category'] == 'Advertisement']\nsorted_budget = filtered_budget.sort_values('amount', ascending=False)\ntop_three = sorted_budget.head(3)\nresult = top_three[['budget_id']]", "sql": "SELECT budget_id FROM budget WHERE category = 'Advertisement' ORDER BY amount DESC LIMIT 3", "difficulty": "simple" }, { "question_id": 1408, "question": "Calculate the total cost spent for Parking in the list.", "db_id": "student_club", "evidence": "expense_description equals 'Parking' in the database; sum of cost;", "code": "import pandas as pd\nresult = expense[expense['expense_description'] == 'Parking']['cost'].sum()", "sql": "SELECT SUM(cost) FROM expense WHERE expense_description = 'Parking'", "difficulty": "simple" }, { "question_id": 1409, "question": "Mention the total expense used on 8/20/2019.", "db_id": "student_club", "evidence": "expense_date equals '2019-08-20' in the database; sum of cost;", "code": "import pandas as pd\nresult = expense[expense['expense_date'] == '2019-08-20']['cost'].sum()", "sql": "SELECT SUM(cost) FROM expense WHERE expense_date = '2019-08-20'", "difficulty": "simple" }, { "question_id": 1410, "question": "List out the full name and total cost that member id \"rec4BLdZHS2Blfp4v\" incurred?", "db_id": "student_club", "evidence": "full name refers to first_name, last name", "code": "import pandas as pd\n\n# Load the necessary tables\nmember_df = pd.read_csv('member.csv')\nexpense_df = pd.read_csv('expense.csv')\n\n# Filter the expenses for the specific member\nmember_expenses = expense_df[expense_df['link_to_member'] == 'rec4BLdZHS2Blfp4v']\n\n# Calculate the total cost\ntotal_cost = member_expenses['cost'].sum()\n\n# Get the member's full name\nmember_info = member_df[member_df['member_id'] == 'rec4BLdZHS2Blfp4v']\nfirst_name = member_info['first_name'].values[0]\nlast_name = member_info['last_name'].values[0]\n\n# Create the result DataFrame\nresult = pd.DataFrame({\n 'First Name': [first_name],\n 'Last Name': [last_name],\n 'Total Cost': [total_cost]\n})\n\n# Print the result\nprint(result)", "sql": "SELECT T1.first_name, T1.last_name, SUM(T2.cost) FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T1.member_id = 'rec4BLdZHS2Blfp4v'", "difficulty": "simple" }, { "question_id": 1411, "question": "State what kind of expenses that Sacha Harrison incurred?", "db_id": "student_club", "evidence": "kind of expenses refers to expense_description; Sacha Harrison is the full name; full name refers to first_name, last_name;", "code": "import pandas as pd\n\n# Load the necessary tables\nevent = pd.read_csv('event.csv')\nmajor = pd.read_csv('major.csv')\nzip_code = pd.read_csv('zip_code.csv')\nattendance = pd.read_csv('attendance.csv')\nbudget = pd.read_csv('budget.csv')\nexpense = pd.read_csv('expense.csv')\nincome = pd.read_csv('income.csv')\nmember = pd.read_csv('member.csv')\n\n# Filter the member table to find Sacha Harrison\nsacha_harrison = member[(member['first_name'] == 'Sacha') & (member['last_name'] == 'Harrison')]\n\n# Get the link_to_member for Sacha Harrison\nsacha_link_to_member = sacha_harrison['member_id'].values[0]\n\n# Filter the expense table to find expenses made by Sacha Harrison\nsacha_expenses = expense[expense['link_to_member'] == sacha_link_to_member]\n\n# Get the kinds of expenses\nkinds_of_expenses = sacha_expenses['expense_description'].unique()\n\n# Record the final result\nresult = kinds_of_expenses\n\n# Print the final result\nprint(result)", "sql": "SELECT T2.expense_description FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T1.first_name = 'Sacha' AND T1.last_name = 'Harrison'", "difficulty": "simple" }, { "question_id": 1412, "question": "What kind of expenses incurred by members who have X-Large in size of tee shirt?", "db_id": "student_club", "evidence": "kind of expenses refers to expense_description; t_shirt_size = 'X-Large'", "code": "import pandas as pd\n\n# Read tables\nevent_df = pd.read_csv('event.csv')\nmajor_df = pd.read_csv('major.csv')\nzip_code_df = pd.read_csv('zip_code.csv')\nattendance_df = pd.read_csv('attendance.csv')\nbudget_df = pd.read_csv('budget.csv')\nexpense_df = pd.read_csv('expense.csv')\nincome_df = pd.read_csv('income.csv')\nmember_df = pd.read_csv('member.csv')\n\n# Filter members with t_shirt_size 'X-Large'\nx_large_members = member_df[member_df['t_shirt_size'] == 'X-Large']\n\n# Get unique member IDs of X-Large members\nx_large_member_ids = x_large_members['member_id'].unique()\n\n# Filter expenses by these member IDs\nexpenses_by_x_large_members = expense_df[expense_df['link_to_member'].isin(x_large_member_ids)]\n\n# Get unique expense descriptions\nunique_expense_descriptions = expenses_by_x_large_members['expense_description'].unique()\n\n# Record the final result\nresult = unique_expense_descriptions\n\n# Print the final result\nprint(result)", "sql": "SELECT T2.expense_description FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T1.t_shirt_size = 'X-Large'", "difficulty": "simple" }, { "question_id": 1413, "question": "Mention the zip code of member who incurred less than 50USD.", "db_id": "student_club", "evidence": "cost is less than 50 in the database;", "code": "import pandas as pd\nmerged = pd.merge(member, expense, left_on='member_id', right_on='link_to_member')\nfiltered = merged[merged['cost'] < 50]\nresult = filtered[['zip']]", "sql": "SELECT T1.zip FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T2.cost < 50", "difficulty": "simple" }, { "question_id": 1414, "question": "State the name of major that Phillip Cullen has joined.", "db_id": "student_club", "evidence": "name of major refers to major_name", "code": "import pandas as pd\nimport numpy as np\nresult = pd.merge(major, member, left_on='major_id', right_on='link_to_major')\nresult = result[(result['first_name'] == 'Phillip') & (result['last_name'] == 'Cullen')]\nresult = result[['major_name']]", "sql": "SELECT T1.major_name FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major WHERE T2.first_name = 'Phillip' AND T2.last_name = 'Cullen'", "difficulty": "simple" }, { "question_id": 1415, "question": "List out the position of members who joined major of Business.", "db_id": "student_club", "evidence": "'Business' is the major name", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[merged['major_name'] == 'Business']\nresult = filtered[['position']]", "sql": "SELECT T2.position FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major WHERE T1.major_name = 'Business'", "difficulty": "simple" }, { "question_id": 1416, "question": "How many members of Business have the Medium size of tee shirt?", "db_id": "student_club", "evidence": "members of Economics refers to major_name = 'Business'; t_shirt_size = 'Medium'", "code": "import pandas as pd\nmerged = pd.merge(major, member, left_on='major_id', right_on='link_to_major')\nfiltered = merged[(merged['major_name'] == 'Business') & (merged['t_shirt_size'] == 'Medium')]\nresult = len(filtered)", "sql": "SELECT COUNT(T2.member_id) FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major WHERE T1.major_name = 'Business' AND T2.t_shirt_size = 'Medium'", "difficulty": "simple" }, { "question_id": 1417, "question": "List out the type of events which have remaining budget more than 30 USD.", "db_id": "student_club", "evidence": "remaining is greater than 30 in the database;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge event and budget tables\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\n\n# Filter for remaining budget > 30\nfiltered = merged[merged['remaining'] > 30]\n\n# Select unique event types\nresult = filtered[['type']].drop_duplicates()", "sql": "SELECT T1.type FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T2.remaining > 30", "difficulty": "simple" }, { "question_id": 1418, "question": "Mention the category of events which were held at MU 215.", "db_id": "student_club", "evidence": "location equals 'MU 215' in the database;location equals 'MU 215' in the database; budget's category refers to event category", "code": "import pandas as pd\nresult = event[event['location'] == 'MU 215']['type']", "sql": "SELECT T1.type FROM event AS T1 WHERE T1.location = 'MU 215'", "difficulty": "simple" }, { "question_id": 1419, "question": "What is the category of event which was taken place in 2020-03-24T12:00:00?", "db_id": "student_club", "evidence": "event_date equals '2020-03-24T12:00:00' in the database;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge event and budget tables\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\n\n# Filter for the specific event date\nfiltered = merged[merged['event_date'] == '2020-03-24T12:00:00']\n\n# Get the category column\nresult = filtered[['category']]", "sql": "SELECT T2.category FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_date = '2020-03-24T12:00:00'", "difficulty": "simple" }, { "question_id": 1420, "question": "State the name of major that Vice President has joined.", "db_id": "student_club", "evidence": "name of major refers to major_name; 'Vice President' is position of Student Club", "code": "import pandas as pd\nresult = pd.merge(member, major, left_on='link_to_major', right_on='major_id').query(\"position == 'Vice President'\")[['major_name']].drop_duplicates()", "sql": "SELECT T1.major_name FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major WHERE T2.position = 'Vice President'", "difficulty": "simple" }, { "question_id": 1421, "question": "Calculate the percentage of members who are major Business in the list?", "db_id": "student_club", "evidence": "position equals 'Member' in the database; major_name equals 'Business' in the database; count of member_id; sum of position = 'Member' and major_name = 'Business';", "code": "import pandas as pd\n\n# Merge member and major tables\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\n\n# Filter for members with position = 'Member'\nmembers_only = merged[merged['position'] == 'Member']\n\n# Calculate percentage of Business majors\ntotal_members = len(members_only)\nbusiness_members = len(members_only[members_only['major_name'] == 'Business'])\npercentage = (business_members / total_members) * 100 if total_members > 0 else 0\n\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT CAST(SUM(CASE WHEN T2.major_name = 'Business' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(T1.member_id) FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T1.position = 'Member'", "difficulty": "moderate" }, { "question_id": 1422, "question": "State the category of events were held at MU 215.", "db_id": "student_club", "evidence": "'MU 215' is the location of event;category in budget refers to event budget category", "code": "import pandas as pd\nresult = event[event['location'] == 'MU 215'][['type']].drop_duplicates()", "sql": "SELECT DISTINCT type AS event_category FROM event WHERE location = 'MU 215'", "difficulty": "simple" }, { "question_id": 1423, "question": "How many income are received with an amount of 50?", "db_id": "student_club", "evidence": "amount equals 50 in the database;", "code": "import pandas as pd\nresult = len(income[income['amount'] == 50])", "sql": "SELECT COUNT(income_id) FROM income WHERE amount = 50", "difficulty": "simple" }, { "question_id": 1424, "question": "Among the members, how many of them have an extra large t-shirt size?", "db_id": "student_club", "evidence": "among the members refers to position = 'Member'; extra large t-shirt size refers to t_shirt_size = 'X-Large'", "code": "import pandas as pd\nresult = len(member[(member['position'] == 'Member') & (member['t_shirt_size'] == 'X-Large')])", "sql": "SELECT COUNT(member_id) FROM member WHERE position = 'Member' AND t_shirt_size = 'X-Large'", "difficulty": "simple" }, { "question_id": 1425, "question": "In the College of Agriculture and Applied Sciences, how many majors are under the department of School of Applied Sciences, Technology and Education?", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nresult = len(major[(major['department'] == 'School of Applied Sciences, Technology and Education') & (major['college'] == 'College of Agriculture and Applied Sciences')])", "sql": "SELECT COUNT(major_id) FROM major WHERE department = 'School of Applied Sciences, Technology and Education' AND college = 'College of Agriculture and Applied Sciences'", "difficulty": "simple" }, { "question_id": 1426, "question": "List the last name of members with a major in environmental engineering and include its department and college name.", "db_id": "student_club", "evidence": "'Environmental Engineering' is the major_name;", "code": "import pandas as pd\n\nresult = pd.merge(member[member['position'] == 'Member'], major[major['major_name'] == 'Environmental Engineering'], left_on='link_to_major', right_on='major_id')[['last_name', 'department', 'college']]", "sql": "SELECT T2.last_name, T1.department, T1.college FROM major AS T1 INNER JOIN member AS T2 ON T1.major_id = T2.link_to_major WHERE T2.position = 'Member' AND T1.major_name = 'Environmental Engineering'", "difficulty": "moderate" }, { "question_id": 1427, "question": "What are the budget category of the events located at MU 215 and a guest speaker type with a 0 budget spent?", "db_id": "student_club", "evidence": "budget category refers to category; events located at refers to location; type = 'Guest Speaker'; 0 budget spent refers to spent = 0; ", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nfiltered = merged[(merged['location'] == 'MU 215') & (merged['type'] == 'Guest Speaker') & (merged['spent'] == 0)]\nresult = filtered['category'].drop_duplicates()", "sql": "SELECT DISTINCT T2.category FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.location = 'MU 215' AND T2.spent = 0 AND T1.type = 'Guest Speaker'", "difficulty": "moderate" }, { "question_id": 1428, "question": "List the city and state of members enrolled under electrical and computer engineering department.", "db_id": "student_club", "evidence": "'Electrical and Computer Engineering Department' is the department; members enrolled refers to position = 'Member'", "code": "import pandas as pd\n\n# Filter members who are in 'Member' position\nmembers_filtered = member[member['position'] == 'Member']\n\n# Merge with major table to get department info\nmerged = pd.merge(members_filtered, major, left_on='link_to_major', right_on='major_id')\n\n# Filter for Electrical and Computer Engineering Department\nmerged = merged[merged['department'] == 'Electrical and Computer Engineering Department']\n\n# Merge with zip_code table to get city and state\nresult = pd.merge(merged, zip_code, left_on='zip', right_on='zip_code')[['city', 'state']]", "sql": "SELECT city, state FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major INNER JOIN zip_code AS T3 ON T3.zip_code = T1.zip WHERE department = 'Electrical and Computer Engineering Department' AND position = 'Member'", "difficulty": "moderate" }, { "question_id": 1429, "question": "What is the name of the social event that was attended by the vice president of the Student_Club located at 900 E. Washington St.?", "db_id": "student_club", "evidence": "name of social event refers to event_name where type = 'Social'; 'Vice President' is position; located at refers to location", "code": "import pandas as pd\n\n# Merge attendance with event\nmerged = pd.merge(attendance, event, left_on='link_to_event', right_on='event_id')\n\n# Merge with member\nmerged = pd.merge(merged, member, left_on='link_to_member', right_on='member_id')\n\n# Filter for Vice President, location, and Social type\nfiltered = merged[(merged['position'] == 'Vice President') & \n (merged['location'] == '900 E. Washington St.') & \n (merged['type'] == 'Social')]\n\n# Get the event name\nresult = filtered[['event_name']]", "sql": "SELECT T2.event_name FROM attendance AS T1 INNER JOIN event AS T2 ON T2.event_id = T1.link_to_event INNER JOIN member AS T3 ON T1.link_to_member = T3.member_id WHERE T3.position = 'Vice President' AND T2.location = '900 E. Washington St.' AND T2.type = 'Social'", "difficulty": "challenging" }, { "question_id": 1430, "question": "What is the last name and position of the student that bought pizza on 09/10/2019?", "db_id": "student_club", "evidence": "expense_description equals 'Pizza' in the database; expense_date equals '2019-09-10' in the database; ratio calculated by dividing 09 by 10;", "code": "import pandas as pd\nmerged = pd.merge(member, expense, left_on='member_id', right_on='link_to_member')\nfiltered = merged[(merged['expense_date'] == '2019-09-10') & (merged['expense_description'] == 'Pizza')]\nresult = filtered[['last_name', 'position']]", "sql": "SELECT T1.last_name, T1.position FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T2.expense_date = '2019-09-10' AND T2.expense_description = 'Pizza'", "difficulty": "moderate" }, { "question_id": 1431, "question": "List the last name of the members of the club that attended the women's soccer event.", "db_id": "student_club", "evidence": "members of the club refers to position = 'Member'; 'Women's Soccer' is event name;", "code": "import pandas as pd\nmerged = pd.merge(attendance, event, left_on='link_to_event', right_on='event_id')\nmerged = pd.merge(merged, member, left_on='link_to_member', right_on='member_id')\nfiltered = merged[(merged['event_name'] == \"Women's Soccer\") & (merged['position'] == 'Member')]\nresult = filtered[['last_name']]", "sql": "SELECT T3.last_name FROM attendance AS T1 INNER JOIN event AS T2 ON T2.event_id = T1.link_to_event INNER JOIN member AS T3 ON T1.link_to_member = T3.member_id WHERE T2.event_name = 'Women''s Soccer' AND T3.position = 'Member'", "difficulty": "moderate" }, { "question_id": 1432, "question": "Among the members with t-shirt size of medium, what is the percentage of the amount 50 received by the Student_Club?", "db_id": "student_club", "evidence": "t_shirt_size equals 'Medium' in the database; position equals 'Member' in the database; amount equals 50 in the database; count of amount = 50; count of member_id;income_id refers to primary key in income table; count of income_id", "code": "import pandas as pd\nmerged = pd.merge(member, income, left_on='member_id', right_on='link_to_member')\nfiltered = merged[(merged['position'] == 'Member') & (merged['t_shirt_size'] == 'Medium')]\nnum = (filtered['amount'] == 50).sum()\ndenom = len(filtered)\nresult = num * 100.0 / denom", "sql": "SELECT CAST(SUM(CASE WHEN T2.amount = 50 THEN 1.0 ELSE 0 END) AS REAL) * 100 / COUNT(T2.income_id) FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T1.position = 'Member' AND T1.t_shirt_size = 'Medium'", "difficulty": "moderate" }, { "question_id": 1433, "question": "Which countries have zip codes with post office boxes?", "db_id": "student_club", "evidence": "type equals 'PO Box' in the database;", "code": "import pandas as pd\nresult = zip_code[(zip_code['type'] == 'PO Box') & (zip_code['county'].notna())]['county'].drop_duplicates()", "sql": "SELECT DISTINCT county FROM zip_code WHERE type = 'PO Box' AND county IS NOT NULL", "difficulty": "simple" }, { "question_id": 1434, "question": "What are the zip codes that have post office boxes in the country of the country of San Juan Municipio whose state is Puerto Rico?", "db_id": "student_club", "evidence": "type equals 'PO Box' in the database;", "code": "import pandas as pd\nresult = zip_code[(zip_code['type'] == 'PO Box') & (zip_code['county'] == 'San Juan Municipio') & (zip_code['state'] == 'Puerto Rico')][['zip_code']]", "sql": "SELECT zip_code FROM zip_code WHERE type = 'PO Box' AND county = 'San Juan Municipio' AND state = 'Puerto Rico';", "difficulty": "simple" }, { "question_id": 1435, "question": "List the names of closed event as \"game\" that was closed from 3/15/2019 to 3/20/2020.", "db_id": "student_club", "evidence": "name of events refers event_name; game event that was closed refers to type = 'Game' where status = 'Closed'; event_date BETWEEN '2019-03-15' and '2020-03-20'; ", "code": "import pandas as pd\n\n# Convert event_date to datetime\nevent['event_date'] = pd.to_datetime(event['event_date'])\n\n# Filter for Game events that are Closed and within the date range\nfiltered = event[(event['type'] == 'Game') & \n (event['status'] == 'Closed') & \n (event['event_date'] >= '2019-03-15') & \n (event['event_date'] <= '2020-03-20')]\n\n# Get distinct event names\nresult = filtered[['event_name']].drop_duplicates()", "sql": "SELECT DISTINCT event_name FROM event WHERE type = 'Game' AND DATE(SUBSTR(event_date, 1, 10)) BETWEEN '2019-03-15' AND '2020-03-20' AND status = 'Closed'", "difficulty": "moderate" }, { "question_id": 1436, "question": "Please provide links to events for members who have paid more than 50 dollar.", "db_id": "student_club", "evidence": "cost is greater than 50 in the database;", "code": "import pandas as pd\nmerged = pd.merge(expense[expense['cost'] > 50], member, left_on='link_to_member', right_on='member_id')\nmerged2 = pd.merge(merged, attendance, left_on='member_id', right_on='link_to_member')\nresult = merged2['link_to_event'].drop_duplicates()", "sql": "SELECT DISTINCT T3.link_to_event FROM expense AS T1 INNER JOIN member AS T2 ON T1.link_to_member = T2.member_id INNER JOIN attendance AS T3 ON T2.member_id = T3.link_to_member WHERE T1.cost > 50", "difficulty": "simple" }, { "question_id": 1437, "question": "Which members who were approved from 1/10/2019 to 11/19/2019? Please identify the member who attended the event and the link to their event.", "db_id": "student_club", "evidence": "approved equals 'true' in the database; expense_date is between '2019-01-10' and '2019-11-19' in the database; ratio calculated by dividing 1 by 10; ratio calculated by dividing 11 by 19;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_expense = pd.read_csv('expense.csv')\ndf_member = pd.read_csv('member.csv')\ndf_attendance = pd.read_csv('attendance.csv')\n\n# Pre-processing: Standardize 'approved' column to string and lowercase to match SQL 'true'\ndf_expense['approved'] = df_expense['approved'].astype(str).str.lower()\n\n# Pre-processing: Convert date column to datetime objects for accurate comparison\ndf_expense['expense_date'] = pd.to_datetime(df_expense['expense_date'])\n\n# Filter logic: date between '2019-01-10' and '2019-11-19' AND approved is 'true'\nfiltered_expense = df_expense[\n (df_expense['approved'] == 'true') & \n (df_expense['expense_date'] >= '2019-01-10') & \n (df_expense['expense_date'] <= '2019-11-19')\n]\n\n# Merge 1: Expense with Member\nmerged_1 = pd.merge(filtered_expense, df_member, left_on='link_to_member', right_on='member_id')\n\n# Merge 2: Result with Attendance\n# Note: 'link_to_member' is in both original tables, so suffixes _x (expense) and _y (attendance) will appear\nmerged_final = pd.merge(merged_1, df_attendance, left_on='member_id', right_on='link_to_member')\n\n# Select specific columns and apply DISTINCT (drop_duplicates)\n# We take link_to_member_x which corresponds to the expense table's link_to_member\nresult = merged_final[['link_to_member_x', 'link_to_event']].drop_duplicates()\n\n# Format output as a list of lists to match SQL execution result strictly\nprint(result.values.tolist())", "sql": "SELECT DISTINCT T1.link_to_member, T3.link_to_event FROM expense AS T1 INNER JOIN member AS T2 ON T1.link_to_member = T2.member_id INNER JOIN attendance AS T3 ON T2.member_id = T3.link_to_member WHERE date(SUBSTR(T1.expense_date, 1, 10)) BETWEEN '2019-01-10' AND '2019-11-19' AND T1.approved = 'true'", "difficulty": "challenging" }, { "question_id": 1438, "question": "Please indicate the college of the person whose first name is Katy with the link to the major \"rec1N0upiVLy5esTO\".", "db_id": "student_club", "evidence": "", "code": "import pandas as pd\nresult = pd.merge(member[member['link_to_major'] == 'rec1N0upiVLy5esTO'][member['first_name'] == 'Katy'], major, left_on='link_to_major', right_on='major_id')['college']", "sql": "SELECT T2.college FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T1.link_to_major = 'rec1N0upiVLy5esTO' AND T1.first_name = 'Katy'", "difficulty": "simple" }, { "question_id": 1439, "question": "Please list the phone numbers of the members who majored in business at the College of Agriculture and Applied Sciences.", "db_id": "student_club", "evidence": "'College of Agriculture and Applied Sciences' is the college; majored in business refers to major_name = 'Business'; phone numbers refers to phone", "code": "import pandas as pd\n\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[(merged['major_name'] == 'Business') & (merged['college'] == 'College of Agriculture and Applied Sciences')]\nresult = filtered[['phone']]", "sql": "SELECT T1.phone FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T2.major_name = 'Business' AND T2.college = 'College of Agriculture and Applied Sciences'", "difficulty": "moderate" }, { "question_id": 1440, "question": "List emails of people who paid more than 20 dollars from 9/10/2019 to 11/19/2019.", "db_id": "student_club", "evidence": "cost is greater than 20 in the database; expense_date is between '2019-09-10' and '2019-11-19' in the database;", "code": "import pandas as pd\nmerged = pd.merge(member, expense, left_on='member_id', right_on='link_to_member')\nfiltered = merged[(merged['expense_date'] >= '2019-09-10') & (merged['expense_date'] <= '2019-11-19') & (merged['cost'] > 20)]\nresult = filtered[['email']].drop_duplicates()", "sql": "SELECT DISTINCT T1.email FROM member AS T1 INNER JOIN expense AS T2 ON T1.member_id = T2.link_to_member WHERE T2.expense_date BETWEEN '2019-09-10' AND '2019-11-19' AND T2.cost > 20", "difficulty": "moderate" }, { "question_id": 1441, "question": "How many members have education major in the College of Education & Human Services?", "db_id": "student_club", "evidence": "'education' is the major name; 'Member' is a position of club;", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[(merged['position'] == 'Member') & (merged['major_name'].str.contains('Education', case=False)) & (merged['college'] == 'College of Education & Human Services')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.member_id) FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T1.position = 'Member' AND T2.major_name LIKE '%Education%' AND T2.college = 'College of Education & Human Services';", "difficulty": "moderate" }, { "question_id": 1442, "question": "What is the percentage of the events that went over budget?", "db_id": "student_club", "evidence": "went over budget refers to remaining < 0; percentage = DIVIDE(SUM(remaining < 0), COUNT(event_id)) * 100went over budget refers to remaining < 0; percentage = DIVIDE(SUM(remaining < 0), COUNT(budget_id)) * 100", "code": "import pandas as pd\n# 计算每个事件是否超预算\nbudget_over = budget.groupby('link_to_event')['remaining'].apply(lambda x: (x < 0).any()).reset_index(name='over_budget')\n# 合并事件表与超预算标记\nmerged = pd.merge(event, budget_over, left_on='event_id', right_on='link_to_event', how='left')\n# 填充缺失值为False\nmerged['over_budget'] = merged['over_budget'].fillna(False)\n# 计算超预算事件数量和总数\nover_count = merged['over_budget'].sum()\ntotal_events = len(event)\n# 计算百分比\nresult = (over_count / total_events) * 100", "sql": "SELECT CAST(SUM(CASE WHEN EXISTS (SELECT 1 FROM budget WHERE link_to_event = e.event_id AND remaining < 0) THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(e.event_id) FROM event e", "difficulty": "simple" }, { "question_id": 1443, "question": "Give the event ID, location, and status of events conducted from November 2019 to March 2020.", "db_id": "student_club", "evidence": "event_date is between '2019-11-01' and '2020-03-31' in the database;", "code": "import pandas as pd\nevent['event_date'] = pd.to_datetime(event['event_date'])\nfiltered = event[(event['event_date'] >= '2019-11-01') & (event['event_date'] <= '2020-03-31')]\nresult = filtered[['event_id', 'location', 'status']]", "sql": "SELECT event_id, location, status FROM event WHERE date(SUBSTR(event_date, 1, 10)) BETWEEN '2019-11-01' AND '2020-03-31'", "difficulty": "simple" }, { "question_id": 1444, "question": "List the expenses that spend more than fifty dollars on average.", "db_id": "student_club", "evidence": "expense refers to expense_description; spend more than fifty dollars on average refers to DIVIDE( SUM(cost), COUNT(expense_id) ) > 50", "code": "import pandas as pd\n\nresult = expense.groupby('expense_description')['cost'].mean()\nresult = result[result > 50].reset_index()[['expense_description']]", "sql": "SELECT expense_description FROM expense GROUP BY expense_description HAVING AVG(cost) > 50", "difficulty": "simple" }, { "question_id": 1445, "question": "Find the full name of members whose t-shirt size is extra large.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name; t_shirt_size = 'X-Large'", "code": "import pandas as pd\n\ndef solve_query(member_df):\n # Check if required columns exist\n required_columns = ['first_name', 'last_name', 't_shirt_size']\n for col in required_columns:\n if col not in member_df.columns:\n raise ValueError(f\"Missing required column: {col}\")\n\n # Filter members with t-shirt size 'X-Large'\n result_df = member_df[member_df['t_shirt_size'] == 'X-Large'][['first_name', 'last_name']]\n\n # Handle possible empty results\n if result_df.empty:\n return pd.DataFrame(columns=['first_name', 'last_name'])\n\n return result_df\n\n# Example function call\n# Assuming 'member.csv' exists and has been loaded into a DataFrame called member_df\ntry:\n member_df = pd.read_csv('member.csv')\n result = solve_query(member_df)\n print(result)\nexcept Exception as e:\n print(f\"Error: {e}\")", "sql": "SELECT first_name, last_name FROM member WHERE t_shirt_size = 'X-Large';", "difficulty": "simple" }, { "question_id": 1446, "question": "Calculate the percentage of zip codes that are PO boxes.", "db_id": "student_club", "evidence": "type equals 'PO Box' in the database; count of zip_code; sum of type = 'PO Box';", "code": "import pandas as pd\nimport numpy as np\n\nresult = (zip_code['type'] == 'PO Box').sum() * 100 / len(zip_code)", "sql": "SELECT CAST(SUM(CASE WHEN type = 'PO Box' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(zip_code) FROM zip_code", "difficulty": "simple" }, { "question_id": 1447, "question": "List the name and location of events that underspend its budget.", "db_id": "student_club", "evidence": "name of event refers to event_name; underspend its budget refers to remaining > 0", "code": "import pandas as pd\nmerged = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\nfiltered = merged[merged['remaining'] > 0]\nresult = filtered[['event_name', 'location']].drop_duplicates()", "sql": "SELECT DISTINCT T1.event_name, T1.location FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T2.remaining > 0", "difficulty": "simple" }, { "question_id": 1448, "question": "Find the name and date of events with expenses for pizza that were more than fifty dollars but less than a hundred dollars.", "db_id": "student_club", "evidence": "name of event refers to event_name; date of event refers to event_date; expenses for pizza refers to expense_description = 'Pizza' where cost > 50 and cost < 100", "code": "import pandas as pd\n\n# Merge expense with budget to get link_to_event\nexpense_budget = pd.merge(expense, budget, left_on='link_to_budget', right_on='budget_id')\n\n# Filter for Pizza expenses between 50 and 100 dollars\npizza_expenses = expense_budget[(expense_budget['expense_description'] == 'Pizza') & (expense_budget['cost'] > 50) & (expense_budget['cost'] < 100)]\n\n# Merge with event table to get event name and date\nresult = pd.merge(pizza_expenses, event, left_on='link_to_event', right_on='event_id')[['event_name', 'event_date']].drop_duplicates()", "sql": "SELECT T1.event_name, T1.event_date FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget WHERE T3.expense_description = 'Pizza' AND T3.cost > 50 AND T3.cost < 100", "difficulty": "challenging" }, { "question_id": 1449, "question": "What is the name and major of members who had to spend more than a hundred dollars on an expense?", "db_id": "student_club", "evidence": "full name refers to first_name, last_name; major of members refers to major_name; spend more than a hundred dollars on an expense refers to cost > 100", "code": "import pandas as pd\nmerged1 = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nmerged2 = pd.merge(merged1, expense, left_on='member_id', right_on='link_to_member')\nfiltered = merged2[merged2['cost'] > 100]\nresult = filtered[['first_name', 'last_name', 'major_name']].drop_duplicates()", "sql": "SELECT DISTINCT T1.first_name, T1.last_name, T2.major_name FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major INNER JOIN expense AS T3 ON T1.member_id = T3.link_to_member WHERE T3.cost > 100", "difficulty": "moderate" }, { "question_id": 1450, "question": "In the events with more than forty incomes, list the city and country in which the event is happening.", "db_id": "student_club", "evidence": "income is greater than 40 in the database;", "code": "import pandas as pd\nimport numpy as np\n\n# Join income with member to get zip codes\nmerged = pd.merge(income, member, left_on='link_to_member', right_on='member_id')\n\n# Join with zip_code table to get city and county\nmerged = pd.merge(merged, zip_code, left_on='zip', right_on='zip_code')\n\n# Filter for income amounts greater than 40\nfiltered = merged[merged['amount'] > 40]\n\n# Select distinct city and county\nresult = filtered[['city', 'county']].drop_duplicates()", "sql": "SELECT DISTINCT z.city, z.county FROM attendance a JOIN income i ON i.link_to_member = a.link_to_member JOIN member m ON m.member_id = a.link_to_member JOIN zip_code z ON z.zip_code = m.zip GROUP BY a.link_to_event, z.city, z.county HAVING COUNT(i.income_id) > 40;", "difficulty": "simple" }, { "question_id": 1451, "question": "Among the members who incurred expenses in more than one event, who paid the most amount?", "db_id": "student_club", "evidence": "count of event_id;", "code": "import pandas as pd\n\n# Merge expense with member\nmerged = pd.merge(expense, member, left_on='link_to_member', right_on='member_id')\n\n# Merge with budget\nmerged = pd.merge(merged, budget, left_on='link_to_budget', right_on='budget_id')\n\n# Merge with event\nmerged = pd.merge(merged, event, left_on='link_to_event', right_on='event_id')\n\n# Group by member_id and calculate number of distinct events and total cost\ngrouped = merged.groupby('member_id').agg({\n 'event_id': 'nunique',\n 'cost': 'sum'\n}).reset_index()\n\n# Filter members who incurred expenses in more than one event\nfiltered = grouped[grouped['event_id'] > 1]\n\n# Sort by total cost in descending order and get the top member\nresult = filtered.sort_values('cost', ascending=False).head(1)['member_id'].iloc[0]", "sql": "SELECT T2.member_id FROM expense AS T1 INNER JOIN member AS T2 ON T1.link_to_member = T2.member_id INNER JOIN budget AS T3 ON T1.link_to_budget = T3.budget_id INNER JOIN event AS T4 ON T3.link_to_event = T4.event_id GROUP BY T2.member_id HAVING COUNT(DISTINCT T4.event_id) > 1 ORDER BY SUM(T1.cost) DESC LIMIT 1", "difficulty": "challenging" }, { "question_id": 1452, "question": "What is the average amount paid by students in a position other than a member?", "db_id": "student_club", "evidence": "position other than a member refers to position ! = 'Member'; average amount paid = DIVIDE( SUM(cost), COUNT(event_id))average amount paid = AVG(T1.cost)", "code": "import pandas as pd\nmerged = pd.merge(expense, member, left_on='link_to_member', right_on='member_id')\nfiltered = merged[merged['position'] != 'Member']\nresult = filtered['cost'].mean()", "sql": "SELECT AVG(T1.cost) FROM expense AS T1 INNER JOIN member AS T2 ON T1.link_to_member = T2.member_id WHERE T2.position != 'Member';", "difficulty": "moderate" }, { "question_id": 1453, "question": "List the name of events with less than average parking cost.", "db_id": "student_club", "evidence": "name of events refers to event_name; less than average parking cost refers to cost < DIVIDE(SUM(cost), COUNT(event_id)) where category = 'Parking'", "code": "import pandas as pd\n\n# Merge event with budget\nmerged1 = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')\n\n# Merge with expense\nmerged2 = pd.merge(merged1, expense, left_on='budget_id', right_on='link_to_budget')\n\n# Filter for Parking category\nparking_data = merged2[merged2['category'] == 'Parking']\n\n# Calculate average parking cost\navg_parking_cost = parking_data['cost'].mean()\n\n# Filter events with parking cost less than average\nbelow_avg = parking_data[parking_data['cost'] < avg_parking_cost]\n\n# Get unique event names\nresult = below_avg[['event_name']].drop_duplicates()", "sql": "SELECT T1.event_name FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget WHERE T2.category = 'Parking' AND T3.cost < (SELECT AVG(T3_sub.cost) FROM expense AS T3_sub INNER JOIN budget AS T2_sub ON T3_sub.link_to_budget = T2_sub.budget_id WHERE T2_sub.category = 'Parking')", "difficulty": "moderate" }, { "question_id": 1454, "question": "What is the percentage of the cost for the meeting events?", "db_id": "student_club", "evidence": "meeting events refers to type = 'Meeting'; percentage = DIVIDE( SUM(cost), COUNT(event_id)) * 100", "code": "import pandas as pd\nmerged_event_budget = pd.merge(event, budget, left_on='event_id', right_on='link_to_event', how='inner')\nmerged_all = pd.merge(merged_event_budget, expense, left_on='budget_id', right_on='link_to_budget', how='inner')\nsum_cost_meeting = merged_all[merged_all['type'] == 'Meeting']['cost'].sum()\npercentage = (sum_cost_meeting * 100) / merged_all['event_id'].nunique()\nresult = pd.DataFrame({'percentage': [percentage]})", "sql": "SELECT (SUM(CASE WHEN T1.type = 'Meeting' THEN T3.cost ELSE 0 END) * 100) / COUNT(DISTINCT T1.event_id) FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event INNER JOIN expense AS T3 ON T2.budget_id = T3.link_to_budget", "difficulty": "moderate" }, { "question_id": 1455, "question": "Which budget allowed the most money for water, chips, and cookies?", "db_id": "student_club", "evidence": "budget allowed refers to expense_description; expense_description = 'Water, chips, cookies'; most money refers to MAX(cost)", "code": "import pandas as pd\n\n# Filter expense for 'Water, chips, cookies'\nfiltered_expense = expense[expense['expense_description'] == 'Water, chips, cookies']\n\n# Merge with budget to get budget_id\nmerged = pd.merge(filtered_expense, budget, left_on='link_to_budget', right_on='budget_id')\n\n# Sort by cost in descending order and get the budget_id with highest cost\nresult = merged.sort_values('cost', ascending=False).head(1)[['budget_id']]", "sql": "SELECT T2.budget_id FROM expense AS T1 INNER JOIN budget AS T2 ON T1.link_to_budget = T2.budget_id WHERE T1.expense_description = 'Water, chips, cookies' ORDER BY T1.cost DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1456, "question": "List the full name of the top five members who spend the most money in the descending order of spending.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name; spend the most money refers to MAX(expense.cost)spend the most money refers to SUM(expense.cost)", "code": "import pandas as pd\nmerged = pd.merge(expense, member, left_on='link_to_member', right_on='member_id')\ngrouped = merged.groupby(['member_id', 'first_name', 'last_name'], as_index=False)['cost'].sum()\nsorted_df = grouped.sort_values('cost', ascending=False)\nresult = sorted_df.head(5)[['first_name', 'last_name']]", "sql": "SELECT T3.first_name, T3.last_name FROM expense AS T1 INNER JOIN member AS T3 ON T1.link_to_member = T3.member_id GROUP BY T3.member_id, T3.first_name, T3.last_name ORDER BY SUM(T1.cost) DESC LIMIT 5", "difficulty": "moderate" }, { "question_id": 1457, "question": "Give the full name and contact number of members who had to spend more than average on each expense.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name; contact number refers to phone; had spent more than average on each expense refers to cost > AVG(cost)", "code": "import pandas as pd\n\n# Calculate average expense cost\navg_cost = expense['cost'].mean()\n\n# Filter expenses greater than average\nabove_avg_expenses = expense[expense['cost'] > avg_cost]\n\n# Merge with member to get full name and phone\nresult = pd.merge(above_avg_expenses, member, left_on='link_to_member', right_on='member_id')[['first_name', 'last_name', 'phone']].drop_duplicates()", "sql": "SELECT DISTINCT T3.first_name, T3.last_name, T3.phone FROM expense AS T1 INNER JOIN budget AS T2 ON T1.link_to_budget = T2.budget_id INNER JOIN member AS T3 ON T3.member_id = T1.link_to_member WHERE T1.cost > ( SELECT AVG(T1.cost) FROM expense AS T1 INNER JOIN budget AS T2 ON T1.link_to_budget = T2.budget_id INNER JOIN member AS T3 ON T3.member_id = T1.link_to_member )", "difficulty": "challenging" }, { "question_id": 1458, "question": "Calculate the difference in the percentage of members in New Jersey and Vermont.", "db_id": "student_club", "evidence": "state equals 'New Jersey' in the database; position equals 'Member' in the database; state equals 'Vermont' in the database; count of position = 'Member'; sum of state = 'New Jersey'; sum of state = 'Vermont';", "code": "import pandas as pd\nimport numpy as np\nmerged = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')\nmembers = merged[merged['position'] == 'Member']\nnj = members['state'].eq('New Jersey').sum()\nvt = members['state'].eq('Vermont').sum()\ntotal = len(members)\ndiff = ((nj - vt) / total * 100) if total else np.nan\nresult = pd.DataFrame({'diff': [diff]})", "sql": "SELECT CAST((SUM(CASE WHEN T2.state = 'New Jersey' AND T1.position = 'Member' THEN 1 ELSE 0 END) - SUM(CASE WHEN T2.state = 'Vermont' AND T1.position = 'Member' THEN 1 ELSE 0 END)) AS REAL) * 100 / NULLIF(SUM(CASE WHEN T1.position = 'Member' THEN 1 ELSE 0 END), 0) AS diff FROM member AS T1 INNER JOIN zip_code AS T2 ON T2.zip_code = T1.zip", "difficulty": "moderate" }, { "question_id": 1459, "question": "What is the major of Garrett Gerke and which department does it belong to?", "db_id": "student_club", "evidence": "major refers to major name;", "code": "import pandas as pd\nimport numpy as np\n\n# Merge member and major tables\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\n\n# Filter for Garrett Gerke\nfiltered = merged[(merged['first_name'] == 'Garrett') & (merged['last_name'] == 'Gerke')]\n\n# Select major_name and department columns\nresult = filtered[['major_name', 'department']]", "sql": "SELECT T2.major_name, T2.department FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T1.first_name = 'Garrett' AND T1.last_name = 'Gerke'", "difficulty": "simple" }, { "question_id": 1460, "question": "Write the full name of the member who spent money for water, veggie tray and supplies and include the cost of it.", "db_id": "student_club", "evidence": "full name refers to first_name, last name; spent money for refers expense description; expense_description = 'Water, Veggie tray, supplies'", "code": "import pandas as pd\n\n# Merge expense with member table\nmerged = pd.merge(expense, member, left_on='link_to_member', right_on='member_id')\n\n# Filter for the specific expense description\nfiltered = merged[merged['expense_description'] == 'Water, Veggie tray, supplies']\n\n# Select only the required columns\nresult = filtered[['first_name', 'last_name', 'cost']]", "sql": "SELECT T2.first_name, T2.last_name, T1.cost FROM expense AS T1 INNER JOIN member AS T2 ON T1.link_to_member = T2.member_id WHERE T1.expense_description = 'Water, Veggie tray, supplies'", "difficulty": "challenging" }, { "question_id": 1461, "question": "List the last names of students under the Elementary Education major and include their phone numbers.", "db_id": "student_club", "evidence": "'Elementary Education' is the major name; phone numbers refers to phone", "code": "import pandas as pd\nmerged = pd.merge(member, major, left_on='link_to_major', right_on='major_id')\nfiltered = merged[merged['major_name'] == 'Elementary Education']\nresult = filtered[['last_name', 'phone']]", "sql": "SELECT T1.last_name, T1.phone FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T2.major_name = 'Elementary Education'", "difficulty": "simple" }, { "question_id": 1462, "question": "What category was budgeted for the 'January Speaker' event and how much was the amount budgeted for that category?", "db_id": "student_club", "evidence": "amount budgeted refers to amount, 'January Speaker' is the event name;", "code": "import pandas as pd\nimport numpy as np\n\nmerged = pd.merge(event[event['event_name'] == 'January Speaker'], budget, left_on='event_id', right_on='link_to_event')\nresult = merged[['category', 'amount']]", "sql": "SELECT T2.category, T2.amount FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T1.event_name = 'January Speaker'", "difficulty": "simple" }, { "question_id": 1463, "question": "List the event names which were budgeted for the food.", "db_id": "student_club", "evidence": "category equals 'Food' in the database;", "code": "import pandas as pd \nresult = pd.merge(event, budget, left_on='event_id', right_on='link_to_event')[budget['category'] == 'Food'][['event_name']]", "sql": "SELECT T1.event_name FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event WHERE T2.category = 'Food';", "difficulty": "simple" }, { "question_id": 1464, "question": "Write the full names of students who received funds on the date of 9/9/2019 and include the amount received.", "db_id": "student_club", "evidence": "full name refers to first_name, last_name, amount of funds received refers to amount, received funds on date refers to date_received", "code": "import pandas as pd\\n\\nmember_df = pd.read_csv('student_club/member.csv')\\nincome_df = pd.read_csv('student_club/income.csv')\\n\\n# 进行内连接\\nmerged_df = pd.merge(member_df, income_df, left_on='member_id', right_on='link_to_member')\\n\\n# 过滤出日期为'2019-09-09'的记录\\nfiltered_df = merged_df[merged_df['date_received'] == '2019-09-09']\\n\\n# 提取所需列\\nresult = filtered_df[['first_name', 'last_name', 'amount']]\\n\\n# 打印结果\\nprint(result)", "sql": "SELECT T1.first_name, T1.last_name, T2.amount FROM member AS T1 INNER JOIN income AS T2 ON T1.member_id = T2.link_to_member WHERE T2.date_received = '2019-09-09'", "difficulty": "challenging" }, { "question_id": 1465, "question": "Which budget category does the expense 'Posters' fall to?", "db_id": "student_club", "evidence": "'Posters' refers to expense description", "code": "import pandas as pd\nresult = pd.merge(expense[expense['expense_description'] == 'Posters'], budget, left_on='link_to_budget', right_on='budget_id')[['category']].drop_duplicates()", "sql": "SELECT DISTINCT T2.category FROM expense AS T1 INNER JOIN budget AS T2 ON T1.link_to_budget = T2.budget_id WHERE T1.expense_description = 'Posters'", "difficulty": "simple" }, { "question_id": 1466, "question": "Write the full name of the club member with the position of 'Secretary' and list which college the club member belongs to.", "db_id": "student_club", "evidence": "full name refers to first_name, last name", "code": "import pandas as pd\nresult = pd.merge(member[member['position'] == 'Secretary'], major, left_on='link_to_major', right_on='major_id')[['first_name', 'last_name', 'college']]", "sql": "SELECT T1.first_name, T1.last_name, T2.college FROM member AS T1 INNER JOIN major AS T2 ON T2.major_id = T1.link_to_major WHERE T1.position = 'Secretary'", "difficulty": "simple" }, { "question_id": 1467, "question": "Calculate the total amount spent on speaker gifts and list the name of the event they were spent on.", "db_id": "student_club", "evidence": "category equals 'Speaker Gifts' in the database; sum of spent;", "code": "import pandas as pd\nfiltered_budget = budget[budget['category'] == 'Speaker Gifts']\nmerged = pd.merge(filtered_budget, event, left_on='link_to_event', right_on='event_id')\nresult = merged.groupby('event_name')['spent'].sum().reset_index()\nresult.columns = ['event_name', 'total_spent']", "sql": "SELECT SUM(T1.spent), T2.event_name FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T1.category = 'Speaker Gifts' GROUP BY T2.event_name", "difficulty": "simple" }, { "question_id": 1468, "question": "Where is the hometown of Garrett Gerke?", "db_id": "student_club", "evidence": "hometown refers to city", "code": "import pandas as pd\nimport numpy as np\n\n# Assume DataFrames are already loaded\n# member, zip_code\n\n# Filter member table for Garrett Gerke\ngarrett = member[(member['first_name'] == 'Garrett') & (member['last_name'] == 'Gerke')]\n\n# Merge with zip_code table to get city\nresult = pd.merge(garrett, zip_code, left_on='zip', right_on='zip_code')[['city']]\n\n# If multiple results, get unique cities\nresult = result['city'].unique() if len(result) > 0 else pd.DataFrame()", "sql": "SELECT T2.city FROM member AS T1 INNER JOIN zip_code AS T2 ON T2.zip_code = T1.zip WHERE T1.first_name = 'Garrett' AND T1.last_name = 'Gerke'", "difficulty": "simple" }, { "question_id": 1469, "question": "Which student has the hometown of Lincolnton, North Carolina with the zip code of 28092? List their full name and position.", "db_id": "student_club", "evidence": "city equals 'Lincolnton' in the database; state equals 'North Carolina' in the database;", "code": "import pandas as pd\n\n# Merge member and zip_code tables\nmerged = pd.merge(member, zip_code, left_on='zip', right_on='zip_code')\n\n# Filter for Lincolnton, North Carolina with zip code 28092\nfiltered = merged[(merged['city'] == 'Lincolnton') & (merged['state'] == 'North Carolina') & (merged['zip_code'] == 28092)]\n\n# Select the required columns\nresult = filtered[['first_name', 'last_name', 'position']]", "sql": "SELECT T1.first_name, T1.last_name, T1.position FROM member AS T1 INNER JOIN zip_code AS T2 ON T2.zip_code = T1.zip WHERE T2.city = 'Lincolnton' AND T2.state = 'North Carolina' AND T2.zip_code = 28092", "difficulty": "moderate" }, { "question_id": 1470, "question": "How many gas stations in CZE has Premium gas?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\nresult = len(gasstations[(gasstations['Country'] == 'CZE') & (gasstations['Segment'] == 'Premium')])", "sql": "SELECT COUNT(GasStationID) FROM gasstations WHERE Country = 'CZE' AND Segment = 'Premium'", "difficulty": "simple" }, { "question_id": 1471, "question": "What is the ratio of customers who pay in EUR against customers who pay in CZK?", "db_id": "debit_card_specializing", "evidence": "Currency equals 'EUR' in the database; Currency equals 'CZK' in the database; count of Currency = 'EUR'; count of Currency = 'CZK';", "code": "import pandas as pd\nresult = (customers['Currency'] == 'EUR').sum() / (customers['Currency'] == 'CZK').sum()", "sql": "SELECT CAST(SUM(IIF(Currency = 'EUR', 1, 0)) AS FLOAT) / SUM(IIF(Currency = 'CZK', 1, 0)) AS ratio FROM customers", "difficulty": "simple" }, { "question_id": 1472, "question": "In 2012, who had the least consumption in LAM?", "db_id": "debit_card_specializing", "evidence": "Year 2012 can be presented as Between 201201 And 201212; The first 4 strings of the Date values in the yearmonth table can represent year.", "code": "import pandas as pd\\n\\ndf_customers = pd.read_csv('debit_card_specializing/customers.csv')\\ndf_yearmonth = pd.read_csv('debit_card_specializing/yearmonth.csv')\\n\\n# 合并两个表\\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\\n\\n# 确保 Date 列是字符串类型\\nmerged_df['Date'] = merged_df['Date'].astype(str)\\n\\n# 过滤出2012年的记录\\nfiltered_df = merged_df[merged_df['Date'].str.startswith('2012')]\\n\\n# 过滤出LAM段的客户\\nlam_segment_df = filtered_df[filtered_df['Segment'] == 'LAM']\\n\\n# 按客户ID分组并计算总消费\\ngrouped_df = lam_segment_df.groupby('CustomerID')['Consumption'].sum().reset_index()\\n\\n# 找到消费最少的客户\\nleast_consumption_customer = grouped_df.sort_values(by='Consumption').head(1)\\n\\nprint(least_consumption_customer)", "sql": "SELECT T1.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Segment = 'LAM' AND SUBSTR(T2.Date, 1, 4) = '2012' GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) ASC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1473, "question": "What was the average monthly consumption of customers in SME for the year 2013?", "db_id": "debit_card_specializing", "evidence": "average of Consumption;", "code": "import pandas as pd\nmerged_df = pd.merge(customers, yearmonth, on='CustomerID', how='inner')\nmerged_df['Date'] = merged_df['Date'].astype(str)\nfiltered_df = merged_df[(merged_df['Segment'] == 'SME') & (merged_df['Date'].str.startswith('2013'))]\nresult = filtered_df['Consumption'].mean()", "sql": "SELECT AVG(T2.Consumption) FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE SUBSTR(T2.Date, 1, 4) = '2013' AND T1.Segment = 'SME'", "difficulty": "moderate" }, { "question_id": 1474, "question": "Which customers, paying in CZK, consumed the most gas in 2011?", "db_id": "debit_card_specializing", "evidence": "Year 2011 can be presented as Between 201101 And 201112, which means between January and December in 2011", "code": "import pandas as pd\\n\\ndf_customers = pd.read_csv('debit_card_specializing/customers.csv')\\ndf_yearmonth = pd.read_csv('debit_card_specializing/yearmonth.csv')\\n\\n# 合并两个表\\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\\n\\n# 确保 Date 列是字符串类型\\nmerged_df['Date'] = merged_df['Date'].astype(str)\\n\\n# 过滤出2011年的记录\\nfiltered_df = merged_df[merged_df['Date'].str.startswith('2011')]\\n\\n# 过滤出使用CZK货币的客户\\nczk_customers_df = filtered_df[filtered_df['Currency'] == 'CZK']\\n\\n# 按客户ID分组并计算总消费\\ngrouped_df = czk_customers_df.groupby('CustomerID')['Consumption'].sum().reset_index()\\n\\n# 找到消费最多的客户\\nmost_consumption_customer = grouped_df.sort_values(by='Consumption', ascending=False).head(1)\\n\\nprint(most_consumption_customer)", "sql": "SELECT T1.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Currency = 'CZK' AND T2.Date BETWEEN 201101 AND 201112 GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1475, "question": "How many customers in KAM had a consumption of less than 30,000 for the year 2012?", "db_id": "debit_card_specializing", "evidence": "Year 2012 can be presented as Between 201201 And 201212, which means between January and December in 2012", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge tables on CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Filter for 'KAM' segment\n# SQL: WHERE T1.Segment = 'KAM'\nmerged_df = merged_df[merged_df['Segment'] == 'KAM']\n\n# Filter for year 2012\n# SQL: AND SUBSTRING(T2.Date, 1, 4) = '2012'\n# Convert Date to string to handle 'YYYYMM' text format safely\nmerged_df['Date'] = merged_df['Date'].astype(str)\nfiltered_df = merged_df[merged_df['Date'].str.startswith('2012')]\n\n# Group by CustomerID and calculate total consumption\n# SQL: GROUP BY T2.CustomerID\ngrouped_df = filtered_df.groupby('CustomerID')['Consumption'].sum().reset_index()\n\n# Filter groups having sum(Consumption) < 30000\n# SQL: HAVING SUM(T2.Consumption) < 30000\ncustomers_with_low_consumption = grouped_df[grouped_df['Consumption'] < 30000]\n\n# Count the number of customers\n# SQL: SELECT COUNT(*)\nresult = len(customers_with_low_consumption)\n\nprint(result)", "sql": "SELECT COUNT(*) FROM ( SELECT T2.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Segment = 'KAM' AND SUBSTRING(T2.Date, 1, 4) = '2012' GROUP BY T2.CustomerID HAVING SUM(T2.Consumption) < 30000 ) AS t1", "difficulty": "moderate" }, { "question_id": 1476, "question": "What was the difference in gas consumption between CZK-paying customers and EUR-paying customers in 2012?", "db_id": "debit_card_specializing", "evidence": "Year 2012 can be presented as Between 201201 And 201212; The first 4 strings of the Date values in the yearmonth table can represent year; Difference in Consumption = CZK customers consumption in 2012 - EUR customers consumption in 2012", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge tables on CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Filter for year 2012\n# SQL: WHERE SUBSTR(T2.Date, 1, 4) = '2012'\nmerged_df['Date'] = merged_df['Date'].astype(str)\nfiltered_df = merged_df[merged_df['Date'].str.startswith('2012')]\n\n# Calculate sum for CZK\n# SQL: SUM(IIF(T1.Currency = 'CZK', T2.Consumption, 0))\nczk_sum = filtered_df[filtered_df['Currency'] == 'CZK']['Consumption'].sum()\n\n# Calculate sum for EUR\n# SQL: SUM(IIF(T1.Currency = 'EUR', T2.Consumption, 0))\neur_sum = filtered_df[filtered_df['Currency'] == 'EUR']['Consumption'].sum()\n\n# Calculate the difference\n# SQL: ... - ...\nresult = czk_sum - eur_sum\n\nprint(result)", "sql": "SELECT SUM(IIF(T1.Currency = 'CZK', T2.Consumption, 0)) - SUM(IIF(T1.Currency = 'EUR', T2.Consumption, 0)) FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE SUBSTR(T2.Date, 1, 4) = '2012'", "difficulty": "challenging" }, { "question_id": 1477, "question": "Which year recorded the most gas use paid in EUR?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge tables on CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Filter for EUR currency\n# SQL: WHERE T1.Currency = 'EUR'\neur_df = merged_df[merged_df['Currency'] == 'EUR'].copy()\n\n# Extract Year from Date (assuming format YYYYMM or similar string)\n# SQL: SUBSTRING(T2.Date, 1, 4)\neur_df['Date'] = eur_df['Date'].astype(str)\neur_df['Year'] = eur_df['Date'].str.slice(0, 4)\n\n# Group by Year and sum Consumption\n# SQL: GROUP BY SUBSTRING(T2.Date, 1, 4)\ngrouped = eur_df.groupby('Year')['Consumption'].sum().reset_index()\n\n# Sort by Consumption descending and take the top 1\n# SQL: ORDER BY SUM(T2.Consumption) DESC LIMIT 1\ntop_record = grouped.sort_values(by='Consumption', ascending=False).head(1)\n\n# Get the year value\nresult = top_record['Year'].values[0]\n\nprint(result)", "sql": "SELECT SUBSTRING(T2.Date, 1, 4) FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Currency = 'EUR' GROUP BY SUBSTRING(T2.Date, 1, 4) ORDER BY SUM(T2.Consumption) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1478, "question": "Which segment had the least consumption?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge tables on CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Group by Segment and sum Consumption\n# SQL: GROUP BY T1.Segment\ngrouped_df = merged_df.groupby('Segment')['Consumption'].sum().reset_index()\n\n# Sort by Consumption in ascending order and take the top 1\n# SQL: ORDER BY SUM(T2.Consumption) ASC LIMIT 1\nleast_consumption_segment = grouped_df.sort_values(by='Consumption', ascending=True).head(1)\n\n# Extract the segment name\nresult = least_consumption_segment['Segment'].values[0]\n\nprint(result)", "sql": "SELECT T1.Segment FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID GROUP BY T1.Segment ORDER BY SUM(T2.Consumption) ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1479, "question": "Which year recorded the most consumption of gas paid in CZK?", "db_id": "debit_card_specializing", "evidence": "The first 4 strings of the Date values in the yearmonth table can represent year.", "code": "import pandas as pd\\n\\n# 示例数据构造(如果实际没有这些变量,请替换为真实数据源)\\ncustomers = pd.DataFrame({\\n 'CustomerID': [1, 2],\\n 'Segment': ['SME', 'LAM'],\\n 'Currency': ['CZK', 'EUR']\\n})\\n\\nyearmonth = pd.DataFrame({\\n 'CustomerID': [1, 1, 2],\\n 'Date': [201301, 201401, 201302],\\n 'Consumption': [100.5, 200.0, 150.0]\\n})\\n\\ntransactions_1k = pd.DataFrame({\\n 'TransactionID': [1, 2, 3],\\n 'Date': ['2013-01-15', '2014-01-20', '2013-02-10'],\\n 'CustomerID': [1, 1, 2],\\n 'ProductID': [101, 102, 101]\\n})\\n\\nproducts = pd.DataFrame({\\n 'ProductID': [101, 102],\\n 'Description': ['gasoline', 'diesel']\\n})\\n\\n# 步骤1: 筛选使用 CZK 的客户\\nczk_customers = customers[customers['Currency'] == 'CZK'][['CustomerID']]\\n\\n# 步骤2: 筛选产品描述包含 \"gas\" 的记录\\ngas_products = products[products['Description'].str.contains('gas', case=False, na=False)][['ProductID']]\\n\\n# 步骤3: 合并 transactions_1k 与 gas_products 获取 gas 相关交易\\ngas_transactions = pd.merge(transactions_1k, gas_products, on='ProductID')\\n\\n# 步骤4: 构造 yearmonth 的年月字段用于匹配 transactions_1k 的日期\\nyearmonth['YearMonth'] = yearmonth['Date'].astype(str).str[:6] # 例如 201301\\ngas_transactions['YearMonth'] = pd.to_datetime(gas_transactions['Date']).dt.strftime('%Y%m') # 格式化为 YYYYMM\\n\\n# 步骤5: 合并 yearmonth 与 gas_transactions\\nmerged_df = pd.merge(yearmonth, gas_transactions, on=['CustomerID', 'YearMonth'])\\n\\n# 步骤6: 合并最终结果与 CZK 客户\\nfinal_df = pd.merge(merged_df, czk_customers, on='CustomerID')\\n\\n# 步骤7: 提取年份\\nfinal_df['Year'] = final_df['Date_x'].astype(str).str[:4]\\n\\n# 步骤8: 聚合每年总消费\\nyearly_consumption = final_df.groupby('Year')['Consumption'].sum().reset_index()\\n\\n# 步骤9: 找出消费最大的年份\\npeak_year = yearly_consumption.loc[yearly_consumption['Consumption'].idxmax(), 'Year']\\n\\n# 输出结果\\nprint(\"Year with the most gas consumption paid in CZK:\", peak_year)", "sql": "SELECT SUBSTR(T2.Date, 1, 4) FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID INNER JOIN transactions_1k AS T3 ON T2.CustomerID = T3.CustomerID AND SUBSTR(T2.Date, 1, 6) = T3.Date INNER JOIN products AS T4 ON T3.ProductID = T4.ProductID WHERE T1.Currency = 'CZK' AND T4.Description LIKE '%gas%' GROUP BY SUBSTR(T2.Date, 1, 4) ORDER BY SUM(T2.Consumption) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1480, "question": "What was the gas consumption peak month for SME customers in 2013?", "db_id": "debit_card_specializing", "evidence": "Year 2013 can be presented as Between 201301 And 201312; The first 4 strings of the Date values in the yearmonth table can represent year; The 5th and 6th string of the date can refer to month.", "code": "import pandas as pd\\ncustomers = pd.read_csv('debit_card_specializing/customers.csv')\\nyearmonth = pd.read_csv('debit_card_specializing/yearmonth.csv')\\n# 步骤1: 筛选 SME 客户\\nsme_customers = customers[customers['Segment'] == 'SME'][['CustomerID']]\\n# 步骤2: 合并 yearmonth 表与 SME 客户信息\\nmerged_df = pd.merge(yearmonth, sme_customers, on='CustomerID')\\n# 步骤3: 过滤 2013 年的数据\\nmerged_df['Year'] = merged_df['Date'].astype(str).str[:4]\\nmerged_df_2013 = merged_df[merged_df['Year'] == '2013'].copy()\\n# 步骤4: 提取月份\\nmerged_df_2013['Month'] = merged_df_2013['Date'].astype(str).str[4:6]\\n# 步骤5: 聚合每月总消费\\nmonthly_consumption = merged_df_2013.groupby('Month')['Consumption'].sum().reset_index()\\n# 步骤6: 找出消费最大的月份\\npeak_month = monthly_consumption.loc[monthly_consumption['Consumption'].idxmax(), 'Month']\\n# 输出结果\\nprint(\"Peak consumption month for SME customers in 2013:\", peak_month)", "sql": "SELECT SUBSTR(T2.Date, 5, 2) FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE SUBSTR(T2.Date, 1, 4) = '2013' AND T1.Segment = 'SME' GROUP BY SUBSTR(T2.Date, 5, 2) ORDER BY SUM(T2.Consumption) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1481, "question": "What is the difference in the annual average consumption of the customers with the least amount of consumption paid in CZK for 2013 between SME and LAM, LAM and KAM, and KAM and SME?", "db_id": "debit_card_specializing", "evidence": "ratio calculated by dividing year by the;", "code": "import pandas as pd\nmerged = pd.merge(customers, yearmonth, on='CustomerID')\nfiltered = merged[(merged['Currency'] == 'CZK') & (merged['Date'].between(201301, 201312))]\nannual = filtered.groupby(['CustomerID', 'Segment'], as_index=False)['Consumption'].sum().rename(columns={'Consumption': 'annual_consumption'})\nmin_cons = annual.groupby('Segment')['annual_consumption'].transform('min')\nleast_each = annual[annual['annual_consumption'] == min_cons]\nseg_avg = least_each.groupby('Segment')['annual_consumption'].mean().reset_index()\navg_SME = seg_avg[seg_avg['Segment'] == 'SME']['annual_consumption'].values[0]\navg_LAM = seg_avg[seg_avg['Segment'] == 'LAM']['annual_consumption'].values[0]\navg_KAM = seg_avg[seg_avg['Segment'] == 'KAM']['annual_consumption'].values[0]\nresult = pd.DataFrame([{ 'SME_LAM_diff': avg_SME - avg_LAM, 'LAM_KAM_diff': avg_LAM - avg_KAM, 'KAM_SME_diff': avg_KAM - avg_SME}])", "sql": "WITH annual AS ( SELECT c.CustomerID, c.Segment, SUM(y.Consumption) AS annual_consumption FROM customers AS c JOIN yearmonth AS y ON y.CustomerID = c.CustomerID WHERE c.Currency = 'CZK' AND y.Date BETWEEN '201301' AND '201312' GROUP BY c.CustomerID, c.Segment ), least_each AS ( SELECT a.* FROM annual a JOIN (SELECT Segment, MIN(annual_consumption) AS min_cons FROM annual GROUP BY Segment) m ON a.Segment = m.Segment AND a.annual_consumption = m.min_cons ), seg_avg AS ( SELECT AVG(CASE WHEN Segment = 'SME' THEN annual_consumption END) AS avg_SME, AVG(CASE WHEN Segment = 'LAM' THEN annual_consumption END) AS avg_LAM, AVG(CASE WHEN Segment = 'KAM' THEN annual_consumption END) AS avg_KAM FROM least_each ) SELECT avg_SME - avg_LAM AS SME_LAM_diff, avg_LAM - avg_KAM AS LAM_KAM_diff, avg_KAM - avg_SME AS KAM_SME_diff FROM seg_avg;", "difficulty": "challenging" }, { "question_id": 1482, "question": "Which of the three segments—SME, LAM and KAM—has the biggest and lowest percentage increases in consumption paid in EUR between 2012 and 2013?", "db_id": "debit_card_specializing", "evidence": "ratio calculated by dividing Decrease by consumption;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Filter for customers who paid in EUR\n# SQL: WHERE T1.Currency = 'EUR'\neur_customers = df_customers[df_customers['Currency'] == 'EUR']\n\n# Merge with yearmonth data\n# SQL: INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(eur_customers, df_yearmonth, on='CustomerID')\n\n# Filter for target segments (SME, LAM, KAM)\n# SQL: WHERE T1.Segment IN ('SME', 'LAM', 'KAM')\ntarget_segments = ['SME', 'LAM', 'KAM']\nsegment_data = merged_df[merged_df['Segment'].isin(target_segments)].copy()\n\n# Extract Year from Date\n# SQL: SUBSTR(T2.Date, 1, 4)\nsegment_data['Year'] = segment_data['Date'].astype(str).str[:4]\n\n# Group by Segment and Year to get total consumption\n# SQL: GROUP BY T1.Segment\nconsumption_by_segment = segment_data.groupby(['Segment', 'Year'])['Consumption'].sum().unstack(fill_value=0)\n\n# Calculate Percentage Increase: (2013 - 2012) / 2012 * 100\n# SQL: (SUM(2013) - SUM(2012)) * 100 / SUM(2012)\n# Ensure columns exist to prevent KeyErrors\nif '2012' in consumption_by_segment.columns and '2013' in consumption_by_segment.columns:\n consumption_by_segment['Percentage_Increase'] = (\n (consumption_by_segment['2013'] - consumption_by_segment['2012']) / consumption_by_segment['2012'] * 100\n )\nelse:\n consumption_by_segment['Percentage_Increase'] = 0.0\n\n# Find biggest and lowest increase\n# SQL: ORDER BY Percentage_Increase DESC LIMIT 1 / ASC LIMIT 1\nbiggest_increase = consumption_by_segment['Percentage_Increase'].idxmax()\nlowest_increase = consumption_by_segment['Percentage_Increase'].idxmin()\n\nresult = [biggest_increase, lowest_increase]\nprint(result)", "sql": "WITH segment_changes AS ( SELECT T1.Segment, CAST((SUM(CASE WHEN SUBSTR(T2.Date, 1, 4) = '2013' THEN T2.Consumption ELSE 0 END) - SUM(CASE WHEN SUBSTR(T2.Date, 1, 4) = '2012' THEN T2.Consumption ELSE 0 END)) AS FLOAT) * 100 / NULLIF(SUM(CASE WHEN SUBSTR(T2.Date, 1, 4) = '2012' THEN T2.Consumption ELSE 0 END), 0) AS Percentage_Increase FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Segment IN ('SME', 'LAM', 'KAM') AND T1.Currency = 'EUR' GROUP BY T1.Segment ) SELECT (SELECT Segment FROM segment_changes ORDER BY Percentage_Increase DESC LIMIT 1) AS Biggest_Increase, (SELECT Segment FROM segment_changes ORDER BY Percentage_Increase ASC LIMIT 1) AS Lowest_Increase", "difficulty": "challenging" }, { "question_id": 1483, "question": "How much did customer 6 consume in total between August and November 2013?", "db_id": "debit_card_specializing", "evidence": "Between August And November 2013 refers to Between 201308 And 201311; The first 4 strings of the Date values in the yearmonth table can represent year; The 5th and 6th string of the date can refer to month.", "code": "import pandas as pd\n\n# Read the CSV file\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Filter for CustomerID 6\n# SQL: WHERE CustomerID = 6\ncustomer_mask = df_yearmonth['CustomerID'] == 6\n\n# Filter for Date between '201308' and '201311'\n# SQL: AND Date BETWEEN '201308' AND '201311'\n# Ensure 'Date' column is string to perform lexicographical comparison matching SQL behavior\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\ndate_mask = (df_yearmonth['Date'] >= '201308') & (df_yearmonth['Date'] <= '201311')\n\n# Apply filters\nfiltered_df = df_yearmonth[customer_mask & date_mask]\n\n# Calculate total consumption\n# SQL: SELECT SUM(Consumption)\nresult = filtered_df['Consumption'].sum()\n\nprint(result)", "sql": "SELECT SUM(Consumption) FROM yearmonth WHERE CustomerID = 6 AND Date BETWEEN '201308' AND '201311'", "difficulty": "simple" }, { "question_id": 1484, "question": "How many more \"discount\" gas stations does the Czech Republic have compared to Slovakia?", "db_id": "debit_card_specializing", "evidence": "Czech Republic can be represented as the Country value in gasstations table is 'CZE'; Slovakia can be represented as the Country value in the gasstations table is 'SVK'; Computation of more \"discount\" gas stations= Total no. of discount gas stations in Czech Republic - Total no. of discount gas stations in Slovakia", "code": "import pandas as pd\n\n# Filter for discount gas stations\ndiscount_stations = gasstations[gasstations['Segment'] == 'Discount']\n\n# Count discount stations in Czech Republic\ncze_count = len(discount_stations[discount_stations['Country'] == 'CZE'])\n\n# Count discount stations in Slovakia\nsvk_count = len(discount_stations[discount_stations['Country'] == 'SVK'])\n\n# Calculate the difference\nresult = cze_count - svk_count", "sql": "SELECT SUM(IIF(Country = 'CZE', 1, 0)) - SUM(IIF(Country = 'SVK', 1, 0)) FROM gasstations WHERE Segment = 'Discount'", "difficulty": "simple" }, { "question_id": 1485, "question": "How much more was customer 7 consuming in April 2013 than customer 5?", "db_id": "debit_card_specializing", "evidence": "April 2013 refers to 201304 in the yearmonth.date", "code": "import pandas as pd\n\n# Read the CSV file\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Ensure Date column is treated as string for comparison\n# SQL: WHERE Date = '201304'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\n\n# Filter for April 2013\napril_2013 = df_yearmonth[df_yearmonth['Date'] == '201304']\n\n# Calculate consumption for Customer 7\n# SQL: SUM(IIF(CustomerID = 7, Consumption, 0))\ncons_7 = april_2013[april_2013['CustomerID'] == 7]['Consumption'].sum()\n\n# Calculate consumption for Customer 5\n# SQL: SUM(IIF(CustomerID = 5, Consumption, 0))\ncons_5 = april_2013[april_2013['CustomerID'] == 5]['Consumption'].sum()\n\n# Calculate the difference\nresult = cons_7 - cons_5\n\nprint(result)", "sql": "SELECT SUM(IIF(CustomerID = 7, Consumption, 0)) - SUM(IIF(CustomerID = 5, Consumption, 0)) FROM yearmonth WHERE Date = '201304'", "difficulty": "simple" }, { "question_id": 1486, "question": "Is it true that more SMEs pay in Czech koruna than in euros? If so, how many more?", "db_id": "debit_card_specializing", "evidence": "Amount of more SMEs = Total of SMEs pay using Currency CZK - Total of SMEs pay using Currency EUR", "code": "import pandas as pd\n\n# Read the CSV file\ndf_customers = pd.read_csv('customers.csv')\n\n# Filter for 'SME' segment\n# SQL: WHERE Segment = 'SME'\nsme_df = df_customers[df_customers['Segment'] == 'SME']\n\n# Calculate count of CZK currency\n# SQL: SUM(Currency = 'CZK')\nczk_count = (sme_df['Currency'] == 'CZK').sum()\n\n# Calculate count of EUR currency\n# SQL: SUM(Currency = 'EUR')\neur_count = (sme_df['Currency'] == 'EUR').sum()\n\n# Calculate the difference\n# SQL: ... - ...\nresult = czk_count - eur_count\n\nprint(result)", "sql": "SELECT SUM(Currency = 'CZK') - SUM(Currency = 'EUR') FROM customers WHERE Segment = 'SME'", "difficulty": "simple" }, { "question_id": 1487, "question": "Which LAM customer used the Euro as their currency and had the highest consumption in October 2013?", "db_id": "debit_card_specializing", "evidence": "October 2013 refers to 201310 in the yearmonth.date", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge tables on CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Filter data\n# SQL: WHERE T1.Segment = 'LAM' AND T2.Date = '201310' AND T1.Currency = 'EUR'\nmerged_df['Date'] = merged_df['Date'].astype(str)\nfiltered_df = merged_df[\n (merged_df['Segment'] == 'LAM') & \n (merged_df['Date'] == '201310') & \n (merged_df['Currency'] == 'EUR')\n]\n\n# Group by CustomerID and sum consumption (Matching SQL logic)\n# SQL: GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) DESC LIMIT 1\ngrouped = filtered_df.groupby('CustomerID')['Consumption'].sum().reset_index()\ntop_customer = grouped.sort_values(by='Consumption', ascending=False).head(1)\n\n# Extract the CustomerID\nresult = top_customer['CustomerID'].values[0]\n\nprint(result)", "sql": "SELECT T1.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Segment = 'LAM' AND T2.Date = '201310' AND T1.Currency = 'EUR' GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) DESC LIMIT 1", "difficulty": "moderate" }, { "question_id": 1488, "question": "Who among KAM's customers consumed the most? How much did it consume?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge customers and yearmonth tables on CustomerID\n# SQL: INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(df_yearmonth, df_customers, on='CustomerID')\n\n# Filter for KAM segment customers\n# SQL: WHERE T1.Segment = 'KAM'\nkam_customers = merged_df[merged_df['Segment'] == 'KAM']\n\n# Calculate total consumption for each KAM customer\n# SQL: GROUP BY T2.CustomerID, SUM(T2.Consumption)\ntotal_consumption_by_customer = kam_customers.groupby('CustomerID')['Consumption'].sum().reset_index()\n\n# Sort by total consumption in descending order and take the top one\n# SQL: ORDER BY SUM(T2.Consumption) DESC LIMIT 1\ntop_record = total_consumption_by_customer.sort_values(by='Consumption', ascending=False).head(1)\n\n# Select the required columns and convert to list of lists to match SQL output structure\n# Structure: [[CustomerID, Consumption]]\nresult = top_record[['CustomerID', 'Consumption']].values.tolist()\n\nprint(result)", "sql": "SELECT T2.CustomerID, SUM(T2.Consumption) \nFROM customers AS T1 \nINNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID \nWHERE T1.Segment = 'KAM' \nGROUP BY T2.CustomerID \nORDER BY SUM(T2.Consumption) DESC \nLIMIT 1", "difficulty": "simple" }, { "question_id": 1489, "question": "How much did the KAM customers consume in total in May 2013?", "db_id": "debit_card_specializing", "evidence": "date equals 201305 in the database;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge customers and yearmonth tables on CustomerID\n# SQL: INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Ensure Date column is treated as string to match the filter value '201305'\n# This fixes the issue where Date is read as int64 but compared against a string\nmerged_df['Date'] = merged_df['Date'].astype(str)\n\n# Filter for KAM segment and May 2013\n# SQL: WHERE T2.Date = '201305' AND T1.Segment = 'KAM'\nfiltered_df = merged_df[\n (merged_df['Segment'] == 'KAM') & \n (merged_df['Date'] == '201305')\n]\n\n# Calculate total consumption\n# SQL: SELECT SUM(T2.Consumption)\nresult = filtered_df['Consumption'].sum()\n\nprint(result)", "sql": "SELECT SUM(T2.Consumption) FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T2.Date = '201305' AND T1.Segment = 'KAM'", "difficulty": "simple" }, { "question_id": 1490, "question": "How many percent of LAM customer consumed more than 46.73?", "db_id": "debit_card_specializing", "evidence": "ratio calculated by dividing 73 by Total;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge customers and yearmonth tables on CustomerID\n# SQL: INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Filter for LAM segment customers\n# SQL: WHERE T1.Segment = 'LAM'\nlam_df = merged_df[merged_df['Segment'] == 'LAM']\n\n# Group by CustomerID and calculate total consumption for each customer\n# SQL: GROUP BY T1.CustomerID\ncustomer_totals = lam_df.groupby('CustomerID')['Consumption'].sum()\n\n# Count customers with consumption > 46.73\n# SQL: SUM(CASE WHEN customer_consumption.total_consumption > 46.73 THEN 1 ELSE 0 END)\ncount_above = (customer_totals > 46.73).sum()\n\n# Count total LAM customers\n# SQL: COUNT(*)\ntotal_count = len(customer_totals)\n\n# Calculate percentage\n# SQL: ... * 100 / COUNT(*)\nif total_count > 0:\n result = (count_above / total_count) * 100\nelse:\n result = 0.0\n\nprint(result)", "sql": "SELECT CAST(SUM(CASE WHEN customer_consumption.total_consumption > 46.73 THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(*) FROM (SELECT T1.CustomerID, SUM(T2.Consumption) as total_consumption FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Segment = 'LAM' GROUP BY T1.CustomerID) AS customer_consumption", "difficulty": "moderate" }, { "question_id": 1491, "question": "Which country has more \"value for money\" gas stations? Please give a total number of \"value for money\" gas stations in each country.", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV file\ndf_gasstations = pd.read_csv('gasstations.csv')\n\n# Filter for 'Value for money' segment\n# SQL: WHERE Segment = 'Value for money'\nfiltered_df = df_gasstations[df_gasstations['Segment'] == 'Value for money']\n\n# Group by Country and count GasStationID\n# SQL: GROUP BY Country, COUNT(GasStationID)\ngrouped_df = filtered_df.groupby('Country')['GasStationID'].count().reset_index()\n\n# Sort by count in descending order and take the top 1\n# SQL: ORDER BY COUNT(GasStationID) DESC LIMIT 1\ntop_result = grouped_df.sort_values(by='GasStationID', ascending=False).head(1)\n\n# Format output as list of lists to match SQL output structure\n# Structure: [[Country, Count]]\nresult = top_result.values.tolist()\n\nprint(result)", "sql": "SELECT Country, COUNT(GasStationID) FROM gasstations WHERE Segment = 'Value for money' GROUP BY Country ORDER BY COUNT(GasStationID) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1492, "question": "What percentage of KAM customers pay in euros?", "db_id": "debit_card_specializing", "evidence": "ratio calculated by dividing Euro by Total;", "code": "import pandas as pd\nkam_customers = customers[customers['Segment'] == 'KAM']\neur_count = kam_customers[kam_customers['Currency'] == 'EUR'].shape[0]\ntotal_count = kam_customers.shape[0]\npercentage = (eur_count / total_count) * 100 if total_count > 0 else 0\nresult = percentage", "sql": "SELECT CAST(SUM(Currency = 'EUR') AS FLOAT) * 100.0 / COUNT(CustomerID) FROM customers WHERE Segment = 'KAM'", "difficulty": "simple" }, { "question_id": 1493, "question": "In February 2012, what percentage of customers consumed more than 528.3?", "db_id": "debit_card_specializing", "evidence": "February 2012 refers to '201202' in yearmonth.date; The first 4 strings of the Date values in the yearmonth table can represent year; The 5th and 6th string of the date can refer to month.", "code": "import pandas as pd\n\n# Read the CSV file\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Ensure Date column is treated as string for comparison\n# SQL: WHERE Date = '201202'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\n\n# Filter for February 2012\nfiltered_df = df_yearmonth[df_yearmonth['Date'] == '201202']\n\n# Count customers with consumption > 528.3\n# SQL: SUM(IIF(Consumption > 528.3, 1, 0))\ncount_above = (filtered_df['Consumption'] > 528.3).sum()\n\n# Count total customers in that month\n# SQL: COUNT(CustomerID)\ntotal_count = len(filtered_df)\n\n# Calculate percentage\n# SQL: ... * 100 / ...\nif total_count > 0:\n result = (count_above / total_count) * 100\nelse:\n result = 0.0\n\nprint(result)", "sql": "SELECT CAST(SUM(IIF(Consumption > 528.3, 1, 0)) AS FLOAT) * 100 / COUNT(CustomerID) FROM yearmonth WHERE Date = '201202'", "difficulty": "simple" }, { "question_id": 1494, "question": "What percentage of Slovakian gas stations are premium?", "db_id": "debit_card_specializing", "evidence": "ratio calculated by dividing Slovakia by Total;", "code": "import pandas as pd\nimport numpy as np\n\n# Filter for Slovakian gas stations\nslovakian_stations = gasstations[gasstations['Country'] == 'SVK']\n\n# Calculate percentage of premium stations\npremium_count = (slovakian_stations['Segment'] == 'Premium').sum()\ntotal_count = len(slovakian_stations)\nresult = (premium_count / total_count) * 100", "sql": "SELECT CAST(SUM(IIF(Segment = 'Premium', 1, 0)) AS FLOAT) * 100 / COUNT(GasStationID) FROM gasstations WHERE Country = 'SVK'", "difficulty": "simple" }, { "question_id": 1495, "question": "Which client ID consumed the most in September 2013?", "db_id": "debit_card_specializing", "evidence": "date equals '201309' in the database;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge tables on CustomerID\n# SQL: INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Ensure Date column is treated as string for comparison\n# SQL: WHERE T2.Date = '201309'\nmerged_df['Date'] = merged_df['Date'].astype(str)\nfiltered_df = merged_df[merged_df['Date'] == '201309']\n\n# Group by CustomerID and sum consumption\n# SQL: GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) DESC LIMIT 1\ngrouped = filtered_df.groupby('CustomerID')['Consumption'].sum().reset_index()\ntop_customer = grouped.sort_values(by='Consumption', ascending=False).head(1)\n\n# Extract the result\nresult = top_customer['CustomerID'].values[0]\n\nprint(result)", "sql": "SELECT T1.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T2.Date = '201309' GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1496, "question": "Which client segment consumed the least in September 2013?", "db_id": "debit_card_specializing", "evidence": "date equals '201309' in the database;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Merge customers and yearmonth tables\n# SQL: INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(df_customers, df_yearmonth, on='CustomerID')\n\n# Ensure Date column is treated as string for comparison\n# SQL: WHERE T2.Date = '201309'\nmerged_df['Date'] = merged_df['Date'].astype(str)\nfiltered_df = merged_df[merged_df['Date'] == '201309']\n\n# Group by Segment and sum consumption\n# SQL: GROUP BY T1.Segment ORDER BY SUM(T2.Consumption) ASC LIMIT 1\ngrouped = filtered_df.groupby('Segment')['Consumption'].sum().reset_index()\nleast_consumed_segment = grouped.sort_values(by='Consumption', ascending=True).head(1)\n\n# Extract the segment name\nresult = least_consumed_segment['Segment'].values[0]\n\nprint(result)", "sql": "SELECT T1.Segment FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T2.Date = '201309' GROUP BY T1.Segment ORDER BY SUM(T2.Consumption) ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1497, "question": "Which SME customer consumed the least in June 2012?", "db_id": "debit_card_specializing", "evidence": "date equals '201206' in the database;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Filter customers for 'SME' segment\n# SQL: WHERE T1.Segment = 'SME'\nsme_customers = df_customers[df_customers['Segment'] == 'SME']\n\n# Ensure Date column is treated as string for comparison\n# SQL: WHERE T2.Date = '201206'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\ndate_filtered = df_yearmonth[df_yearmonth['Date'] == '201206']\n\n# Merge filtered tables\n# SQL: INNER JOIN ... ON ...\nmerged_df = pd.merge(sme_customers, date_filtered, on='CustomerID')\n\n# Group by CustomerID and sum consumption\n# SQL: GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) ASC LIMIT 1\ngrouped = merged_df.groupby('CustomerID')['Consumption'].sum().reset_index()\nleast_consuming_customer = grouped.sort_values(by='Consumption', ascending=True).head(1)\n\n# Extract the CustomerID\nresult = least_consuming_customer['CustomerID'].values[0]\n\nprint(result)", "sql": "SELECT T1.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T2.Date = '201206' AND T1.Segment = 'SME' GROUP BY T1.CustomerID ORDER BY SUM(T2.Consumption) ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1498, "question": "What is the highest monthly consumption in the year 2012?", "db_id": "debit_card_specializing", "evidence": "The first 4 strings of the Date values in the yearmonth table can represent year; The 5th and 6th string of the date can refer to month.", "code": "import pandas as pd\n\n# Read the CSV file\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Ensure Date column is treated as string\n# SQL: SUBSTR(Date, 1, 4) = '2012'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\n\n# Filter for the year 2012\ndf_2012 = df_yearmonth[df_yearmonth['Date'].str.startswith('2012')]\n\n# Group by Date (YYYYMM) to get monthly totals\n# Since we already filtered for 2012, grouping by 'Date' (e.g., '201201') is equivalent to grouping by month\n# SQL: GROUP BY SUBSTR(Date, 5, 2)\nmonthly_consumption = df_2012.groupby('Date')['Consumption'].sum()\n\n# Find the highest monthly consumption\n# SQL: ORDER BY SUM(Consumption) DESC LIMIT 1\nresult = monthly_consumption.max()\n\nprint(result)", "sql": "SELECT SUM(Consumption) FROM yearmonth WHERE SUBSTR(Date, 1, 4) = '2012' GROUP BY SUBSTR(Date, 5, 2) ORDER BY SUM(Consumption) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1499, "question": "What is the biggest monthly consumption of the customers who use euro as their currency?", "db_id": "debit_card_specializing", "evidence": "sum of consumption;Consumption refers to annual consumption", "code": "import pandas as pd\nmerged = pd.merge(customers, yearmonth, on='CustomerID')\nresult = merged[merged['Currency'] == 'EUR']['Consumption'].max()", "sql": "SELECT MAX(T2.Consumption) AS MonthlyConsumption FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Currency = 'EUR'", "difficulty": "simple" }, { "question_id": 1500, "question": "Please list the product description of the products consumed in September, 2013.", "db_id": "debit_card_specializing", "evidence": "September 2013 refers to 201309; The first 4 strings of the Date values in the yearmonth table can represent year; The 5th and 6th string of the date can refer to month.", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\ndf_products = pd.read_csv('products.csv')\n\n# Filter yearmonth for '201309'\n# SQL: WHERE T2.Date = '201309'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\nfiltered_ym = df_yearmonth[df_yearmonth['Date'] == '201309']\n\n# Merge transactions with filtered yearmonth on CustomerID\n# SQL: FROM transactions_1k AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_trans = pd.merge(df_transactions, filtered_ym, on='CustomerID')\n\n# Merge with products on ProductID\n# SQL: INNER JOIN products AS T3 ON T1.ProductID = T3.ProductID\nmerged_final = pd.merge(merged_trans, df_products, on='ProductID')\n\n# Select Description\n# SQL: SELECT T3.Description\nresult = merged_final['Description']\n\nprint(result)", "sql": "SELECT T3.Description FROM transactions_1k AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID INNER JOIN products AS T3 ON T1.ProductID = T3.ProductID WHERE T2.Date = '201309'", "difficulty": "simple" }, { "question_id": 1501, "question": "Please list the countries of the gas stations with transactions taken place in June, 2013.", "db_id": "debit_card_specializing", "evidence": "June 2013 refers to '201306'; The first 4 strings of the Date values in the yearmonth table can represent year; The 5th and 6th string of the date can refer to month;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_gasstations = pd.read_csv('gasstations.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Filter yearmonth for June 2013\n# SQL: WHERE T3.Date = '201306'\n# Important: Convert Date to string to match the string literal '201306'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\nfiltered_ym = df_yearmonth[df_yearmonth['Date'] == '201306']\n\n# Join transactions with filtered yearmonth to get relevant customers\n# SQL: INNER JOIN yearmonth AS T3 ON T1.CustomerID = T3.CustomerID\nmerged_trans = pd.merge(df_transactions, filtered_ym, on='CustomerID')\n\n# Join with gasstations to get country info\n# SQL: INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID\nmerged_final = pd.merge(merged_trans, df_gasstations, on='GasStationID')\n\n# Get distinct countries\n# SQL: SELECT DISTINCT T2.Country\nresult = merged_final['Country'].unique()\n\nprint(result)", "sql": "SELECT DISTINCT T2.Country FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID INNER JOIN yearmonth AS T3 ON T1.CustomerID = T3.CustomerID WHERE T3.Date = '201306'", "difficulty": "moderate" }, { "question_id": 1502, "question": "Please list the chains of the gas stations with transactions in euro.", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\nimport numpy as np\n\n# Merge transactions with customers to get currency info\nmerged = pd.merge(transactions_1k, customers, on='CustomerID')\n\n# Further merge with gasstations to get ChainID\nmerged = pd.merge(merged, gasstations, on='GasStationID')\n\n# Filter for EUR currency and get unique ChainIDs\nresult = merged[merged['Currency'] == 'EUR']['ChainID'].unique()", "sql": "SELECT DISTINCT T3.ChainID FROM transactions_1k AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID INNER JOIN gasstations AS T3 ON T1.GasStationID = T3.GasStationID WHERE T2.Currency = 'EUR'", "difficulty": "simple" }, { "question_id": 1503, "question": "Please list the product description of the products bought in transactions in euro.", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\ndef solve_query(transactions, products, customers):\n # Ensure the necessary columns exist\n if 'CustomerID' not in transactions.columns or 'Currency' not in customers.columns:\n return pd.DataFrame(columns=['ProductID', 'Description'])\n\n # Filter customers with Currency = 'EUR'\n euro_customers = customers[customers['Currency'] == 'EUR']\n\n # Merge transactions with euro_customers to filter relevant transactions\n merged_transactions = pd.merge(transactions, euro_customers, on='CustomerID', how='inner')\n\n # Merge with products to get product descriptions\n result = pd.merge(merged_transactions, products, left_on='ProductID', right_on='ProductID', how='inner')\n\n # Select distinct ProductID and Description\n result = result[['ProductID', 'Description']].drop_duplicates()\n\n return result\n\n# Example function call\ndata_transactions = pd.DataFrame({\n 'TransactionID': [1, 2, 3],\n 'CustomerID': [101, 102, 103],\n 'ProductID': [201, 202, 203]\n})\ndata_products = pd.DataFrame({\n 'ProductID': [201, 202, 203],\n 'Description': ['Gasoline', 'Diesel', 'LPG']\n})\ndata_customers = pd.DataFrame({\n 'CustomerID': [101, 102, 103],\n 'Currency': ['EUR', 'USD', 'EUR']\n})\nresult = solve_query(data_transactions, data_products, data_customers)\nprint(result)", "sql": "SELECT DISTINCT T1.ProductID, P.Description FROM transactions_1k T1 JOIN products P ON T1.ProductID = P.ProductID WHERE EXISTS (SELECT 1 FROM customers C WHERE C.CustomerID = T1.CustomerID AND C.Currency = 'EUR')", "difficulty": "simple" }, { "question_id": 1504, "question": "What is the average total price of the transactions taken place in January, 2012?", "db_id": "debit_card_specializing", "evidence": "In January, 2012 means Date contains '2012-01'", "code": "import pandas as pd\n\n# Filter transactions for January 2012\nfiltered = transactions_1k[transactions_1k['Date'].str.contains('2012-01')]\n\n# Calculate total price for each transaction and get average\nresult = (filtered['Amount'] * filtered['Price']).mean()", "sql": "SELECT AVG(Amount * Price) FROM transactions_1k WHERE Date LIKE '2012-01%'", "difficulty": "simple" }, { "question_id": 1505, "question": "Among the customers who paid in euro, how many of them have a monthly consumption of over 1000?", "db_id": "debit_card_specializing", "evidence": "Currency equals 'EUR' in the database;", "code": "import pandas as pd\nmerged = pd.merge(yearmonth, customers, on='CustomerID')\nfiltered = merged[(merged['Currency'] == 'EUR') & (merged['Consumption'] > 1000)]\nresult = filtered['CustomerID'].nunique()", "sql": "SELECT COUNT(DISTINCT T1.CustomerID) FROM yearmonth AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID WHERE T2.Currency = 'EUR' AND T1.Consumption > 1000.00", "difficulty": "simple" }, { "question_id": 1506, "question": "Please list the product descriptions of the transactions taken place in the gas stations in the Czech Republic.", "db_id": "debit_card_specializing", "evidence": "Czech Republic can be represented as the Country value in the gasstations table is 'CZE';", "code": "import pandas as pd\n\n# Merge transactions with gasstations\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\n\n# Filter for Czech Republic\nczech_transactions = merged[merged['Country'] == 'CZE']\n\n# Merge with products\nfinal_merged = pd.merge(czech_transactions, products, on='ProductID')\n\n# Get unique product descriptions\nresult = final_merged['Description'].unique()", "sql": "SELECT DISTINCT T3.Description FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID INNER JOIN products AS T3 ON T1.ProductID = T3.ProductID WHERE T2.Country = 'CZE'", "difficulty": "moderate" }, { "question_id": 1507, "question": "Please list the disparate time of the transactions taken place in the gas stations from chain no. 11.", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\nresult = pd.merge(transactions_1k, gasstations, on='GasStationID')\nresult = result[result['ChainID'] == 11]\nresult = result[['Time']].drop_duplicates()", "sql": "SELECT DISTINCT T1.Time FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T2.ChainID = 11", "difficulty": "simple" }, { "question_id": 1508, "question": "How many transactions taken place in the gas station in the Czech Republic are with a price of over 1000?", "db_id": "debit_card_specializing", "evidence": "Country equals 'CZE' in the database;", "code": "import pandas as pd\n\n# Merge transactions with gasstations\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\n\n# Filter for Czech Republic and price > 1000\nfiltered = merged[(merged['Country'] == 'CZE') & (merged['Price'] > 1000)]\n\n# Count the transactions\nresult = len(filtered)", "sql": "SELECT COUNT(T1.TransactionID) FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T2.Country = 'CZE' AND T1.Price > 1000", "difficulty": "simple" }, { "question_id": 1509, "question": "Among the transactions made in the gas stations in the Czech Republic, how many of them are taken place after 2012/1/1?", "db_id": "debit_card_specializing", "evidence": "Czech Republic can be represented as the Country value in the gasstations table is 'CZE'", "code": "import pandas as pd\n\n# Convert Date column to datetime\ntransactions_1k['Date'] = pd.to_datetime(transactions_1k['Date'])\n\n# Merge transactions with gas stations\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\n\n# Filter for Czech Republic and dates after 2012-01-01\nfiltered = merged[(merged['Country'] == 'CZE') & (merged['Date'] >= '2012-01-01')]\n\n# Count the transactions\nresult = len(filtered)", "sql": "SELECT COUNT(T1.TransactionID) FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T2.Country = 'CZE' AND STRFTIME('%Y', T1.Date) >= '2012'", "difficulty": "moderate" }, { "question_id": 1510, "question": "What is the average total price of the transactions taken place in gas stations in the Czech Republic?", "db_id": "debit_card_specializing", "evidence": "Country equals 'CZE' in the database;", "code": "import pandas as pd\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\nfiltered = merged[merged['Country'] == 'CZE']\nresult = filtered['Price'].mean()", "sql": "SELECT AVG(T1.Price * T1.Amount) FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T2.Country = 'CZE'", "difficulty": "simple" }, { "question_id": 1511, "question": "For the customers who paid in the euro, what is their average total price of the transactions?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Merge transactions with customers to get currency information\nmerged = pd.merge(transactions_1k, customers, on='CustomerID')\n\n# Filter for customers who paid in EUR\neur_transactions = merged[merged['Currency'] == 'EUR']\n\n# Calculate average price\nresult = eur_transactions['Price'].mean()", "sql": "SELECT AVG(T1.Amount * T1.Price) FROM transactions_1k AS T1 INNER JOIN customers AS T3 ON T1.CustomerID = T3.CustomerID WHERE T3.Currency = 'EUR'", "difficulty": "simple" }, { "question_id": 1512, "question": "Which customer paid the most in 2012/8/25?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-25' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\nfiltered = transactions_1k[transactions_1k['Date'] == '2012-08-25']\ngrouped = filtered.groupby('CustomerID')['Price'].sum().reset_index()\nresult = grouped.sort_values('Price', ascending=False).head(1)['CustomerID']", "sql": "SELECT CustomerID FROM transactions_1k WHERE Date = '2012-08-25' GROUP BY CustomerID ORDER BY SUM(Price) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1513, "question": "Which country's gas station had the first paid cusomer in 2012/8/25?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-25' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Filter transactions for the specific date\nfiltered_trans = transactions_1k[transactions_1k['Date'] == '2012-08-25']\n\n# Sort by time to get the earliest transaction\nsorted_trans = filtered_trans.sort_values('Time', ascending=True)\n\n# Get the first transaction\nfirst_trans = sorted_trans.head(1)\n\n# Merge with gasstations to get country\nmerged = pd.merge(first_trans, gasstations, on='GasStationID')\n\n# Get the country\nresult = merged['Country'].iloc[0]", "sql": "SELECT T2.Country FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.Date = '2012-08-25' ORDER BY T1.Time ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1514, "question": "What kind of currency did the customer paid at 16:25:00 in 2012/8/24?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-24' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Merge transactions with gasstations\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\n\n# Merge with customers\nmerged = pd.merge(merged, customers, on='CustomerID')\n\n# Filter for specific date and time\nfiltered = merged[(merged['Date'] == '2012-08-24') & (merged['Time'] == '16:25:00')]\n\n# Get unique currencies\nresult = filtered[['Currency']].drop_duplicates()", "sql": "SELECT DISTINCT T3.Currency FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID INNER JOIN customers AS T3 ON T1.CustomerID = T3.CustomerID WHERE T1.Date = '2012-08-24' AND T1.Time = '16:25:00'", "difficulty": "simple" }, { "question_id": 1515, "question": "What segment did the customer have at 2012/8/23 21:20:00?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-23' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Filter transactions for the specific date and time\nfiltered_transactions = transactions_1k[(transactions_1k['Date'] == '2012-08-23') & (transactions_1k['Time'] == '21:20:00')]\n\n# Merge with customers to get segment\nresult = pd.merge(filtered_transactions, customers, on='CustomerID')[['Segment']]", "sql": "SELECT T2.Segment FROM transactions_1k AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.date = '2012-08-23' AND T1.time = '21:20:00'", "difficulty": "simple" }, { "question_id": 1516, "question": "How many transactions were paid in CZK in the morning of 2012/8/26?", "db_id": "debit_card_specializing", "evidence": "'2012/8/26' can be represented by '2012-08-26'; The morning refers to the time before '13:00:00'", "code": "import pandas as pd\n\n# Merge transactions_1k with customers\nmerged = pd.merge(transactions_1k, customers, on='CustomerID')\n\n# Filter for date 2012-08-26, morning time (before 13:00:00), and CZK currency\nfiltered = merged[(merged['Date'] == '2012-08-26') & \n (merged['Time'] < '13:00:00') & \n (merged['Currency'] == 'CZK')]\n\n# Count the number of transactions\nresult = len(filtered)", "sql": "SELECT COUNT(T1.TransactionID) FROM transactions_1k AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Date = '2012-08-26' AND T1.Time < '13:00:00' AND T2.Currency = 'CZK'", "difficulty": "moderate" }, { "question_id": 1517, "question": "For the earliest customer, what segment did he/she have?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_customers = pd.read_csv('customers.csv')\n\n# Merge transactions with customers to link Segment info\n# SQL: FROM transactions_1k AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(df_transactions, df_customers, on='CustomerID')\n\n# Sort by Date in ascending order to find the earliest transaction\n# SQL: ORDER BY Date ASC LIMIT 1\nsorted_df = merged_df.sort_values(by='Date', ascending=True)\n\n# Select the Segment of the first record\nif not sorted_df.empty:\n result = sorted_df.iloc[0]['Segment']\nelse:\n result = None\n\nprint(result)", "sql": "SELECT T2.Segment FROM transactions_1k AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID ORDER BY Date ASC LIMIT 1", "difficulty": "simple" }, { "question_id": 1518, "question": "For the deal happened at 2012/8/24 12:42:00, which country was it?", "db_id": "debit_card_specializing", "evidence": "date equals '2012-08-24' in the database; time equals '12:42:00' in the database; datetime '2012-08-24 12:42:00' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\nfiltered_transactions = transactions_1k[(transactions_1k['Date'] == '2012-08-24') & (transactions_1k['Time'] == '12:42:00')]\nmerged = pd.merge(filtered_transactions, gasstations, on='GasStationID')\nresult = merged[['Country']]", "sql": "SELECT T2.Country FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.Date = '2012-08-24' AND T1.Time = '12:42:00';", "difficulty": "simple" }, { "question_id": 1519, "question": "What was the product id of the transaction happened at 2012/8/23 21:20:00?", "db_id": "debit_card_specializing", "evidence": "date equals '2012-08-23' in the database; time equals '21:20:00' in the database; datetime '2012-08-23 21:20:00' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Filter transactions for the specific date and time\nfiltered_transactions = transactions_1k[(transactions_1k['Date'] == '2012-08-23') & (transactions_1k['Time'] == '21:20:00')]\n\n# Get the ProductID(s)\nresult = filtered_transactions[['ProductID']]", "sql": "SELECT T1.ProductID FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.Date = '2012-08-23' AND T1.Time = '21:20:00'", "difficulty": "simple" }, { "question_id": 1520, "question": "For the customer who paid 124.05 in 2012/8/24, how much did he/she spend during the January of 2012? And what is the date and expenses exactly?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-24' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Find the customers who paid 124.05 on 2012-08-24\n# SQL: WHERE T1.Date = '2012-08-24' AND T1.Price = 124.05\n# Note: Interpreting 'paid' as 'Price' based on the provided SQL logic.\ntarget_customers = df_transactions[\n (df_transactions['Date'] == '2012-08-24') & \n (df_transactions['Price'] == 124.05)\n]['CustomerID'].unique()\n\n# Get January 2012 data for these customers\n# SQL: AND T2.Date = '201201'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\nresult_df = df_yearmonth[\n (df_yearmonth['Date'] == '201201') & \n (df_yearmonth['CustomerID'].isin(target_customers))\n]\n\n# Select columns to match SQL output: CustomerID, Date, Consumption\nresult = result_df[['CustomerID', 'Date', 'Consumption']].values.tolist()\n\nprint(result)", "sql": "SELECT T1.CustomerID, T2.Date, T2.Consumption FROM transactions_1k AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Date = '2012-08-24' AND T1.Price = 124.05 AND T2.Date = '201201'", "difficulty": "moderate" }, { "question_id": 1521, "question": "For all the transactions happened during 8:00-9:00 in 2012/8/26, how many happened in CZE?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-26' in the database; Time is between '08:00:00' and '09:00:00' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\nfiltered = merged[(merged['Date'] == '2012-08-26') & (merged['Time'] >= '08:00:00') & (merged['Time'] <= '09:00:00') & (merged['Country'] == 'CZE')]\nresult = len(filtered)", "sql": "SELECT COUNT(T1.TransactionID) FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.Date = '2012-08-26' AND T1.Time BETWEEN '08:00:00' AND '09:00:00' AND T2.Country = 'CZE'", "difficulty": "moderate" }, { "question_id": 1522, "question": "There's one customer spent 214582.17 in the June of 2013, which currency did he/she use?", "db_id": "debit_card_specializing", "evidence": "June of 2013 means Date contains '201306' in the yearmonth.date of the database", "code": "import pandas as pd\n\n# Read the CSV files\ndf_customers = pd.read_csv('customers.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Ensure Date column is treated as string for comparison\n# SQL: WHERE T1.Date = '201306'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\n\n# Filter yearmonth data for June 2013 and specific consumption\n# SQL: AND T1.Consumption = 214582.17\n# Note: Using a small epsilon for float comparison is safer, but strictly matching SQL literal here\nfiltered_df = df_yearmonth[\n (df_yearmonth['Date'] == '201306') & \n (df_yearmonth['Consumption'] == 214582.17)\n]\n\n# Merge with customers table to get currency\n# SQL: INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID\nmerged_df = pd.merge(filtered_df, df_customers, on='CustomerID')\n\n# Extract the Currency\n# SQL: SELECT T2.Currency\nif not merged_df.empty:\n result = merged_df['Currency'].values[0]\nelse:\n result = None\n\nprint(result)", "sql": "SELECT T2.Currency FROM yearmonth AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Date = '201306' AND T1.Consumption = 214582.17", "difficulty": "simple" }, { "question_id": 1523, "question": "Which country was the card owner of No.667467 in?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\nmerged = pd.merge(transactions_1k[transactions_1k['CardID'] == 667467], gasstations, on='GasStationID')\nresult = merged[['Country']]", "sql": "SELECT T2.Country FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.CardID = '667467'", "difficulty": "simple" }, { "question_id": 1524, "question": "What's the nationality of the customer who spent 548.4 in 2012/8/24?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-24' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Merge transactions with gasstations\nmerged = pd.merge(transactions_1k, gasstations, on='GasStationID')\n\n# Filter for the specific date and price\nfiltered = merged[(merged['Date'] == '2012-08-24') & (merged['Price'] == 548.4)]\n\n# Get the country (nationality)\nresult = filtered[['Country']]", "sql": "SELECT T2.Country FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.Date = '2012-08-24' AND T1.Price = 548.4", "difficulty": "simple" }, { "question_id": 1525, "question": "What is the percentage of the customers who used EUR in 2012/8/25?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-25' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_customers = pd.read_csv('customers.csv')\n\n# Filter for transactions on 2012-08-25\n# SQL: WHERE T1.Date = '2012-08-25'\ntransactions_on_date = df_transactions[df_transactions['Date'] == '2012-08-25']\n\n# Get unique customer IDs active on that date (Denominator)\n# SQL: COUNT(DISTINCT CustomerID)\nactive_customer_ids = transactions_on_date['CustomerID'].unique()\ntotal_active_count = len(active_customer_ids)\n\n# Filter customers table for these specific IDs to check Currency\nrelevant_customers = df_customers[df_customers['CustomerID'].isin(active_customer_ids)]\n\n# Count how many of these customers used EUR (Numerator)\n# SQL: AND T2.Currency = 'EUR'\neur_count = len(relevant_customers[relevant_customers['Currency'] == 'EUR'])\n\n# Calculate percentage\n# SQL: ... * 100 / ...\nif total_active_count > 0:\n result = (eur_count / total_active_count) * 100\nelse:\n result = 0.0\n\nprint(result)", "sql": "SELECT CAST(COUNT(DISTINCT T1.CustomerID) AS FLOAT) * 100 / (SELECT COUNT(DISTINCT CustomerID) FROM transactions_1k WHERE Date = '2012-08-25') AS percentage FROM transactions_1k AS T1 INNER JOIN customers AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Date = '2012-08-25' AND T2.Currency = 'EUR'", "difficulty": "simple" }, { "question_id": 1526, "question": "For the customer who paid 634.8 in 2012/8/25, what was the consumption decrease rate from Year 2012 to 2013?", "db_id": "debit_card_specializing", "evidence": "date '2012-08-24' in the database; ratio calculated by dividing 2012 by 8;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Filter for transactions on 2012-08-25 with price 634.8\n# SQL: WHERE Date='2012-08-25' AND Price=634.8\ntarget_trans = df_transactions[\n (df_transactions['Date'] == '2012-08-25') & \n (df_transactions['Price'] == 634.8)\n]\n\n# Get the customer IDs (Handle potential multiple customers)\n# SQL: CustomerID IN (SELECT CustomerID ...)\ntarget_customer_ids = target_trans['CustomerID'].unique()\n\n# Filter yearmonth data for these customers\n# SQL: FROM yearmonth WHERE CustomerID IN ...\ncustomer_consumption = df_yearmonth[df_yearmonth['CustomerID'].isin(target_customer_ids)].copy()\n\n# Ensure Date is string for filtering\ncustomer_consumption['Date'] = customer_consumption['Date'].astype(str)\n\n# Calculate total consumption in 2012\n# SQL: SUM(IIF(SUBSTR(Date,1,4)='2012',Consumption,0))\nconsumption_2012 = customer_consumption[\n customer_consumption['Date'].str.startswith('2012')\n]['Consumption'].sum()\n\n# Calculate total consumption in 2013\n# SQL: SUM(IIF(SUBSTR(Date,1,4)='2013',Consumption,0))\nconsumption_2013 = customer_consumption[\n customer_consumption['Date'].str.startswith('2013')\n]['Consumption'].sum()\n\n# Calculate consumption decrease rate\n# SQL: (Sum2012 - Sum2013) / Sum2012\n# Note: SQL logic does NOT multiply by 100\nif consumption_2012 != 0:\n result = (consumption_2012 - consumption_2013) / consumption_2012\nelse:\n result = 0.0\n\nprint(result)", "sql": "SELECT CAST(SUM(IIF(SUBSTR(Date,1,4)='2012',Consumption,0)) - SUM(IIF(SUBSTR(Date,1,4)='2013',Consumption,0)) AS FLOAT)/SUM(IIF(SUBSTR(Date,1,4)='2012',Consumption,0)) FROM yearmonth WHERE CustomerID IN (SELECT CustomerID FROM transactions_1k WHERE Date='2012-08-25' AND Price=634.8)", "difficulty": "challenging" }, { "question_id": 1527, "question": "Which gas station has the highest amount of revenue?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Read the CSV file\ndf_transactions = pd.read_csv('transactions_1k.csv')\n\n# Group by GasStationID and calculate total revenue (Sum of Price)\n# SQL: GROUP BY GasStationID ORDER BY SUM(Price) DESC LIMIT 1\nrevenue_by_station = df_transactions.groupby('GasStationID')['Price'].sum()\n\n# Find the GasStationID with the highest revenue\nresult = revenue_by_station.idxmax()\n\nprint(result)", "sql": "SELECT GasStationID FROM transactions_1k GROUP BY GasStationID ORDER BY SUM(Price) DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1528, "question": "What is the percentage of \"premium\" against the overall segment in Country = \"SVK\"?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# Filter for SVK country\nsvk_stations = gasstations[gasstations['Country'] == 'SVK']\n\n# Count premium stations in SVK\npremium_count = len(svk_stations[svk_stations['Segment'] == 'Premium'])\n\n# Count total stations in SVK\ntotal_count = len(svk_stations)\n\n# Calculate percentage\nif total_count > 0:\n result = (premium_count / total_count) * 100\nelse:\n result = 0", "sql": "SELECT CAST(SUM(IIF(Country = 'SVK' AND Segment = 'Premium', 1, 0)) AS FLOAT) * 100 / NULLIF(SUM(IIF(Country = 'SVK', 1, 0)),0) FROM gasstations", "difficulty": "simple" }, { "question_id": 1529, "question": "What is the amount spent by customer \"38508\" at the gas stations? How much had the customer spent in January 2012?", "db_id": "debit_card_specializing", "evidence": "value equals '201201' in the database;", "code": "import pandas as pd\n# 筛选目标客户交易记录\nfiltered = transactions_1k[transactions_1k['CustomerID'] == 38508]\n# 转换日期格式并计算月份标识\nfiltered = filtered.assign(Month=pd.to_datetime(filtered['Date']).dt.strftime('%Y%m'))\n# 计算总消费和指定月份消费\nresult = pd.DataFrame({\n 'TotalSpent': [filtered['Price'].sum()],\n 'Jan2012Spent': [filtered[filtered['Month'] == '201201']['Price'].sum()]\n})", "sql": "SELECT SUM(Price) AS TotalSpent, SUM(CASE WHEN strftime('%Y%m', Date) = '201201' THEN Price ELSE 0 END) AS Jan2012Spent FROM transactions_1k WHERE CustomerID = 38508", "difficulty": "moderate" }, { "question_id": 1530, "question": "Which are the top five best selling products? Please state the full name of them.", "db_id": "debit_card_specializing", "evidence": "Description of products contains full nameAmount refers to quantity sold", "code": "import pandas as pd\nresult = (pd.merge(transactions_1k, products, on='ProductID').groupby(['ProductID', 'Description'], as_index=False)['Amount'].sum().sort_values(by='Amount', ascending=False).head(5)['Description'])", "sql": "SELECT T2.Description FROM transactions_1k AS T1 INNER JOIN products AS T2 ON T1.ProductID = T2.ProductID GROUP BY T2.ProductID, T2.Description ORDER BY SUM(T1.Amount) DESC LIMIT 5", "difficulty": "simple" }, { "question_id": 1531, "question": "Who is the top spending customer and how much is the average price per single item purchased by this customer? What currency was being used?", "db_id": "debit_card_specializing", "evidence": "average price per single item = Total(price) / Total(amount)", "code": "import pandas as pd\n# 找出消费最高的客户ID\ntop_customer = transactions_1k.groupby('CustomerID').apply(lambda x: (x['Price'] * x['Amount']).sum()).idxmax()\n# 计算该客户的平均单价和货币\navg_price = transactions_1k[transactions_1k['CustomerID'] == top_customer]['Price'].sum() / transactions_1k[transactions_1k['CustomerID'] == top_customer]['Amount'].sum()\ncurrency = customers[customers['CustomerID'] == top_customer]['Currency'].iloc[0]\n# 构建结果\nresult = pd.DataFrame([{ 'CustomerID': top_customer, 'avg_price': avg_price, 'Currency': currency }])", "sql": "SELECT T1.CustomerID, SUM(T2.Price)/SUM(T2.Amount) AS avg_price, T1.Currency FROM customers T1 JOIN transactions_1k T2 ON T1.CustomerID = T2.CustomerID WHERE T1.CustomerID = ( SELECT CustomerID FROM transactions_1k GROUP BY CustomerID ORDER BY SUM(Price*Amount) DESC LIMIT 1 ) GROUP BY T1.CustomerID, T1.Currency", "difficulty": "moderate" }, { "question_id": 1532, "question": "Which country had the gas station that sold the most expensive product id No.2 for one unit?", "db_id": "debit_card_specializing", "evidence": "", "code": "import pandas as pd\n\n# 假设数据已存在\n# transactions_1k, gasstations 已作为DataFrame加载\n\n# 筛选产品ID为2的交易\nfiltered_trans = transactions_1k[transactions_1k['ProductID'] == 2]\n\n# 将交易数据与加油站数据连接\nmerged = pd.merge(filtered_trans, gasstations, on='GasStationID')\n\n# 按价格降序排序并取第一行的国家\nresult = merged.sort_values('Price', ascending=False).head(1)[['Country']]", "sql": "SELECT T2.Country FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T1.ProductID = 2 ORDER BY T1.Price DESC LIMIT 1", "difficulty": "simple" }, { "question_id": 1533, "question": "For all the people who paid more than 29.00 per unit of product id No.5. Give their consumption status in the August of 2012.", "db_id": "debit_card_specializing", "evidence": "August of 2012 refers to the Date value = '201208' ; Price per unit of product = Price / Amount;", "code": "import pandas as pd\n\n# Read the CSV files\ndf_transactions = pd.read_csv('transactions_1k.csv')\ndf_yearmonth = pd.read_csv('yearmonth.csv')\n\n# Filter transactions\n# Conditions:\n# 1. ProductID = 5\n# 2. Unit Price (Price / Amount) > 29.00\n# 3. Transaction Date is in August 2012 (SQL: strftime('%Y%m', T1.Date) = '201208')\n# Note: Assuming Date format in transactions_1k is 'YYYY-MM-DD'\ntarget_transactions = df_transactions[\n (df_transactions['ProductID'] == 5) & \n ((df_transactions['Price'] / df_transactions['Amount']) > 29.00) &\n (df_transactions['Date'].str.startswith('2012-08'))\n]\n\n# Get unique customer IDs from these specific transactions\ntarget_customer_ids = target_transactions['CustomerID'].unique()\n\n# Filter yearmonth data for August 2012 and these customers\n# SQL: T2.Date = '201208'\ndf_yearmonth['Date'] = df_yearmonth['Date'].astype(str)\nconsumption_data = df_yearmonth[\n (df_yearmonth['Date'] == '201208') & \n (df_yearmonth['CustomerID'].isin(target_customer_ids))\n]\n\n# Get distinct consumption values\n# SQL: SELECT DISTINCT T2.Consumption\nresult = consumption_data['Consumption'].unique().tolist()\n\nprint(result)", "sql": "SELECT DISTINCT T2.Consumption FROM transactions_1k AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Price / T1.Amount > 29.00 AND T1.ProductID = 5 AND T2.Date = '201208' AND strftime('%Y%m', T1.Date) = '201208'", "difficulty": "moderate" } ]