birdsql/bird_sql_dev_20251106 huggingface dataset:
Database: california_schools
Question: What is the complete address of the school with the lowest excellence rate? Indicate the Street, City, Zip and State.
Evidence: Excellence Rate = NumGE1500 / NumTstTakr; complete address has Street, City, State, Zip code
SQL:
SELECT T2.Street, T2.City, T2.State, T2.Zip
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;
Database: california_schools
Question: What are the webpages for the Los Angeles County school that has between 2,000 and 3,000 test takers?
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'
Database: california_schools
Question: What is the average number of test takers from Fresno schools that opened between 1/1/1980 and 12/31/1980?
Evidence: between 1/1/1980 and 12/31/1980 means the year = 1980; Fresno is a county;
SQL:
SELECT AVG(T1.NumTstTakr) FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE strftime('%Y', T2.OpenDate) = '1980' AND T2.County = 'Fresno'
Database: california_schools
Question: What is the telephone number for the school with the lowest average score in reading in Fresno Unified?
Evidence: Fresno Unified is a name of district;
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
Database: california_schools
Question: List the names of virtual schools that are among the top 5 in their respective counties based on average reading scores.
Evidence: Exclusively virtual refers to Virtual = 'F'; respective counties means PARTITION BY County
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
Database: california_schools
Question: What is the type of education offered in the school who scored the highest average in Math?
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
Database: california_schools
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?
Evidence: Average score for all subjects can be computed by (AvgScrMath + AvgScrRead + AvgScrWrite) / 3
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 AND T1.AvgScrRead IS NOT NULL AND T1.AvgScrWrite IS NOT NULL ORDER BY (T1.AvgScrMath + T1.AvgScrRead + T1.AvgScrWrite) / 3 ASC LIMIT 1
Database: california_schools
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.
SQL:
SELECT T1.AvgScrWrite, T2.City FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode ORDER BY T1.NumGE1500 DESC LIMIT 1
Database: california_schools
Question: For schools administered by Ricci Ulrich, provide a comprehensive performance analysis including their SAT scores in all three sections, total SAT score, rankings compared to other schools, FRPM eligibility rate, test participation rate, and how their writing scores compare to their district average.
Evidence: FRPM stands for Free or Reduced Price Meal. Test participation rate = (Number of Test Takers / Enrollment) * 100.
SQL:
WITH SchoolStats AS (
    SELECT 
        s.CDSCode,
        s.School,
        s.AdmFName1,
        s.AdmLName1,
        sat.AvgScrWrite,
        sat.AvgScrRead,
        sat.AvgScrMath,
        sat.NumTstTakr,
        f.`Enrollment (K-12)`,
        f.`Percent (%) Eligible FRPM (K-12)` * 100 AS FRPMPercentage,
        (sat.AvgScrWrite + sat.AvgScrRead + sat.AvgScrMath) AS TotalSATScore,
        RANK() OVER (ORDER BY sat.AvgScrWrite DESC) AS WriteScoreRank,
        RANK() OVER (ORDER BY (sat.AvgScrWrite + sat.AvgScrRead + sat.AvgScrMath) DESC) AS TotalScoreRank
    FROM schools s
    INNER JOIN satscores sat ON s.CDSCode = sat.cds
    LEFT JOIN frpm f ON s.CDSCode = f.CDSCode
    WHERE s.AdmFName1 = 'Ricci' AND s.AdmLName1 = 'Ulrich'
),
DistrictAverages AS (
    SELECT 
        s.District,
        AVG(sat.AvgScrWrite) AS DistrictAvgWriteScore,
        AVG(sat.AvgScrRead) AS DistrictAvgReadScore,
        AVG(sat.AvgScrMath) AS DistrictAvgMathScore
    FROM schools s
    INNER JOIN satscores sat ON s.CDSCode = sat.cds
    GROUP BY s.District
)

SELECT 
    ss.School,
    ss.AvgScrWrite,
    ss.AvgScrRead,
    ss.AvgScrMath,
    ss.TotalSATScore,
    ss.NumTstTakr,
    ss.`Enrollment (K-12)`,
    ss.FRPMPercentage,
    ss.WriteScoreRank,
    ss.TotalScoreRank,
    da.DistrictAvgWriteScore,
    CASE 
        WHEN ss.AvgScrWrite > da.DistrictAvgWriteScore THEN 'Above District Average'
        WHEN ss.AvgScrWrite = da.DistrictAvgWriteScore THEN 'Equal to District Average'
        ELSE 'Below District Average'
    END AS ComparisonToDistrictAvg,
    ROUND((ss.AvgScrWrite - da.DistrictAvgWriteScore), 2) AS DifferenceFromDistrictAvg,
    ROUND((ss.NumTstTakr * 100.0 / ss.`Enrollment (K-12)`), 2) AS PercentageTakingSAT
FROM SchoolStats ss
LEFT JOIN schools s ON ss.CDSCode = s.CDSCode
LEFT JOIN DistrictAverages da ON s.District = da.District
ORDER BY ss.AvgScrWrite DESC;
Database: california_schools
Question: Which state special schools have the highest number of enrollees from grades 1 through 12?
Evidence: State Special Schools are identified by DOC code 31; Grades 1 through 12 means K-12
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, T2.CDSCode ASC LIMIT 1
Database: california_schools
Question: What is the monthly average number of schools that opened in Alameda County under the jurisdiction of the Elementary School District in 1980?
Evidence: Elementary School District refers to DOC = 52; Monthly average number of schools that opened in 1980 = count(schools that opened in 1980) / 12
SQL:
SELECT CAST(COUNT(School) AS REAL) / 12 FROM schools WHERE DOC = 52 AND County = 'Alameda' AND strftime('%Y', OpenDate) = '1980'
Database: california_schools
Question: What is the ratio of merged Unified School District schools to merged Elementary School District schools in Orange County?
Evidence: Elementary School District refers to DOC = 52; Unified School District refers to DOC = 54.

