birdsql/bird_sql_dev_20251106 huggingface dataset:
Database: financial
Question: For all disponent clients with accounts that have post-transaction issuance statements, provide a comprehensive profile including their loan statistics, transaction activity, credit card information, and categorize them based on their service usage, ranked by transaction volume.
Evidence: Post-transaction issuance refers to frequency = 'POPLATEK PO OBRATU'. Disponent refers to disposition type = 'DISPONENT'. Status 'A' indicates active loans while 'B' indicates completed loans.
SQL:
WITH ClientLoanInfo AS (
    SELECT 
        d.client_id,
        d.type AS disposition_type,
        a.frequency,
        COUNT(l.loan_id) AS loan_count,
        AVG(l.amount) 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
    FROM disp d
    JOIN account a ON d.account_id = a.account_id
    LEFT JOIN loan l ON a.account_id = l.account_id
    WHERE a.frequency = 'POPLATEK PO OBRATU' AND d.type = 'DISPONENT'
    GROUP BY d.client_id, d.type, a.frequency
),
ClientTransactions AS (
    SELECT 
        d.client_id,
        COUNT(t.trans_id) AS transaction_count,
        SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END) AS total_income,
        SUM(CASE WHEN t.type = 'VYDAJ' THEN t.amount ELSE 0 END) AS total_expense,
        MAX(t.date) AS last_transaction_date
    FROM disp d
    JOIN account a ON d.account_id = a.account_id
    JOIN trans t ON a.account_id = t.account_id
    WHERE a.frequency = 'POPLATEK PO OBRATU' AND d.type = 'DISPONENT'
    GROUP BY d.client_id
),
ClientCards AS (
    SELECT
        d.client_id,
        COUNT(c.card_id) AS card_count,
        GROUP_CONCAT(DISTINCT c.type) AS card_types
    FROM disp d
    JOIN account a ON d.account_id = a.account_id
    LEFT JOIN card c ON d.disp_id = c.disp_id
    WHERE a.frequency = 'POPLATEK PO OBRATU' AND d.type = 'DISPONENT'
    GROUP BY d.client_id
)
SELECT 
    cli.client_id,
    c.gender,
    c.birth_date,
    d.A2 AS district_name,
    d.A3 AS region,
    cli.loan_count,
    cli.avg_loan_amount,
    cli.active_loans,
    cli.completed_loans,
    ct.transaction_count,
    ct.total_income,
    ct.total_expense,
    ct.total_income - ct.total_expense AS net_balance,
    ct.last_transaction_date,
    cc.card_count,
    cc.card_types,
    CASE 
        WHEN cli.loan_count > 0 AND cc.card_count > 0 THEN 'Full Service Client'
        WHEN cli.loan_count > 0 THEN 'Loan Only Client'
        WHEN cc.card_count > 0 THEN 'Card Only Client'
        ELSE 'Basic Client'
    END AS client_category,
    RANK() OVER (ORDER BY ct.transaction_count DESC) AS transaction_rank
FROM ClientLoanInfo cli
JOIN client c ON cli.client_id = c.client_id
JOIN district d ON c.district_id = d.district_id
LEFT JOIN ClientTransactions ct ON cli.client_id = ct.client_id
LEFT JOIN ClientCards cc ON cli.client_id = cc.client_id
ORDER BY transaction_rank, cli.client_id;
Database: financial
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.
Evidence: 'POPLATEK TYDNE' stands for weekly issuance
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
Database: financial
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.
Evidence: Loan validity more than 12 months refers to duration > 12
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
Database: financial
Question: What is the average age at account opening, total number with loans, number with successfully completed loans, and number currently in debt for female clients born before 1950 from Sokolov who own accounts? Also, what are the earliest and latest years these accounts were opened?
Evidence: Female refers to gender = 'F'; Sokolov is a district name in column A2; loan status 'A' means contract finished with no problems, 'D' means running contract with client in debt; only account owners are considered
SQL:
WITH female_clients_from_sokolov AS (
    SELECT 
        c.client_id,
        c.birth_date,
        STRFTIME('%Y', c.birth_date) AS birth_year,
        d.A2 AS district_name
    FROM 
        client c
    INNER JOIN 
        district d ON c.district_id = d.district_id
    WHERE 
        c.gender = 'F' 
        AND STRFTIME('%Y', c.birth_date) < '1950' 
        AND d.A2 = 'Sokolov'
),
client_accounts AS (
    SELECT 
        fc.client_id,
        fc.birth_year,
        a.account_id,
        a.date AS account_open_date,
        STRFTIME('%Y', a.date) AS account_open_year,
        CAST(STRFTIME('%Y', 'now') AS INTEGER) - CAST(fc.birth_year AS INTEGER) AS client_age_now,
        CAST(STRFTIME('%Y', a.date) AS INTEGER) - CAST(fc.birth_year AS INTEGER) AS client_age_at_opening
    FROM 
        female_clients_from_sokolov fc
    INNER JOIN 
        disp d ON fc.client_id = d.client_id
    INNER JOIN 
        account a ON d.account_id = a.account_id
    WHERE 
        d.type = 'OWNER'
),
client_loan_status AS (
    SELECT 
        ca.client_id,
        ca.account_id,
        ca.birth_year,
        ca.account_open_date,
        ca.client_age_at_opening,
        CASE 
            WHEN l.loan_id IS NOT NULL THEN 'Has Loan'
            ELSE 'No Loan'
        END AS loan_status,
        CASE
            WHEN l.status = 'A' THEN 'Contract Finished/No Problems'
            WHEN l.status = 'B' THEN 'Contract Finished/Loan Not Paid'
            WHEN l.status = 'C' THEN 'Running Contract/OK So Far'
            WHEN l.status = 'D' THEN 'Running Contract/Client in Debt'
            ELSE 'No Loan'
        END AS loan_details
    FROM 
        client_accounts ca
    LEFT JOIN 
        loan l ON ca.account_id = l.account_id
)
SELECT 
    COUNT(DISTINCT cls.client_id) AS total_female_clients,
    AVG(cls.client_age_at_opening) AS avg_age_at_account_opening,
    SUM(CASE WHEN cls.loan_status = 'Has Loan' THEN 1 ELSE 0 END) AS clients_with_loans,
    SUM(CASE WHEN cls.loan_details = 'Contract Finished/No Problems' THEN 1 ELSE 0 END) AS clients_with_good_loans,
    SUM(CASE WHEN cls.loan_details = 'Running Contract/Client in Debt' THEN 1 ELSE 0 END) AS clients_with_debt,
    MIN(STRFTIME('%Y', cls.account_open_date)) AS earliest_account_year,
    MAX(STRFTIME('%Y', cls.account_open_date)) AS latest_account_year