Ratio refers to number of merged Unified School District schools in Orange County / number of merged Elementary School District schools
SQL:
SELECT CAST(SUM(CASE WHEN DOC = 54 THEN 1 ELSE 0 END) AS REAL) / NULLIF(SUM(CASE WHEN DOC = 52 THEN 1 ELSE 0 END),0) FROM schools WHERE StatusType = 'Merged' AND County = 'Orange'
Database: california_schools
Question: Which different county has the most number of closed schools? Please provide the name of each school as well as the closure date.
Evidence: Closure date and closed date are synonyms; 'Closed' was mentioned in schools.StatusType.
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
Database: california_schools
Question: What is the postal street address for the school with the 7th highest Math average? Indicate the school's name.
Evidence: Postal street and mailing street are synonyms.
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 6, 1
Database: california_schools
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.
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, T1.cds DESC LIMIT 1
Database: california_schools
Question: What is the total number of schools whose total SAT scores are greater or equal to 1500 whose mailing city is Lakeport?
Evidence: Total SAT scores can be computed by AvgScrRead + AvgScrMath + AvgScrWrite
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
Database: california_schools
Question: How many test takers are there at the school/s whose mailing city address is in Fresno?
SQL:
SELECT SUM(T1.NumTstTakr) FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.MailCity = 'Fresno'
Database: california_schools
Question: Please specify all of the schools and their related mailing zip codes that are under Avetik Atoian's administration.
SQL:
SELECT School, MailZip FROM schools WHERE AdmFName1 = 'Avetik' AND AdmLName1 = 'Atoian'
Database: california_schools
Question: Of all the schools with a mailing state address in California, how many are active in San Joaquin city?
SQL:
SELECT COUNT(CDSCode) FROM schools WHERE City = 'San Joaquin' AND MailState = 'CA' AND StatusType = 'Active'
Database: california_schools
Question: What is the phone number and extension number for the school that had the 333rd highest average writing score?
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
Database: california_schools
Question: What is the phone number and extension number for the school with the zip code 95203-3704? Indicate the school's name.
SQL:
SELECT Phone, Ext, School FROM schools WHERE Zip = '95203-3704'
Database: california_schools
Question: What is the website for the schools under the administrations of Mike Larson and Dante Alvarez?
SQL:
SELECT Website FROM schools WHERE (AdmFName1 = 'Mike' AND AdmLName1 = 'Larson') OR (AdmFName1 = 'Dante' AND AdmLName1 = 'Alvarez')
Database: california_schools
Question: For all partially virtual charter schools in San Joaquin County, provide a comprehensive analysis including their enrollment statistics, poverty levels based on free and reduced-price meal eligibility, SAT performance metrics, and rank them by enrollment size within the county.
Evidence: Partially virtual schools have Virtual = 'P'; Charter schools have Charter = 1; Poverty levels are categorized based on FRPM percentage: over 75% is High Poverty, 50-75% is Medium-High Poverty, 25-50% is Medium-Low Poverty, and under 25% is Low Poverty.
SQL:
WITH CharterSchoolStats AS (
    SELECT 
        s.CDSCode,
        s.Website,
        s.School,
        s.County,
        s.Charter,
        s.Virtual,
        s.CharterNum,
        s.FundingType,
        f.`Enrollment (K-12)` AS TotalEnrollment,
        f.`FRPM Count (K-12)` AS FRPMCount,
        f.`Percent (%) Eligible FRPM (K-12)` AS FRPMPercentage,
        CASE 
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.75 THEN 'High Poverty'
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.50 THEN 'Medium-High Poverty'
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.25 THEN 'Medium-Low Poverty'
            ELSE 'Low Poverty'
        END AS PovertyLevel,
        RANK() OVER (PARTITION BY s.County ORDER BY f.`Enrollment (K-12)` DESC) AS EnrollmentRank
    FROM 
        schools s
    LEFT JOIN 
        frpm f ON s.CDSCode = f.CDSCode
    WHERE 
        s.County = 'San Joaquin' 
        AND s.Virtual = 'P' 
        AND s.Charter = 1
)
SELECT 
    cs.School AS SchoolName,
    cs.Website,
    cs.CharterNum AS CharterNumber,
    cs.FundingType,
    cs.TotalEnrollment,
    cs.FRPMCount,
    ROUND(cs.FRPMPercentage * 100, 2) || '%' AS FRPMPercentage,
    cs.PovertyLevel,
    cs.EnrollmentRank,
    COALESCE(sat.NumTstTakr, 0) AS SATTestTakers,
    COALESCE(sat.AvgScrRead, 0) AS AvgReadingScore,
    COALESCE(sat.AvgScrMath, 0) AS AvgMathScore,
    COALESCE(sat.AvgScrWrite, 0) AS AvgWritingScore,
    COALESCE(sat.NumGE1500, 0) AS StudentsOver1500,
    CASE 
        WHEN sat.NumTstTakr > 0 THEN ROUND((CAST(sat.NumGE1500 AS REAL) / sat.NumTstTakr) * 100, 2) || '%'
        ELSE '0%'
    END AS PercentOver1500
FROM 
    CharterSchoolStats cs
LEFT JOIN 
    satscores sat ON cs.CDSCode = sat.cds
ORDER BY 
    cs.EnrollmentRank, 
    cs.TotalEnrollment DESC;
Database: california_schools
Question: For charter schools owned by Elementary School Districts in Hickman, what are their enrollment sizes, free and reduced price meal eligibility rates, SAT performance metrics, and how do they rank by size within the city?
Evidence: Elementary School District refers to DOC = '52'; Charter schools refers to Charter = 1; FRPM stands for Free or Reduced Price Meal program
SQL:
WITH CharterSchoolStats AS (
    SELECT 
        s.CDSCode,
        s.School,
        s.City,
        s.DOC,
        s.Charter,
        f.`Charter School Number`,
        f.`Charter Funding Type`,
        f.`Enrollment (K-12)` AS EnrollmentK12,
        f.`FRPM Count (K-12)` AS FRPMCount,
        f.`Percent (%) Eligible FRPM (K-12)` AS FRPMPercent,
        CASE 
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.75 THEN 'High FRPM'
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.50 THEN 'Medium FRPM'
            ELSE 'Low FRPM'
        END AS FRPMCategory,
        ROW_NUMBER() OVER (PARTITION BY s.City ORDER BY f.`Enrollment (K-12)` DESC) AS SizeRank
    FROM 
        schools s
    LEFT JOIN 
        frpm f ON s.CDSCode = f.CDSCode
    WHERE 
        s.DOC = '52' 
        AND s.Charter = 1
        AND s.StatusType = 'Active'
),
SATPerformance AS (
    SELECT 
        cds,
        sname,
        NumTstTakr,
        AvgScrRead,
        AvgScrMath,
        AvgScrWrite,
        (AvgScrRead + AvgScrMath + AvgScrWrite) AS TotalScore,
        CAST(NumGE1500 AS REAL) / NULLIF(NumTstTakr, 0) AS PercentOver1500
    FROM 
        satscores
    WHERE 
        rtype = 'S'
)

SELECT 
    c.CDSCode,
    c.School,
    c.City,
    c.EnrollmentK12,
    c.FRPMCount,
    c.FRPMPercent,
    c.FRPMCategory,
    c.SizeRank,
    s.NumTstTakr AS SATTestTakers,
    s.AvgScrRead AS SATReadingScore,
    s.AvgScrMath AS SATMathScore,
    s.AvgScrWrite AS SATWritingScore,
    s.TotalScore AS SATTotalScore,
    s.PercentOver1500 AS PercentOver1500,
    CASE 
        WHEN s.PercentOver1500 IS NULL THEN 'No SAT Data'
        WHEN s.PercentOver1500 > 0.5 THEN 'High Performing'
        WHEN s.PercentOver1500 > 0.25 THEN 'Average Performing'
        ELSE 'Low Performing'
    END AS SATPerformanceCategory,
    COUNT(*) OVER () AS TotalCharterSchools,
    AVG(c.EnrollmentK12) OVER () AS AvgCharterEnrollment
FROM 
    CharterSchoolStats c
LEFT JOIN 
    SATPerformance s ON c.CDSCode = s.cds
WHERE 
    c.City = 'Hickman'
ORDER BY 
    c.EnrollmentK12 DESC;
Database: california_schools
Question: For non-chartered schools in Los Angeles County with a free meal rate below 0.18%, provide details about each school including their enrollment, free meal count, exact free meal percentage, their rank within the county, and statistics about how many schools in the county fall into this low free meal category.
Evidence: non-chartered schools refer to Charter = 0; free meal rate = Free Meal Count (K-12) * 100 / Enrollment (K-12)
SQL:
WITH SchoolStats AS (
    SELECT 
        s.CDSCode,
        s.School,
        s.County,
        s.District,
        s.Charter,
        f.`Free Meal Count (K-12)`,
        f.`Enrollment (K-12)`,
        CAST(f.`Free Meal Count (K-12)` AS REAL) * 100 / f.`Enrollment (K-12)` AS FreePercent,
        f.`FRPM Count (K-12)`,
        CAST(f.`FRPM Count (K-12)` AS REAL) * 100 / f.`Enrollment (K-12)` AS FRPMPercent,
        CASE 
            WHEN CAST(f.`Free Meal Count (K-12)` AS REAL) * 100 / f.`Enrollment (K-12)` < 0.18 THEN 'Very Low'
            WHEN CAST(f.`Free Meal Count (K-12)` AS REAL) * 100 / f.`Enrollment (K-12)` < 10 THEN 'Low'
            WHEN CAST(f.`Free Meal Count (K-12)` AS REAL) * 100 / f.`Enrollment (K-12)` < 30 THEN 'Medium'
            ELSE 'High'
        END AS FreeCategory,
        ROW_NUMBER() OVER (PARTITION BY s.County ORDER BY CAST(f.`Free Meal Count (K-12)` AS REAL) * 100 / f.`Enrollment (K-12)`) AS CountyRank
    FROM 
        schools s
    INNER JOIN 
        frpm f ON s.CDSCode = f.CDSCode
    LEFT JOIN 
        satscores sat ON s.CDSCode = sat.cds
    WHERE 
        s.Charter = 0
        AND f.`Enrollment (K-12)` > 0
),
CountyStats AS (
    SELECT
        County,
        COUNT(*) AS TotalSchools,
        COUNT(CASE WHEN FreePercent < 0.18 THEN 1 END) AS LowFreeSchools,
        AVG(FreePercent) AS AvgFreePercent,
        MIN(FreePercent) AS MinFreePercent,
        MAX(FreePercent) AS MaxFreePercent
    FROM
        SchoolStats
    GROUP BY
        County
    HAVING
        COUNT(CASE WHEN FreePercent < 0.18 THEN 1 END) > 0
)

SELECT
    ss.CDSCode,
    ss.School,
    ss.District,
    ss.County,
    ss.`Enrollment (K-12)` AS Enrollment,
    ss.`Free Meal Count (K-12)` AS FreeMealCount,
    ROUND(ss.FreePercent, 4) AS FreePercentage,
    ss.FreeCategory,
    ss.CountyRank,
    cs.TotalSchools,
    cs.LowFreeSchools,
    ROUND(cs.AvgFreePercent, 4) AS CountyAvgFreePercent,
    ROUND(100.0 * cs.LowFreeSchools / cs.TotalSchools, 2) || '%' AS PctLowFreeInCounty,
    (SELECT COUNT(*) FROM SchoolStats WHERE County = 'Los Angeles' AND FreePercent < 0.18) AS LATotalLowFree
FROM
    SchoolStats ss
JOIN
    CountyStats cs ON ss.County = cs.County
WHERE
    ss.County = 'Los Angeles'
    AND ss.FreePercent < 0.18
ORDER BY
    ss.FreePercent ASC;