FROM 
    client_loan_status cls;
Database: financial
Question: List out the accounts who have the earliest trading date in 1995 ?
SQL:
SELECT DISTINCT account_id
FROM trans
WHERE STRFTIME('%Y', date) = '1995'
  AND date = (SELECT MIN(date) FROM trans WHERE STRFTIME('%Y', date) = '1995')
ORDER BY account_id ASC;
Database: financial
Question: State different accounts who have account opening date before 1997 and own an amount of money greater than 3000USD
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
Database: financial
Question: For all clients who received their credit card on March 3rd, 1994, provide a comprehensive profile including their personal information, banking activity, loan history, and district characteristics. Categorize them as borrowers based on their age and loan status, and rank them by age within their gender group.
Evidence: Active loans refers to status = 'A'. Young borrower means age at card issue is less than 30 years old with at least one loan. Mature borrower means age at card issue is 30 or older with at least one loan.
SQL:
WITH ClientCardInfo AS (
    SELECT 
        c.client_id,
        c.gender,
        c.birth_date,
        cd.issued,
        cd.type AS card_type,
        STRFTIME('%Y', c.birth_date) AS birth_year,
        STRFTIME('%Y', cd.issued) - STRFTIME('%Y', c.birth_date) AS age_at_card_issue
    FROM client c
    JOIN disp d ON c.client_id = d.client_id
    JOIN card cd ON d.disp_id = cd.disp_id
    WHERE cd.issued = '1994-03-03'
),
ClientAccountInfo AS (
    SELECT 
        c.client_id,
        COUNT(DISTINCT a.account_id) AS account_count,
        SUM(CASE WHEN l.loan_id IS NOT NULL THEN 1 ELSE 0 END) AS loan_count,
        SUM(CASE WHEN l.status = 'A' THEN 1 ELSE 0 END) AS active_loans,
        AVG(CASE WHEN l.loan_id IS NOT NULL THEN l.amount ELSE NULL END) AS avg_loan_amount
    FROM client c
    JOIN disp d ON c.client_id = d.client_id
    JOIN account a ON d.account_id = a.account_id
    LEFT JOIN loan l ON a.account_id = l.account_id
    GROUP BY c.client_id
),
ClientDistrictInfo AS (
    SELECT 
        c.client_id,
        d.A2 AS district_name,
        d.A3 AS region,
        d.A11 AS avg_salary,
        d.A14 AS entrepreneurs_per_1000
    FROM client c
    JOIN district d ON c.district_id = d.district_id
)

SELECT 
    ci.client_id,
    ci.gender,
    ci.birth_date,
    ci.card_type,
    ci.age_at_card_issue,
    cai.account_count,
    cai.loan_count,
    cai.active_loans,
    cai.avg_loan_amount,
    cdi.district_name,
    cdi.region,
    cdi.avg_salary,
    CASE 
        WHEN cai.loan_count > 0 AND ci.age_at_card_issue < 30 THEN 'Young borrower'
        WHEN cai.loan_count > 0 AND ci.age_at_card_issue >= 30 THEN 'Mature borrower'
        ELSE 'Non-borrower'
    END AS borrower_category,
    RANK() OVER (PARTITION BY ci.gender ORDER BY ci.age_at_card_issue) AS age_rank_by_gender
FROM ClientCardInfo ci
JOIN ClientAccountInfo cai ON ci.client_id = cai.client_id
JOIN ClientDistrictInfo cdi ON ci.client_id = cdi.client_id
ORDER BY ci.client_id;
Database: financial
Question: For the transaction of 840 on October 14, 1998, provide detailed information about the account including when it was opened, how long it had been open, the account owner's gender and age at the time, the total number of transactions up to that date, how many cards were issued, and whether the account had a loan before this transaction.
Evidence: Transaction date is 1998-10-14 and transaction amount is 840. Account owner refers to disposition type = 'OWNER'.
SQL:
WITH TransactionDetails AS (
    SELECT 
        t.account_id,
        t.amount,
        t.date AS transaction_date,
        t.type,
        t.operation,
        t.balance,
        t.k_symbol,
        a.date AS account_opening_date,
        a.frequency,
        d.district_id,
        d.A2 AS district_name,
        d.A3 AS region,
        ROW_NUMBER() OVER (PARTITION BY t.account_id ORDER BY t.date) AS transaction_rank
    FROM trans t
    JOIN account a ON t.account_id = a.account_id
    JOIN district d ON a.district_id = d.district_id
    WHERE t.amount = 840 AND t.date = '1998-10-14'
),
AccountOwners AS (
    SELECT 
        disp.account_id,
        client.client_id,
        client.gender,
        client.birth_date,
        CASE
            WHEN client.gender = 'M' THEN 'Male'
            WHEN client.gender = 'F' THEN 'Female'
            ELSE 'Unknown'
        END AS gender_full,
        CAST(strftime('%Y', '1998-10-14') AS INTEGER) - CAST(strftime('%Y', client.birth_date) AS INTEGER) - 
            CASE 
                WHEN strftime('%m%d', '1998-10-14') < strftime('%m%d', client.birth_date) THEN 1 
                ELSE 0 
            END AS age_at_transaction,
        disp.type AS disposition_type
    FROM disp
    JOIN client ON disp.client_id = client.client_id
    WHERE disp.type = 'OWNER'
)

SELECT 
    td.account_id,
    td.account_opening_date,
    td.transaction_date,
    CAST(julianday(td.transaction_date) - julianday(td.account_opening_date) AS INTEGER) AS days_account_open_before_transaction,
    td.amount,
    td.balance,
    td.district_name,
    td.region,
    ao.client_id,
    ao.gender_full,
    ao.age_at_transaction,
    (SELECT COUNT(*) FROM trans WHERE account_id = td.account_id AND date <= td.transaction_date) AS total_transactions_to_date,
    (SELECT COUNT(*) FROM card c JOIN disp d ON c.disp_id = d.disp_id WHERE d.account_id = td.account_id) AS cards_issued,
    CASE 
        WHEN EXISTS (SELECT 1 FROM loan WHERE account_id = td.account_id AND date <= td.transaction_date) THEN 'Yes'
        ELSE 'No'
    END AS has_loan_before_transaction