Database: california_schools
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
Evidence: Chartered schools refer to Charter = 1 in the table schools; Full name refers to first name, last name
SQL:
SELECT AdmFName1, AdmLName1, School, City FROM schools WHERE Charter = 1 AND CharterNum = '00D2'
Database: california_schools
Question: What is the total number of schools with a mailing city in Hickman belonging to the charter number 00D4?
SQL:
SELECT COUNT(*) FROM schools WHERE CharterNum = '00D4' AND MailCity = 'Hickman'
Database: california_schools
Question: What is the ratio in percentage of Santa Clara County charter schools that are locally funded compared to charter schools with all other types of funding?
Evidence: Ratio in percentage = (count(locally funded charter schools in Santa Clara) / count(non-locally funded charter schools in Santa Clara)) * 100%
SQL:
SELECT CAST(SUM(CASE WHEN FundingType = 'Locally funded' THEN 1 ELSE 0 END) AS REAL) * 100 / SUM(CASE WHEN FundingType != 'Locally funded' THEN 1 ELSE 0 END) FROM schools WHERE County = 'Santa Clara' AND Charter = 1
Database: california_schools
Question: For directly funded schools that opened in Stanislaus County between 2000 and 2005, provide detailed information about each school including their enrollment, free or reduced price meal eligibility rates, SAT scores, and how they compare to the county average. Also rank them by their FRPM percentage and SAT performance.
Evidence: Directly funded schools refers to FundingType = 'Directly funded'; FRPM stands for Free or Reduced Price Meal
SQL:
WITH DirectlyFundedSchools AS (
    SELECT 
        s.CDSCode,
        s.School,
        s.County,
        s.OpenDate,
        s.FundingType,
        strftime('%Y', s.OpenDate) AS OpenYear,
        f.`Charter School (Y/N)` AS IsCharter,
        f.`Enrollment (K-12)` AS Enrollment,
        f.`FRPM Count (K-12)` AS FRPMCount,
        f.`Percent (%) Eligible FRPM (K-12)` AS FRPMPercent,
        CASE 
            WHEN f.`Educational Option Type` = 'Traditional' THEN 'Traditional'
            ELSE 'Non-Traditional'
        END AS SchoolType,
        sat.AvgScrRead,
        sat.AvgScrMath,
        sat.AvgScrWrite,
        (sat.AvgScrRead + sat.AvgScrMath + sat.AvgScrWrite) AS TotalSATScore
    FROM schools s
    LEFT JOIN frpm f ON s.CDSCode = f.CDSCode
    LEFT JOIN satscores sat ON s.CDSCode = sat.cds
    WHERE strftime('%Y', s.OpenDate) BETWEEN '2000' AND '2005'
      AND s.County = 'Stanislaus'
      AND s.FundingType = 'Directly funded'
),
CountyStats AS (
    SELECT 
        County,
        COUNT(*) AS TotalSchools,
        AVG(Enrollment) AS AvgEnrollment,
        AVG(FRPMPercent) AS AvgFRPMPercent,
        AVG(TotalSATScore) AS AvgTotalSATScore,
        SUM(CASE WHEN IsCharter = 1 THEN 1 ELSE 0 END) AS CharterCount,
        SUM(CASE WHEN SchoolType = 'Traditional' THEN 1 ELSE 0 END) AS TraditionalCount
    FROM DirectlyFundedSchools
    GROUP BY County
)

SELECT 
    dfs.School,
    dfs.OpenDate,
    dfs.OpenYear,
    dfs.Enrollment,
    dfs.FRPMCount,
    dfs.FRPMPercent,
    dfs.SchoolType,
    dfs.AvgScrRead,
    dfs.AvgScrMath,
    dfs.AvgScrWrite,
    dfs.TotalSATScore,
    cs.TotalSchools AS CountyTotalSchools,
    cs.AvgEnrollment AS CountyAvgEnrollment,
    cs.AvgFRPMPercent AS CountyAvgFRPMPercent,
    CASE
        WHEN dfs.FRPMPercent > cs.AvgFRPMPercent THEN 'Above County Average'
        WHEN dfs.FRPMPercent < cs.AvgFRPMPercent THEN 'Below County Average'
        ELSE 'At County Average'
    END AS FRPMStatus,
    RANK() OVER (ORDER BY dfs.FRPMPercent DESC) AS FRPMRank,
    RANK() OVER (ORDER BY dfs.TotalSATScore DESC) AS SATScoreRank
FROM DirectlyFundedSchools dfs
JOIN CountyStats cs ON dfs.County = cs.County
ORDER BY dfs.OpenDate ASC;
Database: california_schools
Question: What is the total amount of Community College District closure in 1989 in the city of San Francisco?
SQL:
SELECT COUNT(School) FROM schools WHERE strftime('%Y', ClosedDate) = '1989' AND City = 'San Francisco' AND DOCType = 'Community College District'
Database: california_schools
Question: Which county reported the most number of school closure in the 1980s with school wonership code belonging to Youth Authority Facilities (CEA)?
Evidence: Youth Authority Facilities (CEA) refers to SOC = 11; 1980s = years between 1980 and 1989
SQL:
SELECT County
FROM (
    SELECT County, COUNT(CDSCode) as closure_count,
           DENSE_RANK() OVER (ORDER BY COUNT(CDSCode) DESC) as rank_num
    FROM schools 
    WHERE strftime('%Y', ClosedDate) BETWEEN '1980' AND '1989' 
      AND StatusType = 'Closed' 
      AND SOC = '11'
    GROUP BY County
) 
WHERE rank_num = 1
ORDER BY County ASC
Database: california_schools
Question: For State Special Schools with a School Ownership Code starting with 3, show me their NCES district ID, school name, charter status, current operational status, opening date, enrollment, poverty classification, SAT scores by subject, overall average SAT score, and enrollment ranking. Sort the results by enrollment from highest to lowest.
Evidence: State Special Schools refers to DOCType = 'State Special Schools'; School Ownership Code starting with 3 means SOC = '31' OR SOC LIKE '3%'; Poverty classification is based on Percent (%) Eligible FRPM (K-12) where >75% is High Poverty, >50% is Medium Poverty, >25% is Low Poverty, otherwise Very Low Poverty
SQL:
WITH StateSpecialSchools AS (
    SELECT 
        s.CDSCode,
        s.NCESDist,
        s.School,
        s.DOCType,
        s.SOC,
        CASE 
            WHEN s.Charter = 1 THEN 'Charter'
            ELSE 'Non-Charter'
        END AS SchoolType,
        s.OpenDate,
        s.ClosedDate,
        CASE 
            WHEN s.ClosedDate IS NULL THEN 'Active'
            ELSE 'Closed'
        END AS CurrentStatus
    FROM schools s
    WHERE s.DOCType = 'State Special Schools'
),
SchoolMetrics AS (
    SELECT 
        s.CDSCode,
        f.`Enrollment (K-12)`,
        f.`FRPM Count (K-12)`,
        f.`Percent (%) Eligible FRPM (K-12)`,
        CASE 
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.75 THEN 'High Poverty'
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.50 THEN 'Medium Poverty'
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.25 THEN 'Low Poverty'
            ELSE 'Very Low Poverty'
        END AS PovertyLevel,
        COALESCE(sat.NumTstTakr, 0) AS SATTestTakers,
        COALESCE(sat.AvgScrRead, 0) AS AvgReadingScore,
        COALESCE(sat.AvgScrMath, 0) AS AvgMathScore,
        COALESCE(sat.AvgScrWrite, 0) AS AvgWritingScore,
        COALESCE(sat.NumGE1500, 0) AS StudentsOver1500,
        RANK() OVER (ORDER BY f.`Enrollment (K-12)` DESC) AS EnrollmentRank
    FROM schools s
    LEFT JOIN frpm f ON s.CDSCode = f.CDSCode
    LEFT JOIN satscores sat ON s.CDSCode = sat.cds
    WHERE s.DOCType = 'State Special Schools'
)