FROM TransactionDetails td
LEFT JOIN AccountOwners ao ON td.account_id = ao.account_id
ORDER BY td.account_opening_date;
Database: financial
Question: For the loan approved on August 25, 1994, provide a comprehensive profile including: the district information (name, region, average salary rank, unemployment rank), how long the account was open before the loan, the demographics of clients in that district (total count, gender breakdown, average age), and the account's transaction history (number of transactions and total income) before the loan date.
Evidence: Income transactions refer to type = 'PRIJEM'. Average age is calculated as of the loan date 1994-08-25.
SQL:
WITH LoanAccounts AS (
    SELECT 
        T2.account_id,
        T2.date AS loan_date,
        T1.district_id,
        T1.date AS account_open_date,
        JULIANDAY(T2.date) - JULIANDAY(T1.date) AS days_since_account_opened
    FROM 
        account AS T1 
    INNER JOIN 
        loan AS T2 ON T1.account_id = T2.account_id
    WHERE 
        T2.date = '1994-08-25'
),
DistrictInfo AS (
    SELECT 
        d.district_id,
        d.A2 AS district_name,
        d.A3 AS region,
        d.A11 AS avg_salary,
        d.A12 AS unemployment_rate_1995,
        RANK() OVER (ORDER BY d.A11 DESC) AS salary_rank,
        RANK() OVER (ORDER BY d.A12) AS unemployment_rank
    FROM 
        district d
    INNER JOIN 
        LoanAccounts la ON d.district_id = la.district_id
),
ClientsInDistrict AS (
    SELECT 
        d.district_id,
        COUNT(DISTINCT c.client_id) AS num_clients,
        SUM(CASE WHEN c.gender = 'M' THEN 1 ELSE 0 END) AS male_clients,
        SUM(CASE WHEN c.gender = 'F' THEN 1 ELSE 0 END) AS female_clients,
        AVG(JULIANDAY('1994-08-25') - JULIANDAY(c.birth_date))/365.25 AS avg_client_age
    FROM 
        client c
    INNER JOIN 
        district d ON c.district_id = d.district_id
    GROUP BY 
        d.district_id
)
SELECT 
    la.district_id,
    di.district_name,
    di.region,
    la.account_open_date,
    la.days_since_account_opened AS days_account_open_before_loan,
    di.avg_salary,
    di.unemployment_rate_1995,
    di.salary_rank,
    di.unemployment_rank,
    cid.num_clients,
    cid.male_clients,
    cid.female_clients,
    cid.avg_client_age,
    (SELECT COUNT(*) FROM trans t WHERE t.account_id = la.account_id AND t.date < '1994-08-25') AS transactions_before_loan,
    (SELECT SUM(amount) FROM trans t WHERE t.account_id = la.account_id AND t.date < '1994-08-25' AND t.type = 'PRIJEM') AS total_income_before_loan
FROM 
    LoanAccounts la
LEFT JOIN 
    DistrictInfo di ON la.district_id = di.district_id
LEFT JOIN 
    ClientsInDistrict cid ON la.district_id = cid.district_id
ORDER BY 
    la.district_id;
Database: financial
Question: For the client who received a credit card on October 21, 1996, what are the complete details of their largest transaction, including their personal information, district details, and any associated loans or orders?
Evidence: Card issued date refers to issued = '1996-10-21'; largest transaction refers to MAX(amount)
SQL:
WITH TransactionStats AS (
    SELECT 
        T4.account_id,
        T4.trans_id,
        T4.amount,
        T4.type,
        T4.date,
        T4.balance,
        RANK() OVER (PARTITION BY T4.account_id ORDER BY T4.amount DESC) as amount_rank
    FROM trans AS T4
),
ClientCards AS (
    SELECT 
        T2.client_id,
        T3.account_id,
        T1.card_id,
        T1.issued,
        T1.type as card_type,
        T5.gender,
        T5.birth_date,
        (strftime('%Y', 'now') - strftime('%Y', T5.birth_date)) - 
            (strftime('%m-%d', 'now') < strftime('%m-%d', T5.birth_date)) as client_age
    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 client AS T5 ON T2.client_id = T5.client_id
    WHERE T1.issued = '1996-10-21'
),
DistrictInfo AS (
    SELECT 
        d.district_id,
        d.A2 as district_name,
        d.A3 as region,
        d.A11 as avg_salary,
        d.A12 as unemployment_rate_95
    FROM district d
)

SELECT 
    cc.client_id,
    cc.card_id,
    cc.card_type,
    cc.gender,
    cc.client_age,
    di.district_name,
    di.region,
    ts.trans_id,
    ts.amount as largest_transaction_amount,
    ts.type as transaction_type,
    ts.date as transaction_date,
    ts.balance as balance_after_transaction,
    CASE 
        WHEN ts.amount > 10000 THEN 'High Value'
        WHEN ts.amount > 5000 THEN 'Medium Value'
        ELSE 'Low Value'
    END as transaction_category,
    CASE 
        WHEN l.loan_id IS NOT NULL THEN 'Has Loan'
        ELSE 'No Loan'
    END as loan_status,
    l.amount as loan_amount,
    o.order_id,
    o.bank_to
FROM ClientCards cc
JOIN TransactionStats ts ON cc.account_id = ts.account_id AND ts.amount_rank = 1
JOIN client c ON cc.client_id = c.client_id
JOIN DistrictInfo di ON c.district_id = di.district_id
LEFT JOIN loan l ON cc.account_id = l.account_id
LEFT JOIN "order" o ON cc.account_id = o.account_id
ORDER BY ts.amount DESC
LIMIT 1
Database: financial
Question: What is the gender of the oldest client who opened his/her account in the highest average salary branch?
Evidence: Earlier birthdate refers to older age; A11 refers to average salary
SQL:
SELECT T2.gender FROM district AS T1 INNER JOIN client AS T2 ON T1.district_id = T2.district_id ORDER BY T1.A11 DESC, T2.birth_date ASC LIMIT 1
Database: financial
Question: For the client who applied the biggest loan, what was his/her first amount of transaction after opened the account?
SQL:
WITH max_loan_account AS (
    SELECT l.account_id, a.date AS account_open_date
    FROM loan l
    JOIN account a ON l.account_id = a.account_id
    ORDER BY l.amount DESC
    LIMIT 1
)
SELECT t.amount
FROM trans t
JOIN max_loan_account m ON t.account_id = m.account_id
WHERE t.date >= m.account_open_date
ORDER BY t.date ASC
LIMIT 1
Database: financial
Question: How many clients opened their accounts in Jesenik branch were women?
Evidence: A2 has region names; Woman and female share the same meaning; female refers to gender = 'F'
SQL:
SELECT COUNT(DISTINCT client.client_id)
FROM client
INNER JOIN disp ON client.client_id = disp.client_id
INNER JOIN account ON disp.account_id = account.account_id
INNER JOIN district ON account.district_id = district.district_id
WHERE client.gender = 'F' AND district.A2 = 'Jesenik' AND disp.type = 'OWNER'
Database: financial
Question: What is the disposition id of the client who made 5100 USD transaction in 1998/9/2?
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
Database: financial
Question: For the female client born on January 29, 1976, provide a comprehensive analysis of all her owned accounts including their locations, transaction activity, financial products, and regional economic indicators.
Evidence: PRIJEM refers to incoming transactions (credits), VYDAJ refers to outgoing transactions (debits). Account district refers to the district where the account was opened, which may differ from the client's residence district.
SQL:
WITH female_client AS (
    SELECT 
        c.client_id, 
        c.birth_date, 
        c.district_id,
        d.A2 AS district_name
    FROM client c
    JOIN district d ON c.district_id = d.district_id
    WHERE c.birth_date = '1976-01-29' AND c.gender = 'F'
),
client_accounts AS (
    SELECT 
        fc.client_id,
        fc.district_name AS residence_district,
        a.account_id,
        a.date AS account_open_date,
        d2.A2 AS account_district,
        d2.A3 AS account_region,
        CASE 
            WHEN fc.district_id = a.district_id THEN 'Same as residence'
            ELSE 'Different from residence'
        END AS district_comparison,
        ROW_NUMBER() OVER (PARTITION BY fc.client_id ORDER BY a.date) AS account_order
    FROM female_client fc
    JOIN disp dp ON fc.client_id = dp.client_id
    JOIN account a ON dp.account_id = a.account_id
    JOIN district d2 ON a.district_id = d2.district_id
    WHERE dp.type = 'OWNER'
),
account_transactions AS (
    SELECT
        ca.client_id,
        ca.account_id,
        ca.account_district,
        COUNT(t.trans_id) AS transaction_count,
        SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END) AS total_income,
        SUM(CASE WHEN t.type = 'VYDAJ' THEN t.amount ELSE 0 END) AS total_expense,
        MAX(t.balance) AS max_balance,
        COUNT(DISTINCT t.k_symbol) AS distinct_transaction_types
    FROM client_accounts ca
    LEFT JOIN trans t ON ca.account_id = t.account_id
    GROUP BY ca.client_id, ca.account_id, ca.account_district
)

SELECT 
    ca.residence_district,
    ca.account_district,
    ca.district_comparison,
    ca.account_open_date,
    at.transaction_count,
    at.total_income,
    at.total_expense,
    at.max_balance,
    (SELECT COUNT(*) FROM loan l WHERE l.account_id = ca.account_id) AS loan_count,
    (SELECT COUNT(*) FROM card c JOIN disp d ON c.disp_id = d.disp_id WHERE d.account_id = ca.account_id) AS card_count,
    d.A3 AS region,
    d.A10 AS urban_ratio,
    d.A11 AS avg_salary,
    d.A14 AS entrepreneurs_per_1000
FROM client_accounts ca
JOIN account_transactions at ON ca.account_id = at.account_id
JOIN district d ON ca.account_district = d.A2
ORDER BY ca.account_open_date;
Database: financial
Question: For the client who applied for a 98832 USD loan on January 3rd, 1996, provide a comprehensive profile including their birthday, age at the time of loan application, location, transaction history before the loan, expense-to-income ratio, balance range, credit card information, and number of previous loans.
Evidence: PRIJEM refers to incoming transactions (credits), VYDAJ refers to outgoing transactions (debits). Expense to income ratio is calculated as (total expenses / total income) * 100.
SQL:
WITH LoanClient AS (
    SELECT 
        T1.loan_id,
        T1.account_id,
        T1.date AS loan_date,
        T1.amount,
        T1.duration,
        T1.payments,
        T1.status,
        T4.client_id,
        T4.birth_date,
        T4.gender,
        T4.district_id AS client_district_id,
        T2.district_id AS account_district_id,
        CAST(strftime('%Y', T1.date) AS INTEGER) - CAST(strftime('%Y', T4.birth_date) AS INTEGER) - 
            CASE WHEN strftime('%m%d', T1.date) < strftime('%m%d', T4.birth_date) THEN 1 ELSE 0 END AS age_at_loan
    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 AND T3.type = 'OWNER'
    INNER JOIN client AS T4 ON T3.client_id = T4.client_id
    WHERE T1.date = '1996-01-03' AND T1.amount = 98832
),
ClientTransactions AS (
    SELECT 
        LC.client_id,
        LC.birth_date,
        LC.age_at_loan,
        COUNT(DISTINCT t.trans_id) AS transaction_count,
        SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END) AS total_income,
        SUM(CASE WHEN t.type = 'VYDAJ' THEN t.amount ELSE 0 END) AS total_expense,
        MAX(t.balance) AS max_balance,
        MIN(t.balance) AS min_balance,
        d.A2 AS district_name,
        d.A3 AS region
    FROM LoanClient LC
    JOIN account a ON LC.account_id = a.account_id
    LEFT JOIN trans t ON a.account_id = t.account_id AND t.date < LC.loan_date
    LEFT JOIN district d ON LC.client_district_id = d.district_id
    GROUP BY LC.client_id, LC.birth_date, LC.age_at_loan, d.A2, d.A3
),
CardInfo AS (
    SELECT 
        LC.client_id,
        COUNT(DISTINCT c.card_id) AS card_count,
        GROUP_CONCAT(DISTINCT c.type) AS card_types
    FROM LoanClient LC
    JOIN disp d ON LC.client_id = d.client_id
    LEFT JOIN card c ON d.disp_id = c.disp_id
    GROUP BY LC.client_id
)
SELECT 
    CT.birth_date,
    CT.age_at_loan,
    CT.district_name,
    CT.region,
    CT.transaction_count,
    CT.total_income,
    CT.total_expense,
    CASE 
        WHEN CT.total_income > 0 THEN ROUND((CT.total_expense * 100.0) / CT.total_income, 2)
        ELSE 0 
    END AS expense_to_income_ratio,
    CT.max_balance,
    CT.min_balance,
    COALESCE(CI.card_count, 0) AS card_count,
    COALESCE(CI.card_types, 'None') AS card_types,
    (SELECT COUNT(*) FROM loan l 
     JOIN account a ON l.account_id = a.account_id
     JOIN disp d ON a.account_id = d.account_id
     WHERE d.client_id = CT.client_id AND l.date < '1996-01-03') AS previous_loans