SELECT 
    ss.NCESDist,
    ss.School,
    ss.SchoolType,
    ss.CurrentStatus,
    CASE 
        WHEN ss.OpenDate IS NOT NULL THEN date(ss.OpenDate)
        ELSE 'Unknown'
    END AS OpeningDate,
    sm.`Enrollment (K-12)` AS Enrollment,
    sm.PovertyLevel,
    sm.AvgReadingScore,
    sm.AvgMathScore,
    sm.AvgWritingScore,
    ROUND((sm.AvgReadingScore + sm.AvgMathScore + sm.AvgWritingScore)/3.0, 2) AS AvgTotalScore,
    sm.EnrollmentRank
FROM StateSpecialSchools ss
JOIN SchoolMetrics sm ON ss.CDSCode = sm.CDSCode
WHERE ss.SOC = '31' OR ss.SOC LIKE '3%'
ORDER BY sm.EnrollmentRank ASC;
Database: california_schools
Question: How many active and closed District Community Day Schools are there in the county of Alpine?
SQL:
SELECT COUNT(School) FROM schools WHERE (StatusType = 'Closed' OR StatusType = 'Active') AND SOC = 69 AND County = 'Alpine'
Database: california_schools
Question: What is the district code for the School that does not offer a magnet program in the city of Fresno?
Evidence: When magnet is equal to 0 in the database, it means ths school doesn't offer a magnet program.
SQL:
SELECT DISTINCT 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
Database: california_schools
Question: How many students from the ages of 5 to 17 are enrolled at the State Special School school in Fremont for the 2014-2015 academic year?
Evidence: State Special School means EdOpsCode = 'SSS'
SQL:
SELECT T1.`Enrollment (Ages 5-17)` 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` BETWEEN 2014 AND 2015
Database: california_schools
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?
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'
Database: california_schools
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?
Evidence: District Special Education Consortia School refers to EdOpsCode = 'SPECON'.
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'
Database: california_schools
Question: What is the educational level name for the schools with Breakfast Provision 2 in county code 37? Indicate the name of the school.
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
Database: california_schools
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?
Evidence: High school can be represented as EILCode = 'HS'
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'
Database: california_schools
Question: For schools in Los Angeles County that serve grades K-9, what are their poverty levels based on FRPM eligibility rates, and how do they perform on SAT tests? Include their charter status and rank them by FRPM percentage.
Evidence: Poverty level is categorized as High Poverty (≥75% FRPM), Medium Poverty (50-74% FRPM), or Low Poverty (<50% FRPM). FRPM percentage = FRPM Count (Ages 5-17) / Enrollment (Ages 5-17) * 100. Charter status can be found in Charter field where 1 = Yes and 0 = No.
SQL:
WITH SchoolStats AS (
    SELECT 
        s.CDSCode,
        s.School,
        s.County,
        s.GSserved,
        s.Charter,
        s.CharterNum,
        s.City,
        f.`FRPM Count (Ages 5-17)`,
        f.`Enrollment (Ages 5-17)`,
        f.`FRPM Count (Ages 5-17)` * 100.0 / f.`Enrollment (Ages 5-17)` AS FRPM_Percentage,
        CASE 
            WHEN f.`FRPM Count (Ages 5-17)` * 100.0 / f.`Enrollment (Ages 5-17)` >= 75 THEN 'High Poverty'
            WHEN f.`FRPM Count (Ages 5-17)` * 100.0 / f.`Enrollment (Ages 5-17)` >= 50 THEN 'Medium Poverty'
            ELSE 'Low Poverty'
        END AS Poverty_Level
    FROM schools AS s
    INNER JOIN frpm AS f ON s.CDSCode = f.CDSCode
    WHERE s.County = 'Los Angeles' AND s.GSserved = 'K-9'
),
SAT_Performance AS (
    SELECT 
        ss.cds,
        ss.NumTstTakr,
        ss.AvgScrRead,
        ss.AvgScrMath,
        ss.AvgScrWrite,
        ss.AvgScrRead + ss.AvgScrMath + ss.AvgScrWrite AS Total_SAT_Score,
        RANK() OVER (ORDER BY ss.AvgScrRead + ss.AvgScrMath + ss.AvgScrWrite DESC) AS SAT_Rank
    FROM satscores AS ss
    WHERE ss.rtype = 'S'
)
SELECT 
    ss.School,
    ss.City,
    ss.FRPM_Percentage AS "Percent (%) Eligible FRPM (Ages 5-17)",
    ss.Poverty_Level,
    CASE WHEN ss.Charter = 1 THEN 'Yes (' || ss.CharterNum || ')' ELSE 'No' END AS Is_Charter,
    sp.NumTstTakr AS "Number of SAT Test Takers",
    sp.AvgScrRead AS "Avg Reading Score",
    sp.AvgScrMath AS "Avg Math Score",
    sp.AvgScrWrite AS "Avg Writing Score",
    sp.Total_SAT_Score AS "Total SAT Score",
    sp.SAT_Rank AS "SAT Ranking",
    ROUND(ss.`FRPM Count (Ages 5-17)`, 0) AS "FRPM Count",
    ROUND(ss.`Enrollment (Ages 5-17)`, 0) AS "Enrollment"
FROM SchoolStats ss
LEFT JOIN SAT_Performance sp ON ss.CDSCode = sp.cds
ORDER BY ss.FRPM_Percentage DESC;
Database: california_schools
Question: For the most common grade span served in Adelanto, what are the enrollment statistics, poverty levels, and average SAT scores across all active schools?
Evidence: Poverty level is categorized as High (>75% FRPM eligible), Medium (50-75% FRPM eligible), or Low (<50% FRPM eligible). FRPM refers to Free or Reduced Price Meal program eligibility.
SQL:
WITH SchoolsByGradeSpan AS (
    SELECT 
        s.GSserved,
        COUNT(s.CDSCode) AS school_count,
        RANK() OVER (ORDER BY COUNT(s.CDSCode) DESC) AS grade_span_rank
    FROM 
        schools s
    WHERE 
        s.City = 'Adelanto'
    GROUP BY 
        s.GSserved
),
SchoolStats AS (
    SELECT 
        s.GSserved,
        s.School,
        f.`Enrollment (K-12)`,
        f.`FRPM Count (K-12)`,
        f.`Percent (%) Eligible FRPM (K-12)`,
        CASE 
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.75 THEN 'High Poverty'
            WHEN f.`Percent (%) Eligible FRPM (K-12)` > 0.50 THEN 'Medium Poverty'
            ELSE 'Low Poverty'
        END AS poverty_level,
        sat.AvgScrRead,
        sat.AvgScrMath,
        sat.AvgScrWrite
    FROM 
        schools s
    LEFT JOIN 
        frpm f ON s.CDSCode = f.CDSCode
    LEFT JOIN 
        satscores sat ON s.CDSCode = sat.cds
    WHERE 
        s.City = 'Adelanto' AND
        s.StatusType = 'Active'
)
SELECT 
    sbs.GSserved AS most_common_grade_span,
    sbs.school_count,
    COUNT(ss.School) AS active_schools,
    AVG(ss.`Enrollment (K-12)`) AS avg_enrollment,
    SUM(ss.`Enrollment (K-12)`) AS total_enrollment,
    AVG(ss.`Percent (%) Eligible FRPM (K-12)`) AS avg_frpm_percentage,
    COUNT(CASE WHEN ss.poverty_level = 'High Poverty' THEN 1 END) AS high_poverty_schools,
    COUNT(CASE WHEN ss.poverty_level = 'Medium Poverty' THEN 1 END) AS medium_poverty_schools,
    COUNT(CASE WHEN ss.poverty_level = 'Low Poverty' THEN 1 END) AS low_poverty_schools,
    AVG(ss.AvgScrRead) AS avg_reading_score,
    AVG(ss.AvgScrMath) AS avg_math_score,
    AVG(ss.AvgScrWrite) AS avg_writing_score
FROM 
    SchoolsByGradeSpan sbs
JOIN 
    SchoolStats ss ON sbs.GSserved = ss.GSserved
WHERE 
    sbs.grade_span_rank = 1
GROUP BY 
    sbs.GSserved, sbs.school_count;
Database: california_schools
Question: For fully virtual schools in San Diego and Santa Barbara counties, which county has the most virtual schools? Provide comprehensive statistics including the count, breakdown of charter vs regular schools, enrollment figures, average free/reduced meal percentage, average SAT scores, and identify the largest virtual school by enrollment.
Evidence: Fully virtual schools refer to schools where Virtual = 'F'. Charter schools are identified by Charter School (Y/N) = 1. FRPM refers to Free or Reduced Price Meal program eligibility.
SQL:
WITH VirtualSchoolsByCounty AS (
    SELECT 
        s.County,
        s.School,
        s.Virtual,
        s.SOCType,
        s.GSoffered,
        CASE 
            WHEN f.`Charter School (Y/N)` = 1 THEN 'Charter School'
            ELSE 'Regular School'
        END AS SchoolType,
        f.`Enrollment (K-12)` AS Enrollment,
        f.`FRPM Count (K-12)` AS FRPMCount,
        ROUND(f.`Percent (%) Eligible FRPM (K-12)` * 100, 2) AS FRPMPercentage,
        sat.NumTstTakr AS SATTestTakers,
        sat.AvgScrRead + sat.AvgScrMath + sat.AvgScrWrite AS TotalSATScore,
        ROW_NUMBER() OVER (PARTITION BY s.County ORDER BY f.`Enrollment (K-12)` DESC) AS EnrollmentRank
    FROM schools s
    LEFT JOIN frpm f ON s.CDSCode = f.CDSCode
    LEFT JOIN satscores sat ON s.CDSCode = sat.cds
    WHERE s.County IN ('San Diego', 'Santa Barbara')
    AND s.Virtual = 'F'
),
CountyStats AS (
    SELECT
        County,
        COUNT(*) AS TotalVirtualSchools,
        AVG(Enrollment) AS AvgEnrollment,
        MAX(Enrollment) AS MaxEnrollment,
        MIN(Enrollment) AS MinEnrollment,
        SUM(CASE WHEN SchoolType = 'Charter School' THEN 1 ELSE 0 END) AS CharterCount,
        SUM(CASE WHEN SchoolType = 'Regular School' THEN 1 ELSE 0 END) AS RegularCount,
        AVG(FRPMPercentage) AS AvgFRPMPercentage,
        AVG(TotalSATScore) AS AvgSATScore
    FROM VirtualSchoolsByCounty
    GROUP BY County
),
RankedCounties AS (
    SELECT
        County,
        TotalVirtualSchools,
        AvgEnrollment,
        MaxEnrollment,
        MinEnrollment,
        CharterCount,
        RegularCount,
        AvgFRPMPercentage,
        AvgSATScore,
        RANK() OVER (ORDER BY TotalVirtualSchools DESC, AvgEnrollment DESC) AS CountyRank
    FROM CountyStats
)

SELECT 
    r.County,
    r.TotalVirtualSchools AS amount,
    r.CharterCount AS CharterSchools,
    r.RegularCount AS RegularSchools,
    ROUND(r.AvgEnrollment, 2) AS AverageEnrollment,
    r.MaxEnrollment AS HighestEnrollment,
    r.MinEnrollment AS LowestEnrollment,
    ROUND(r.AvgFRPMPercentage, 2) || '%' AS AvgFreeReducedMealPercentage,
    ROUND(r.AvgSATScore, 2) AS AverageSATScore,
    (SELECT School FROM VirtualSchoolsByCounty v WHERE v.County = r.County AND EnrollmentRank = 1) AS LargestVirtualSchool
FROM RankedCounties r
WHERE r.CountyRank = 1;
Database: california_schools
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.
SQL:
SELECT T1.`School Type`, T1.`School Name`, T2.Latitude FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode ORDER BY T2.Latitude DESC, T1.CDSCode ASC LIMIT 1
Database: california_schools
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.
Evidence: State of California refers to state = 'CA'
SQL:
SELECT T2.City, T1.`Low Grade`, T1.`School Name` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.State = 'CA' ORDER BY T2.Latitude ASC LIMIT 1
Database: california_schools
Question: What is the grade span offered in the school with the highest longitude?
Evidence: the highest longitude refers to the school with the maximum absolute longitude value.
SQL:
SELECT GSoffered FROM schools ORDER BY ABS(longitude) DESC LIMIT 1
Database: california_schools
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.
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'
SQL:
SELECT T2.City, COUNT(T2.CDSCode) FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.Magnet = 1 AND T2.GSoffered = 'K-8' AND T1.`NSLP Provision Status` = 'Multiple Provision Types' GROUP BY T2.City
Database: california_schools
Question: What are the two most common first names among the school administrators? Indicate the district to which they administer.
SQL:
SELECT DISTINCT T1.AdmFName1, T1.District 
FROM schools AS T1 
INNER JOIN (
    SELECT admfname1 
    FROM schools 
    GROUP BY admfname1 
    ORDER BY COUNT(admfname1) DESC, admfname1 ASC
    LIMIT 2
) AS T2 
ON T1.AdmFName1 = T2.admfname1;
Database: california_schools
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.
Evidence: Percent (%) Eligible Free (K-12) = `Free Meal Count (K-12)` / `Enrollment (K-12)` * 100%
SQL:
SELECT 
    T1.`Free Meal Count (K-12)` * 100 / T1.`Enrollment (K-12)` AS "Percent (%) Eligible Free (K-12)",
    T1.`District Code` 
FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode 
WHERE T2.AdmFName1 = 'Alusine' OR T2.AdmFName2 = 'Alusine' OR T2.AdmFName3 = 'Alusine'
Database: california_schools
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.
SQL:
SELECT AdmLName1, District, County, School FROM schools WHERE CharterNum = '0040'
Database: california_schools
Question: What are the valid e-mail addresses of the administrator of the school located in the San Bernardino county, City of San Bernardino that belongs to a Unified School District and opened between 1/1/2009 to 12/31/2010 whose school types are public Intermediate/Middle Schools?
Evidence: Intermediate/Middle Schools refers to SOC = '62'; Unified School District refers to DOC = '54'; years between 2009 and 2010 can refer to 'between 1/1/2009 to 12/31/2010'
SQL:
SELECT AdmEmail1, AdmEmail2 FROM schools WHERE County = 'San Bernardino' AND City = 'San Bernardino' AND DOC = 54 AND strftime('%Y', OpenDate) BETWEEN '2009' AND '2010' AND SOC = 62
Database: california_schools
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.
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, T1.cds ASC LIMIT 1
Database: financial
Question: How many accounts who choose issuance after transaction are staying in East Bohemia region?
Evidence: A3 contains the data of region; 'POPLATEK PO OBRATU' represents for 'issuance after transaction'.
SQL:
SELECT COUNT(T2.account_id) FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id WHERE T1.A3 = 'east Bohemia' AND T2.frequency = 'POPLATEK PO OBRATU'
Database: financial
Question: How many accounts who have region in Prague are eligible for loans?
Evidence: A3 contains the data of region
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'
Database: financial
Question: The average unemployment ratio of 1995 and 1996, which one has higher percentage?
Evidence: A12 refers to unemploymant rate 1995; A13 refers to unemploymant rate 1996
SQL:
SELECT IIF(AVG(A13) > AVG(A12), '1996', '1995') AS higher_year FROM district;
Database: financial
Question: What are the overall statistics for female clients in districts where the average salary is between 6,000 and 10,000, ranking in the top 3 for salary within their region, having at least 5 female clients, and with active loan accounts?
Evidence: Average salary refers to A11; Female refers to gender = 'F'; Loan status: 'A' = active, 'B' = completed, 'C' = defaulted
SQL:
WITH DistrictStats AS (
    SELECT 
        d.district_id,
        d.A2 AS district_name,
        d.A3 AS region,
        d.A11 AS avg_salary,
        COUNT(DISTINCT c.client_id) AS female_clients,
        AVG(CAST(strftime('%Y', 'now') - strftime('%Y', c.birth_date) AS INTEGER)) AS avg_age,
        RANK() OVER (PARTITION BY d.A3 ORDER BY d.A11 DESC) AS salary_rank_in_region
    FROM 
        district d
    JOIN 
        client c ON d.district_id = c.district_id
    WHERE 
        c.gender = 'F'
    GROUP BY 
        d.district_id, d.A2, d.A3, d.A11
    HAVING 
        d.A11 BETWEEN 6000 AND 10000
),
AccountActivity AS (
    SELECT 
        a.district_id,
        COUNT(DISTINCT a.account_id) AS total_accounts,
        COUNT(DISTINCT l.loan_id) AS total_loans,
        ROUND(AVG(l.amount), 2) AS avg_loan_amount,
        SUM(CASE WHEN l.status = 'A' THEN 1 ELSE 0 END) AS active_loans,
        SUM(CASE WHEN l.status = 'B' THEN 1 ELSE 0 END) AS completed_loans,
        SUM(CASE WHEN l.status = 'C' THEN 1 ELSE 0 END) AS defaulted_loans
    FROM 
        account a
    LEFT JOIN 
        loan l ON a.account_id = l.account_id
    JOIN 
        disp d ON a.account_id = d.account_id
    JOIN 
        client c ON d.client_id = c.client_id
    WHERE 
        c.gender = 'F'
    GROUP BY 
        a.district_id
)
SELECT 
    COUNT(DISTINCT ds.district_id) AS district_count,
    SUM(ds.female_clients) AS total_female_clients,
    ROUND(AVG(ds.avg_salary), 2) AS average_female_salary,
    ROUND(AVG(ds.avg_age), 1) AS average_female_age,
    SUM(aa.total_accounts) AS total_female_accounts,
    SUM(aa.total_loans) AS total_female_loans,
    ROUND(AVG(aa.avg_loan_amount), 2) AS average_female_loan_amount,
    SUM(aa.active_loans) AS active_female_loans,
    SUM(aa.completed_loans) AS completed_female_loans,
    SUM(aa.defaulted_loans) AS defaulted_female_loans,
    GROUP_CONCAT(DISTINCT ds.region) AS regions_represented
FROM 
    DistrictStats ds
JOIN 
    AccountActivity aa ON ds.district_id = aa.district_id
WHERE 
    ds.salary_rank_in_region <= 3
    AND ds.female_clients >= 5
    AND aa.total_loans > 0;
Database: financial
Question: How many male customers who are living in North Bohemia have average salary greater than 8000?
Evidence: Male means that gender = 'M'; A3 refers to region; A11 pertains to average salary.
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;
Database: financial
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?
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.
SQL:
SELECT T1.account_id,
       (SELECT MAX(A11) - MIN(A11) FROM district)
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.district_id = (
  SELECT district_id FROM client WHERE gender = 'F' ORDER BY birth_date ASC LIMIT 1
)
ORDER BY T2.A11 DESC
LIMIT 1;
Database: financial
Question: List out the account numbers of clients who are youngest and have highest average salary?
Evidence: If the person A's birthdate < B's birthdate, it means that person B is younger than person A; A11 refers to average salary
SQL:
SELECT T1.account_id 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 T1.district_id = T4.district_id WHERE T3.client_id = ( SELECT T3.client_id FROM client AS T3 INNER JOIN disp AS T2 ON T3.client_id = T2.client_id INNER JOIN account AS T1 ON T2.account_id = T1.account_id INNER JOIN district AS T4 ON T1.district_id = T4.district_id WHERE T3.birth_date = (SELECT MAX(birth_date) FROM client) ORDER BY T4.A11, T3.client_id DESC LIMIT 1)
Database: financial
Question: What is the demographic breakdown and financial profile of account owners who receive weekly statements, segmented by gender, age group, and region?
Evidence: Weekly statements refers to frequency = 'POPLATEK TYDNE'; age groups are defined as Young (under 30), Middle-aged (30-50), and Senior (over 50); PRIJEM represents income transactions and VYDAJ represents expense transactions.
SQL:
WITH CustomerWeeklyStatements AS (
    SELECT 
        T2.client_id,
        T1.account_id,
        T1.district_id,
        T1.date AS account_open_date,
        COUNT(DISTINCT T3.card_id) AS num_cards
    FROM 
        account AS T1
    INNER JOIN 
        disp AS T2 ON T1.account_id = T2.account_id
    LEFT JOIN
        card AS T3 ON T2.disp_id = T3.disp_id
    WHERE 
        T2.type = 'OWNER' 
        AND T1.frequency = 'POPLATEK TYDNE'
    GROUP BY
        T2.client_id, T1.account_id, T1.district_id, T1.date
),
ClientInfo AS (
    SELECT 
        c.client_id,
        c.gender,
        c.birth_date,
        CASE
            WHEN strftime('%Y', 'now') - strftime('%Y', c.birth_date) - (strftime('%m-%d', 'now') < strftime('%m-%d', c.birth_date)) < 30 THEN 'Young'
            WHEN strftime('%Y', 'now') - strftime('%Y', c.birth_date) - (strftime('%m-%d', 'now') < strftime('%m-%d', c.birth_date)) BETWEEN 30 AND 50 THEN 'Middle-aged'
            ELSE 'Senior'
        END AS age_group,
        d.A2 AS district_name,
        d.A3 AS region
    FROM 
        client c
    JOIN 
        district d ON c.district_id = d.district_id
),
LoanAndTransactionData AS (
    SELECT 
        cws.client_id,
        COUNT(DISTINCT l.loan_id) AS num_loans,
        COALESCE(SUM(l.amount), 0) AS total_loan_amount,
        COALESCE(MAX(l.amount), 0) AS max_loan_amount,
        COUNT(DISTINCT t.trans_id) AS num_transactions,
        COALESCE(SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END), 0) AS total_income,
        COALESCE(SUM(CASE WHEN t.type = 'VYDAJ' THEN t.amount ELSE 0 END), 0) AS total_expense
    FROM 
        CustomerWeeklyStatements cws
    LEFT JOIN 
        loan l ON cws.account_id = l.account_id
    LEFT JOIN 
        trans t ON cws.account_id = t.account_id
    GROUP BY 
        cws.client_id
)

SELECT 
    COUNT(DISTINCT cws.client_id) AS total_weekly_owners,
    ci.gender,
    ci.age_group,
    ci.region,
    ROUND(AVG(cws.num_cards), 2) AS avg_cards_per_customer,
    ROUND(AVG(ltd.num_loans), 2) AS avg_loans_per_customer,
    ROUND(AVG(ltd.total_loan_amount), 2) AS avg_loan_amount,
    ROUND(AVG(ltd.num_transactions), 2) AS avg_transactions,
    ROUND(AVG(ltd.total_income - ltd.total_expense), 2) AS avg_net_balance,
    COUNT(DISTINCT CASE WHEN ltd.num_loans > 0 THEN cws.client_id END) AS customers_with_loans,
    ROUND(COUNT(DISTINCT CASE WHEN ltd.num_loans > 0 THEN cws.client_id END) * 100.0 / COUNT(DISTINCT cws.client_id), 2) AS percent_with_loans
FROM 
    CustomerWeeklyStatements cws
JOIN 
    ClientInfo ci ON cws.client_id = ci.client_id
JOIN 
    LoanAndTransactionData ltd ON cws.client_id = ltd.client_id
GROUP BY 
    ci.gender, ci.age_group, ci.region
ORDER BY 
    total_weekly_owners DESC;