FROM ClientTransactions CT
LEFT JOIN CardInfo CI ON CT.client_id = CI.client_id
ORDER BY CT.birth_date;
Database: financial
Question: For the first client who opened his/her account in Prague, what is his/her account ID?
Evidence: A3 stands for region names
SQL:
SELECT T1.account_id
FROM account AS T1
INNER JOIN district AS T2 ON T1.district_id = T2.district_id
WHERE T2.A3 = 'Prague'
ORDER BY T1.date ASC
LIMIT 1;
Database: financial
Question: What is the district name, number of inhabitants, total number of clients, number of male clients, and percentage of male clients for the most populated district in the south Bohemia region?
Evidence: Percentage of male clients = (number of male clients / total number of clients) * 100. Male refers to gender = 'M'. A3 is the region name, A2 is the district name, and A4 contains the number of inhabitants.
SQL:
WITH RegionStats AS (
    SELECT 
        d.district_id,
        d.A3 AS region,
        CAST(d.A4 AS INTEGER) AS inhabitants,
        COUNT(DISTINCT c.client_id) AS total_clients,
        SUM(CASE WHEN c.gender = 'M' THEN 1 ELSE 0 END) AS male_clients,
        RANK() OVER (PARTITION BY d.A3 ORDER BY CAST(d.A4 AS INTEGER) DESC) AS population_rank
    FROM 
        district d
    LEFT JOIN 
        client c ON d.district_id = c.district_id
    WHERE 
        d.A3 = 'south Bohemia'
    GROUP BY 
        d.district_id, d.A3, d.A4
)
SELECT 
    rs.district_id,
    d.A2 AS district_name,
    rs.region,
    rs.inhabitants,
    rs.total_clients,
    rs.male_clients,
    CASE 
        WHEN rs.total_clients > 0 THEN ROUND((rs.male_clients * 100.0 / rs.total_clients), 2)
        ELSE 0 
    END AS pct_male
FROM 
    RegionStats rs
JOIN 
    district d ON rs.district_id = d.district_id
WHERE 
    rs.population_rank = 1
ORDER BY 
    rs.inhabitants DESC, rs.district_id
LIMIT 1;
Database: financial
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?
Evidence: Increase rate of his/her account balance = [(balance of date A - balance of date B) / balance of Date B] * 100%
SQL:
SELECT CAST((SUM(IIF(T3.date = '1998-12-27', T3.balance, 0)) - SUM(IIF(T3.date = '1993-03-22', T3.balance, 0))) AS REAL) * 100 / SUM(IIF(T3.date = '1993-03-22', T3.balance, 0)) FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN trans AS T3 ON T3.account_id = T2.account_id WHERE T1.date = '1993-07-05'
Database: financial
Question: For each region, what percentage of the total loan amount has been fully paid without issues, and what percentage of loans were successfully completed? Also include the average interest paid on successful loans compared to all loans.
Evidence: Loan paid with no issue refers to status = 'A'; Interest paid = (monthly payments * duration) - loan amount; Percentage = (amount with status 'A' / total amount) * 100%
SQL:
WITH LoansByDistrict AS (
    SELECT 
        d.A2 AS district_name,
        d.A3 AS region,
        l.status,
        l.amount,
        l.duration,
        l.payments,
        a.frequency,
        strftime('%Y', l.date) AS loan_year,
        CASE 
            WHEN c.gender = 'M' THEN 'Male'
            WHEN c.gender = 'F' THEN 'Female'
            ELSE 'Unknown'
        END AS gender,
        ROUND((l.payments * l.duration) - l.amount, 2) AS interest_paid
    FROM 
        loan l
    JOIN 
        account a ON l.account_id = a.account_id
    JOIN 
        district d ON a.district_id = d.district_id
    JOIN 
        disp di ON a.account_id = di.account_id AND di.type = 'OWNER'
    JOIN 
        client c ON di.client_id = c.client_id
),
RegionSummary AS (
    SELECT
        region,
        SUM(CASE WHEN status = 'A' THEN amount ELSE 0 END) AS paid_amount,
        SUM(amount) AS total_amount,
        COUNT(CASE WHEN status = 'A' THEN 1 END) AS successful_loans,
        COUNT(*) AS total_loans,
        ROUND(AVG(CASE WHEN status = 'A' THEN interest_paid END), 2) AS avg_interest_paid_successful,
        ROUND(AVG(interest_paid), 2) AS avg_interest_paid_all
    FROM 
        LoansByDistrict
    GROUP BY 
        region
)
SELECT 
    region,
    ROUND((CAST(paid_amount AS REAL) * 100) / total_amount, 2) AS paid_amount_percentage,
    ROUND((CAST(successful_loans AS REAL) * 100) / total_loans, 2) AS successful_loans_percentage,
    successful_loans,
    total_loans,
    paid_amount,
    total_amount,
    avg_interest_paid_successful,
    avg_interest_paid_all,
    (SELECT ROUND((CAST(SUM(CASE WHEN status = 'A' THEN amount ELSE 0 END) AS REAL) * 100) / SUM(amount), 2) FROM loan) AS overall_percentage
FROM 
    RegionSummary
ORDER BY 
    paid_amount_percentage DESC;
Database: financial
Question: For loans under $100,000, what is the percentage of loans running with no issues in each region and loan size category, and how does each region's performance compare to the overall average?
Evidence: Status = 'C' means running contract with no issues; Small loans are under $50,000, Medium loans are $50,000-$99,999; Percentage is calculated by dividing loans with status 'C' by total loans and multiplying by 100
SQL:
WITH LoanStatusByRegion AS (
    SELECT 
        d.A3 AS region,
        l.status,
        l.amount,
        l.duration,
        CASE 
            WHEN l.status = 'C' THEN 1
            ELSE 0
        END AS is_running_ok,
        CASE 
            WHEN l.amount < 50000 THEN 'Small'
            WHEN l.amount < 100000 THEN 'Medium'
            ELSE 'Large'
        END AS loan_size_category
    FROM 
        loan l
    JOIN 
        account a ON l.account_id = a.account_id
    JOIN 
        district d ON a.district_id = d.district_id
    WHERE 
        l.amount < 100000
),
RegionalStats AS (
    SELECT 
        region,
        loan_size_category,
        COUNT(status) AS total_loans,
        SUM(is_running_ok) AS running_ok_loans,
        CAST(SUM(is_running_ok) AS REAL) * 100 / COUNT(status) AS percentage_running_ok,
        AVG(amount) AS avg_loan_amount,
        AVG(duration) AS avg_duration
    FROM 
        LoanStatusByRegion
    GROUP BY 
        region, loan_size_category
),
OverallStats AS (
    SELECT 
        loan_size_category,
        COUNT(status) AS total_loans,
        SUM(is_running_ok) AS running_ok_loans,
        CAST(SUM(is_running_ok) AS REAL) * 100 / COUNT(status) AS percentage_running_ok
    FROM 
        LoanStatusByRegion
    GROUP BY 
        loan_size_category
)
SELECT 
    r.region,
    r.loan_size_category,
    r.total_loans,
    r.running_ok_loans,
    ROUND(r.percentage_running_ok, 2) AS percentage_running_ok,
    ROUND(r.avg_loan_amount, 2) AS avg_loan_amount,
    r.avg_duration,
    ROUND(o.percentage_running_ok, 2) AS overall_percentage,
    ROUND(r.percentage_running_ok - o.percentage_running_ok, 2) AS diff_from_overall
FROM 
    RegionalStats r
JOIN 
    OverallStats o ON r.loan_size_category = o.loan_size_category
ORDER BY 
    r.region, r.loan_size_category;
Database: financial
Question: From Year 1995 to 2000, who are the accounts holders from 'east Bohemia'. State the account ID the frequency of statement issuance.
Evidence: Accounts holder refers to the person who own this account.
SQL:
SELECT T1.account_id, T1.frequency FROM account AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T2.A3 = 'east Bohemia' AND STRFTIME('%Y', T1.date) BETWEEN '1995' AND '2000'
Database: financial
Question: For loan ID 4990, provide a comprehensive profile including the borrower's demographics, loan details with status description, district economic indicators, and how this loan ranks among other loans in the same district.
Evidence: Status descriptions: A = Running - OK, B = Running - Issues, C = Finished - No Issues, D = Finished - Issues. Problematic loans are those with status B or D. District information includes A2 for district name, A3 for region, A11 for average salary, and A12 for unemployment rate in 1995.
SQL:
WITH LoanStats AS (
  SELECT 
    l.loan_id,
    l.account_id,
    l.amount,
    l.duration,
    l.status,
    CASE
      WHEN l.status = 'A' THEN 'Running - OK'
      WHEN l.status = 'B' THEN 'Running - Issues'
      WHEN l.status = 'C' THEN 'Finished - No Issues'
      WHEN l.status = 'D' THEN 'Finished - Issues'
      ELSE 'Unknown'
    END AS status_description,
    a.district_id,
    ROUND(l.amount / l.duration, 2) AS avg_monthly_payment,
    RANK() OVER (PARTITION BY a.district_id ORDER BY l.amount DESC) AS district_loan_rank
  FROM loan AS l
  JOIN account AS a ON l.account_id = a.account_id
),
DistrictStats AS (
  SELECT
    d.district_id,
    d.A2 AS district_name,
    d.A3 AS region,
    d.A11 AS avg_salary,
    d.A12 AS unemployment_rate_1995,
    COUNT(DISTINCT l.loan_id) AS total_loans,
    AVG(l.amount) AS avg_loan_amount,
    SUM(CASE WHEN l.status IN ('B', 'D') THEN 1 ELSE 0 END) AS problematic_loans
  FROM district AS d
  LEFT JOIN account AS a ON d.district_id = a.district_id
  LEFT JOIN loan AS l ON a.account_id = l.account_id
  GROUP BY d.district_id, d.A2, d.A3, d.A11, d.A12
)
SELECT
  ls.loan_id,
  d.A2 AS district_name,
  d.A3 AS region,
  c.gender,
  DATE(c.birth_date) AS birth_date,
  ls.amount AS loan_amount,
  ls.duration AS loan_duration_months,
  ls.status_description,
  d.A11 AS district_avg_salary,
  d.A12 AS unemployment_rate_1995,
  ds.total_loans AS district_total_loans,
  ds.avg_loan_amount AS district_avg_loan_amount,
  ds.problematic_loans AS district_problematic_loans,
  ls.district_loan_rank,
  (SELECT COUNT(*) FROM trans AS t WHERE t.account_id = a.account_id) AS total_transactions
FROM LoanStats AS ls
JOIN account AS a ON ls.account_id = a.account_id
JOIN district AS d ON ls.district_id = d.district_id
JOIN DistrictStats AS ds ON d.district_id = ds.district_id
JOIN disp AS dp ON a.account_id = dp.account_id AND dp.type = 'OWNER'
JOIN client AS c ON dp.client_id = c.client_id
WHERE ls.loan_id = 4990
Database: financial
Question: For accounts with loans exceeding $300,000 in districts where the average salary is above the national average, show me the account details including district, region, loan statistics, account owner demographics, income classification, transaction activity, savings ratio, and how they rank within their region by maximum loan amount. Only include accounts with positive net income or no transaction history, and limit results to the top 100 by maximum loan amount.
Evidence: Average salary refers to A11 in the district table. Income categories are classified as High Income (total income > 1,000,000), Medium Income (total income > 500,000), or Low Income (otherwise). PRIJEM represents incoming transactions and VYDAJ represents outgoing transactions. Savings ratio is calculated as (total income - total expense) / total income.
SQL:
WITH LoanStatistics AS (
    SELECT 
        account_id,
        AVG(amount) AS avg_loan_amount,
        MAX(amount) AS max_loan_amount,
        COUNT(*) AS loan_count
    FROM loan
    GROUP BY account_id
    HAVING MAX(amount) > 300000
),
ClientDetails AS (
    SELECT 
        c.client_id,
        c.gender,
        CAST(strftime('%Y', 'now') AS INTEGER) - CAST(strftime('%Y', c.birth_date) AS INTEGER) AS age,
        d.account_id,
        d.type AS disposition_type
    FROM client c
    JOIN disp d ON c.client_id = d.client_id
    WHERE d.type = 'OWNER'
),
TransactionSummary AS (
    SELECT 
        account_id,
        SUM(CASE WHEN type = 'PRIJEM' THEN amount ELSE 0 END) AS total_income,
        SUM(CASE WHEN type = 'VYDAJ' THEN amount ELSE 0 END) AS total_expense,
        COUNT(*) AS transaction_count
    FROM trans
    GROUP BY account_id
)

SELECT 
    a.account_id,
    d.A2 AS district_name,
    d.A3 AS region_name,
    ls.max_loan_amount,
    ls.avg_loan_amount,
    ls.loan_count,
    cd.gender,
    cd.age,
    CASE 
        WHEN ts.total_income > 1000000 THEN 'High Income'
        WHEN ts.total_income > 500000 THEN 'Medium Income'
        ELSE 'Low Income'
    END AS income_category,
    ts.transaction_count,
    ROUND((ts.total_income - ts.total_expense) * 1.0 / CASE WHEN ts.total_income = 0 THEN 1 ELSE ts.total_income END, 2) AS savings_ratio,
    RANK() OVER (PARTITION BY d.A3 ORDER BY ls.max_loan_amount DESC) AS region_loan_rank
FROM account a
INNER JOIN district d ON a.district_id = d.district_id
INNER JOIN LoanStatistics ls ON a.account_id = ls.account_id
LEFT JOIN ClientDetails cd ON a.account_id = cd.account_id
LEFT JOIN TransactionSummary ts ON a.account_id = ts.account_id
WHERE d.A11 > (SELECT AVG(A11) FROM district)
  AND (ts.total_income > ts.total_expense OR ts.total_income IS NULL)
ORDER BY ls.max_loan_amount DESC, region_name, district_name
LIMIT 100;
Database: financial
Question: For 60-month loans, show me the top 3 largest loans in each district, including the district's average salary, loan details, client demographics, transaction history, and calculated interest rate. Order the results by highest average salary and loan amount.
Evidence: A2 refers to district name; A11 refers to average salary; loan status: A = Finished - OK, B = Finished - Default, C = Running - OK, D = Running - Default; interest rate is calculated as (total payments - loan amount) / loan amount * 100
SQL:
WITH LoanStatistics AS (
  SELECT 
    T3.loan_id,
    T2.A2 AS district_name,
    T2.A11 AS avg_salary,
    T3.amount,
    T3.duration,
    T3.payments,
    T3.status,
    T3.account_id,
    ROW_NUMBER() OVER (PARTITION BY T2.A2 ORDER BY T3.amount DESC) AS district_loan_rank
  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
),
ClientInfo AS (
  SELECT 
    d.account_id,
    COUNT(DISTINCT c.client_id) AS num_clients,
    SUM(CASE WHEN c.gender = 'M' THEN 1 ELSE 0 END) AS male_clients,
    SUM(CASE WHEN c.gender = 'F' THEN 1 ELSE 0 END) AS female_clients,
    AVG(CAST(strftime('%Y', 'now') AS INTEGER) - CAST(strftime('%Y', c.birth_date) AS INTEGER)) AS avg_client_age
  FROM disp d
  JOIN client c ON d.client_id = c.client_id
  GROUP BY d.account_id
),
TransactionSummary AS (
  SELECT
    account_id,
    COUNT(*) AS total_transactions,
    SUM(CASE WHEN type = 'PRIJEM' THEN amount ELSE 0 END) AS total_incoming,
    SUM(CASE WHEN type = 'VYDAJ' THEN amount ELSE 0 END) AS total_outgoing
  FROM trans
  GROUP BY account_id
)
SELECT 
  ls.loan_id,
  ls.district_name,
  ls.avg_salary,
  ls.amount AS loan_amount,
  ls.payments AS monthly_payment,
  ls.status AS loan_status,
  ls.district_loan_rank,
  CASE 
    WHEN ls.status = 'A' THEN 'Finished - OK'
    WHEN ls.status = 'B' THEN 'Finished - Default'
    WHEN ls.status = 'C' THEN 'Running - OK'
    WHEN ls.status = 'D' THEN 'Running - Default'
    ELSE 'Unknown'
  END AS status_description,
  ci.num_clients,
  ci.male_clients,
  ci.female_clients,
  ci.avg_client_age,
  ts.total_transactions,
  ts.total_incoming,
  ts.total_outgoing,
  (ts.total_incoming - ts.total_outgoing) AS account_balance,
  ROUND((ls.payments * ls.duration * 1.0 - ls.amount) / ls.amount * 100, 2) AS interest_rate_percent
FROM LoanStatistics ls
LEFT JOIN ClientInfo ci ON ls.account_id = ci.account_id
LEFT JOIN TransactionSummary ts ON ls.account_id = ts.account_id
WHERE ls.district_loan_rank <= 3
ORDER BY ls.avg_salary DESC, ls.amount DESC;
Database: financial
Question: For loan contracts which are still running where clients are in debt, list the district and state the percentage unemployment rate increment from 1995 to 1996.
Evidence: Unemployment increment rate in percentage = [(unemployment rate 1996 - unemployment rate 1995) / unemployment rate 2015] * 100; unemployment rate 1995 appears in the A12; unemployment rate 1996 appears in the A13; Loan contracts which are still running where client are in debt can be presented as status = 'D'
SQL:
SELECT DISTINCT T3.A2 AS district_name, CAST((T3.A13 - T3.A12) AS REAL) * 100 / NULLIF(T3.A12,0) AS unemployment_increment FROM loan 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.status = 'D' ORDER BY district_name ASC
Database: financial
Question: For accounts opened in 1993, provide a monthly breakdown showing the percentage of accounts from Decin district, average transaction statistics, and indicate whether each month's Decin percentage is above, below, or equal to the overall yearly average.
Evidence: A2 refers to district name. PRIJEM refers to income transactions and VYDAJ refers to expense transactions.
SQL:
WITH AccountsOpenedIn1993 AS (
    SELECT 
        a.account_id,
        a.district_id,
        d.A2 AS district_name,
        STRFTIME('%m', a.date) AS opening_month
    FROM 
        account a
    JOIN 
        district d ON a.district_id = d.district_id
    WHERE 
        STRFTIME('%Y', a.date) = '1993'
),
AccountsWithTransactions AS (
    SELECT 
        a.account_id,
        a.district_name,
        a.opening_month,
        COUNT(t.trans_id) AS transaction_count,
        SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END) AS total_income,
        SUM(CASE WHEN t.type = 'VYDAJ' THEN t.amount ELSE 0 END) AS total_expense
    FROM 
        AccountsOpenedIn1993 a
    LEFT JOIN 
        trans t ON a.account_id = t.account_id
    GROUP BY 
        a.account_id, a.district_name, a.opening_month
),
MonthlyStats AS (
    SELECT 
        opening_month,
        COUNT(*) AS accounts_count,
        SUM(CASE WHEN district_name = 'Decin' THEN 1 ELSE 0 END) AS decin_accounts_count,
        AVG(transaction_count) AS avg_transactions,
        AVG(total_income) AS avg_income,
        AVG(total_expense) AS avg_expense
    FROM 
        AccountsWithTransactions
    GROUP BY 
        opening_month
)
SELECT 
    opening_month,
    accounts_count,
    decin_accounts_count,
    CAST(decin_accounts_count AS REAL) * 100 / accounts_count AS decin_percentage,
    avg_transactions,
    avg_income,
    avg_expense,
    (SELECT CAST(SUM(CASE WHEN district_name = 'Decin' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) 
     FROM AccountsWithTransactions) AS overall_decin_percentage,
    CASE 
        WHEN CAST(decin_accounts_count AS REAL) * 100 / accounts_count > 
             (SELECT CAST(SUM(CASE WHEN district_name = 'Decin' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) 
              FROM AccountsWithTransactions)
        THEN 'Above Average'
        WHEN CAST(decin_accounts_count AS REAL) * 100 / accounts_count = 
             (SELECT CAST(SUM(CASE WHEN district_name = 'Decin' THEN 1 ELSE 0 END) AS REAL) * 100 / COUNT(*) 
              FROM AccountsWithTransactions)
        THEN 'Average'
        ELSE 'Below Average'
    END AS comparison_to_overall
FROM 
    MonthlyStats
ORDER BY 
    opening_month;
Database: financial
Question: For accounts with monthly statement issuance, provide a comprehensive financial profile including client demographics, transaction activity, loan details, and rankings by transaction volume and cash flow performance.
Evidence: Monthly statement issuance refers to frequency = 'POPLATEK MESICNE'. Net cash flow is calculated as total income minus total expense. Active loans have status 'A' and completed loans have status 'B'.
SQL:
WITH MonthlyAccounts AS (
  SELECT 
    account_id, 
    district_id, 
    date AS account_open_date
  FROM 
    account 
  WHERE 
    frequency = 'POPLATEK MESICNE'
),
AccountTransactions AS (
  SELECT 
    ma.account_id,
    COUNT(t.trans_id) AS transaction_count,
    SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END) AS total_income,
    SUM(CASE WHEN t.type = 'VYDAJ' THEN t.amount ELSE 0 END) AS total_expense,
    MAX(t.balance) AS max_balance,
    MIN(t.balance) AS min_balance
  FROM 
    MonthlyAccounts ma
  LEFT JOIN 
    trans t ON ma.account_id = t.account_id
  GROUP BY 
    ma.account_id
),
AccountLoans AS (
  SELECT 
    ma.account_id,
    COUNT(l.loan_id) AS loan_count,
    SUM(l.amount) AS total_loan_amount,
    AVG(l.duration) AS avg_loan_duration,
    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
  FROM 
    MonthlyAccounts ma
  LEFT JOIN 
    loan l ON ma.account_id = l.account_id
  GROUP BY 
    ma.account_id
)
SELECT 
  ma.account_id,
  d.A2 AS district_name,
  d.A3 AS region,
  ma.account_open_date,
  COUNT(DISTINCT c.client_id) AS client_count,
  ROUND(AVG(JULIANDAY('now') - JULIANDAY(c.birth_date))/365.25, 1) AS avg_client_age,
  at.transaction_count,
  at.total_income,
  at.total_expense,
  at.total_income - at.total_expense AS net_cash_flow,
  at.max_balance,
  at.min_balance,
  al.loan_count,
  al.total_loan_amount,
  al.avg_loan_duration,
  al.active_loans,
  al.completed_loans,
  COUNT(DISTINCT o.order_id) AS order_count,
  COUNT(DISTINCT card.card_id) AS card_count,
  RANK() OVER (ORDER BY at.transaction_count DESC) AS transaction_rank,
  RANK() OVER (ORDER BY (at.total_income - at.total_expense) DESC) AS cash_flow_rank
FROM 
  MonthlyAccounts ma
JOIN 
  district d ON ma.district_id = d.district_id
LEFT JOIN 
  disp ON ma.account_id = disp.account_id
LEFT JOIN 
  client c ON disp.client_id = c.client_id
LEFT JOIN 
  AccountTransactions at ON ma.account_id = at.account_id
LEFT JOIN 
  AccountLoans al ON ma.account_id = al.account_id
LEFT JOIN 
  "order" o ON ma.account_id = o.account_id
LEFT JOIN 
  card ON disp.disp_id = card.disp_id
GROUP BY 
  ma.account_id, d.A2, d.A3, ma.account_open_date, at.transaction_count, 
  at.total_income, at.total_expense, at.max_balance, at.min_balance,
  al.loan_count, al.total_loan_amount, al.avg_loan_duration, 
  al.active_loans, al.completed_loans
ORDER BY 
  transaction_rank, cash_flow_rank;
Database: financial
Question: List the top nine districts, by descending order, from the highest to the lowest, the number of female account holders.
Evidence: A2 refers to districts; Female refers to gender = 'F'
SQL:
SELECT T2.A2, COUNT(T1.client_id) FROM client AS T1 INNER JOIN district AS T2 ON T1.district_id = T2.district_id WHERE T1.gender = 'F' GROUP BY T2.district_id, T2.A2 ORDER BY COUNT(T1.client_id) DESC LIMIT 9
Database: financial
Question: Which are the top ten withdrawals (non-credit card) by district names for the month of January 1996?
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 names
SQL:
SELECT 
    T1.A2 AS district_name,  
    SUM(T3.amount) AS total_non_credit_withdrawals  
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_non_credit_withdrawals DESC 
LIMIT 10;
Database: financial
Question: How many of the account holders in South Bohemia still do not own credit cards?
Evidence: A3 contains the region names; South Bohemia is one of region names.
SQL:
SELECT COUNT(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 WHERE T1.A3 = 'south Bohemia' AND T3.type != 'OWNER'
Database: financial
Question: Which district has highest active loan?
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
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