File size: 474,422 Bytes
38818fc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | {"question_id": 0, "db_id": "california_schools", "question": "Among schools with a school-level SAT excellence rate above 0.3, what is the highest ages-5-17 free-meal eligibility rate?", "evidence": "SAT excellence rate is the share of test takers scoring at least 1500.", "SQL": "SELECT MAX(1.0 * f.`Free Meal Count (Ages 5-17)` / f.`Enrollment (Ages 5-17)`) FROM frpm AS f JOIN satscores AS s ON s.cds = f.CDSCode WHERE s.rtype = 'S' AND s.NumTstTakr > 0 AND f.`Enrollment (Ages 5-17)` > 0 AND 1.0 * s.NumGE1500 / s.NumTstTakr > 0.3", "difficulty": "moderate"}
{"question_id": 1, "db_id": "california_schools", "question": "For locally funded schools whose K-12 minus ages-5-17 enrollment difference exceeds the average such difference among locally funded schools, list each school's directory-listed name and DOC type.", "evidence": "", "SQL": "SELECT s.School, s.DOCTYPE FROM frpm AS f JOIN schools AS s ON f.CDSCode = s.CDSCode WHERE s.FundingType = 'Locally funded' AND (f.`Enrollment (K-12)` - f.`Enrollment (Ages 5-17)`) > (SELECT AVG(f2.`Enrollment (K-12)` - f2.`Enrollment (Ages 5-17)`) FROM frpm AS f2 JOIN schools AS s2 ON f2.CDSCode = s2.CDSCode WHERE s2.FundingType = 'Locally funded') ORDER BY s.CDSCode", "difficulty": "challenging"}
{"question_id": 2, "db_id": "california_schools", "question": "For the five schools with ownership code 66 and the largest K-12 free-or-reduced-price meal counts, give each school's K-12 eligible meal rate rounded to six decimal places.", "evidence": "", "SQL": "SELECT ROUND(1.0 * f.`FRPM Count (K-12)` / NULLIF(f.`Enrollment (K-12)`, 0), 6) FROM frpm AS f JOIN schools AS s ON s.CDSCode = f.CDSCode WHERE s.SOC = '66' AND NOT f.`FRPM Count (K-12)` IS NULL AND f.`Enrollment (K-12)` > 0 ORDER BY f.`FRPM Count (K-12)` DESC, s.CDSCode LIMIT 5", "difficulty": "moderate"}
{"question_id": 3, "db_id": "california_schools", "question": "What is the ratio of merged Unified School District schools in Orange County to merged Elementary School District schools?", "evidence": "", "SQL": "SELECT CAST(SUM(CASE WHEN DOC = 54 THEN 1 ELSE 0 END) AS FLOAT) / SUM(CASE WHEN DOC = 52 THEN 1 ELSE 0 END) FROM schools WHERE StatusType = 'Merged' AND County = 'Orange'", "difficulty": "moderate"}
{"question_id": 4, "db_id": "california_schools", "question": "What are the mailing street address and name of the school with the seventh-highest recorded average mathematics score?", "evidence": "", "SQL": "SELECT sc.MailStreet, sc.School FROM satscores AS sat JOIN schools AS sc ON sc.CDSCode = sat.cds WHERE sat.rtype = 'S' AND NOT sat.AvgScrMath IS NULL ORDER BY sat.AvgScrMath DESC, sat.cds LIMIT 1 OFFSET 6", "difficulty": "simple"}
{"question_id": 5, "db_id": "california_schools", "question": "How many non-charter schools in Los Angeles County have a K-12 free-meal percentage below 0.18%?", "evidence": "", "SQL": "SELECT COUNT(T2.School) FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'Los Angeles' AND T2.Charter = 0 AND CAST(T1.`Free Meal Count (K-12)` AS FLOAT) * 100 / T1.`Enrollment (K-12)` < 0.18", "difficulty": "challenging"}
{"question_id": 6, "db_id": "california_schools", "question": "Which schools served a grade span of Kindergarten to 9th grade in the county of Los Angeles and what is its Percent (%) Eligible FRPM (Ages 5-17)?", "evidence": "FRPM eligibility percentage is free-or-reduced-price meal recipients divided by same-age-band enrollment, times 100.", "SQL": "SELECT T2.School, T1.`FRPM Count (Ages 5-17)` * 100 / T1.`Enrollment (Ages 5-17)` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.County = 'Los Angeles' AND T2.GSserved = 'K-9'", "difficulty": "moderate"}
{"question_id": 7, "db_id": "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": "K-12 free-meal eligibility percentage is K-12 free-meal recipients divided by K-12 enrollment, times 100.", "SQL": "SELECT T1.`Free Meal Count (K-12)` * 100 / T1.`Enrollment (K-12)`, T1.`District Code` FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.AdmFName1 = 'Alusine'", "difficulty": "moderate"}
{"question_id": 8, "db_id": "california_schools", "question": "List the distinct available administrator email addresses for public intermediate/middle schools in San Bernardino city and county, in a unified school district, opened during 2009 or 2010.", "evidence": "", "SQL": "WITH matched AS (SELECT AdmEmail1, AdmEmail2, AdmEmail3 FROM schools WHERE County = 'San Bernardino' AND City = 'San Bernardino' AND DOCType = 'Unified School District' AND SOCType = 'Intermediate/Middle Schools (Public)' AND OpenDate >= '2009-01-01' AND OpenDate < '2011-01-01') SELECT AdmEmail1 AS email FROM matched WHERE NOT AdmEmail1 IS NULL AND TRIM(AdmEmail1) <> '' UNION SELECT AdmEmail2 AS email FROM matched WHERE NOT AdmEmail2 IS NULL AND TRIM(AdmEmail2) <> '' UNION SELECT AdmEmail3 AS email FROM matched WHERE NOT AdmEmail3 IS NULL AND TRIM(AdmEmail3) <> '' ORDER BY email", "difficulty": "challenging"}
{"question_id": 9, "db_id": "california_schools", "question": "I'm comparing three high schools in Alameda County and want to focus on the one with the biggest student body. The schools have these CDS codes: 1751010130583, 1612910137588, and 1611760134270. Which of these three schools has the highest enrollment of students aged 5-17? Please give me the 5-digit NCES school identification number for that school. If two or more of them tie for the highest enrollment, give me the NCES identification number of each tied school.", "evidence": "NCES school identification number: the 5-digit school-level NCES identifier. Enrollment (Ages 5-17): the number of students aged 5 through 17 enrolled at the school.", "SQL": "SELECT T1.NCESSchool FROM schools AS T1 INNER JOIN frpm AS T2 ON T1.CDSCode = T2.CDSCode WHERE CAST(T2.CDSCode AS SIGNED) IN (1751010130583, 1612910137588, 1611760134270) AND T2.`Enrollment (Ages 5-17)` = (SELECT MAX(f.`Enrollment (Ages 5-17)`) FROM frpm AS f WHERE CAST(f.CDSCode AS SIGNED) IN (1751010130583, 1612910137588, 1611760134270))", "difficulty": "challenging"}
{"question_id": 10, "db_id": "california_schools", "question": "I'm profiling the High Tech High charter network in San Diego. For charter number 756, what is the average number of SAT test takers per school across all of its schools with a San Diego mailing city? Count every school regardless of operational status, and treat a school with no SAT record as having zero test takers. Round the average to two decimals.", "evidence": "Charter number 756 is the state-issued charter number.", "SQL": "SELECT ROUND(SUM(COALESCE(sc.NumTstTakr, 0)) * 1.0 / COUNT(*), 2) AS avg_sat_test_takers_per_school FROM schools AS s LEFT JOIN satscores AS sc ON sc.cds = s.CDSCode WHERE CAST(s.CharterNum AS SIGNED) = 756 AND s.MailCity = 'San Diego'", "difficulty": "challenging"}
{"question_id": 11, "db_id": "california_schools", "question": "Following up on the SAT participation review: among the currently operating high schools in the district with NCES identification number 0613360 that had no SAT test takers, which one begins serving students at the earliest grade? Please give me each such school's name and grade span served. Note that a high school must actually enroll students through grade 12-offering grade 12 without enrollment doesn't count. A school with no SAT record counts as having zero SAT test takers and should be included; only exclude schools with a positive number of SAT test takers. Compare starting grades as school grades-preschool comes before kindergarten, which comes before grade 1-and use the lowest grade the school actually serves, not just what it offers. If several schools tie at the earliest grade, list them all alphabetically by school name.", "evidence": "NCES identification number 0613360 is the school district identification number assigned by the National Center for Education Statistics.", "SQL": "WITH cohort AS (SELECT s.School AS school_name, s.GSserved AS grade_span_served, CASE WHEN SUBSTRING(s.GSserved, 1, LOCATE('-', CONCAT(s.GSserved, '-')) - 1) = 'P' THEN -1 WHEN SUBSTRING(s.GSserved, 1, LOCATE('-', CONCAT(s.GSserved, '-')) - 1) = 'K' THEN 0 ELSE CAST(SUBSTRING(s.GSserved, 1, LOCATE('-', CONCAT(s.GSserved, '-')) - 1) AS SIGNED) END AS start_rank FROM schools AS s LEFT JOIN satscores AS t ON s.CDSCode = t.cds WHERE s.NCESDist = '0613360' AND s.StatusType = 'Active' AND s.GSserved LIKE '%12' AND COALESCE(t.NumTstTakr, 0) = 0) SELECT school_name, grade_span_served FROM cohort WHERE start_rank = (SELECT MIN(start_rank) FROM cohort) ORDER BY school_name", "difficulty": "challenging"}
{"question_id": 12, "db_id": "california_schools", "question": "I'm profiling schools run directly by the California State Board of Education. Which of those schools has the highest average SAT reading score? If several tie for the highest, give me all of them. For each school, I need its name and its full mailing street address - the complete address, not an abbreviated one. Only include schools the State Board runs directly, and the score must be the school's own result, not a district-wide figure.", "evidence": "State Board of Education: the state authority that directly runs and oversees certain California schools.", "SQL": "SELECT s.School, s.MailStreet FROM satscores AS t JOIN schools AS s ON t.cds = s.CDSCode WHERE s.DOCType = 'State Board of Education' AND NOT t.sname IS NULL AND NOT t.AvgScrRead IS NULL AND t.AvgScrRead = (SELECT MAX(t2.AvgScrRead) FROM satscores AS t2 JOIN schools AS s2 ON t2.cds = s2.CDSCode WHERE s2.DOCType = 'State Board of Education' AND NOT t2.sname IS NULL AND NOT t2.AvgScrRead IS NULL)", "difficulty": "challenging"}
{"question_id": 13, "db_id": "california_schools", "question": "I'm trying to verify where a school I was told about is located. It's a high school in Alameda County with Breakfast Provision 2 status, serving grades 9 through 12, and its identification number is 1611920113902. What city is this school in?", "evidence": "The identification number is the school's CDS code; Educational Instruction Level Code 'HS' identifies a high school; grades 9 through 12 means lowest grade 9 and highest grade 12; Breakfast Provision 2 is a National School Lunch Program provision status.", "SQL": "SELECT s.City FROM schools AS s INNER JOIN frpm AS f ON s.CDSCode = f.CDSCode WHERE CAST(s.CDSCode AS SIGNED) = 1611920113902 AND f.`NSLP Provision Status` = 'Breakfast Provision 2' AND s.County = 'Alameda' AND f.`Low Grade` = '9' AND f.`High Grade` = '12' AND s.EILCode = 'HS'", "difficulty": "challenging"}
{"question_id": 14, "db_id": "california_schools", "question": "I'm reviewing NSLP Provision 2 schools. Can you give me the name and city of every high school (educational instruction level code HS) whose meal-program status is exactly Provision 2 and whose lowest grade served is above ninth grade? One row per school, ordered by school name. Note: only the status named Provision 2 counts-the breakfast and lunch variants are separate statuses and shouldn't be included.", "evidence": "", "SQL": "SELECT T2.School AS school, T2.City AS city FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T1.`NSLP Provision Status` = 'Provision 2' AND T2.EILCode = 'HS' AND CAST(T1.`Low Grade` AS SIGNED) > 9 ORDER BY T2.School", "difficulty": "challenging"}
{"question_id": 15, "db_id": "california_schools", "question": "I'm profiling California's statewide benefit charter networks. Among the schools run by a statewide benefit charter network, which single school had the highest number of SAT test takers who scored 1500 or above? Please give me that school's name and its phone number. If several schools tie for the highest count, list every tied school with its phone number.", "evidence": "Statewide benefit charter: a charter school network authorized directly by the California State Board of Education to operate schools throughout the state; charter schools authorized by a school district or county office of education are not statewide benefit charters.", "SQL": "SELECT s.School AS school_name, s.Phone AS phone FROM satscores AS t INNER JOIN schools AS s ON t.cds = s.CDSCode WHERE s.DOCType = 'Statewide Benefit Charter' AND t.rtype = 'S' AND t.NumGE1500 = (SELECT MAX(t2.NumGE1500) FROM satscores AS t2 INNER JOIN schools AS s2 ON t2.cds = s2.CDSCode WHERE s2.DOCType = 'Statewide Benefit Charter' AND t2.rtype = 'S')", "difficulty": "challenging"}
{"question_id": 16, "db_id": "california_schools", "question": "I'm looking at a directly-funded charter high school in California with CDS code 1611190130609. Could you tell me its average SAT math score and how many students took the SAT there? Just that one school's figures. If the school with that CDS code turns out not to be directly funded, then there's no answer.", "evidence": "CDS code: the identification number the California Department of Education assigns to a county, district, or school. Directly-funded charter school: a charter school that receives its funding directly from the state rather than through its district.", "SQL": "SELECT T1.AvgScrMath AS average_math_score, T1.NumTstTakr AS number_of_test_takers FROM satscores AS T1 INNER JOIN frpm AS T2 ON T1.cds = T2.CDSCode WHERE CAST(T1.cds AS SIGNED) = 1611190130609 AND T2.`Charter Funding Type` = 'Directly funded'", "difficulty": "challenging"}
{"question_id": 17, "db_id": "california_schools", "question": "I'm looking at SAT participation in Contra Costa County. How many schools in the county had more SAT test takers than the school with CDS code 7618040730051? That school is itself a Contra Costa County school, so I just want the count of schools strictly ahead of it by number of SAT test takers, based on the SAT results snapshot in the data. A single number is all I need.", "evidence": "CDS code: the County-District-School identifier that the California Department of Education assigns to each school and district in the state.", "SQL": "SELECT COUNT(*) AS school_count FROM satscores WHERE cname = 'Contra Costa' AND NOT sname IS NULL AND NumTstTakr > (SELECT NumTstTakr FROM satscores WHERE CAST(cds AS SIGNED) = 7618040730051)", "difficulty": "challenging"}
{"question_id": 18, "db_id": "california_schools", "question": "I'm comparing schools in San Francisco. How many public schools with a San Francisco mailing city had an average total SAT score of at least 1500? Please count only schools whose district type is 'Unified School District', 'High School District', 'Elementary School District', or 'County Office of Education (COE)' - exclude any other district type. I just need the single count of qualifying schools.", "evidence": "A school's total SAT score is the sum of its average reading, average math, and average writing scores; a school's mailing city is the city in its mailing address.", "SQL": "SELECT COUNT(*) AS n FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.MailCity = 'San Francisco' AND T2.DOCType IN ('Unified School District', 'High School District', 'Elementary School District', 'County Office of Education (COE)') AND (T1.AvgScrRead + T1.AvgScrMath + T1.AvgScrWrite) >= 1500", "difficulty": "challenging"}
{"question_id": 19, "db_id": "california_schools", "question": "What is the lowest grade level at which any school in our district begins serving students? If several schools tie at the lowest grade, just report that single grade level for the whole district. Our district is NCES district ID 0632640.", "evidence": "'P' stands for preschool.", "SQL": "SELECT T1.`Low Grade` AS lowest_grade FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE T2.NCESDist = '0632640' ORDER BY (T1.`Low Grade` = 'P') DESC, (T1.`Low Grade` = 'K') DESC, CAST(T1.`Low Grade` AS SIGNED), T1.`Low Grade` LIMIT 1", "difficulty": "challenging"}
{"question_id": 20, "db_id": "california_schools", "question": "I'm reviewing administrator coverage across Amador and Madera counties, and I want to see which administrator first names actually cover the most schools. For the two administrator first names whose holders run the most schools across the two counties (ranking names by the number of schools their holders run, with the alphabetically earlier name ranking higher if two names run equally many schools), please give me one row per public school district in those two counties and per those two first names, showing the district name, the first name, and the number of schools in that district run by an administrator with that first name - including every public school district, even ones where that's zero. Every administrator listed for a school counts, not just the first-listed one. A public school district means a unified school district, an elementary school district, a high school district, or a county office of education, and only Amador and Madera counties are in scope.", "evidence": "", "SQL": "WITH scope AS (SELECT CDSCode, District, AdmFName1 AS fn FROM schools WHERE County IN ('Amador', 'Madera') AND DOCType IN ('Unified School District', 'Elementary School District', 'High School District', 'County Office of Education (COE)') AND NOT AdmFName1 IS NULL UNION SELECT CDSCode, District, AdmFName2 FROM schools WHERE County IN ('Amador', 'Madera') AND DOCType IN ('Unified School District', 'Elementary School District', 'High School District', 'County Office of Education (COE)') AND NOT AdmFName2 IS NULL UNION SELECT CDSCode, District, AdmFName3 FROM schools WHERE County IN ('Amador', 'Madera') AND DOCType IN ('Unified School District', 'Elementary School District', 'High School District', 'County Office of Education (COE)') AND NOT AdmFName3 IS NULL), ranked AS (SELECT fn, COUNT(DISTINCT CDSCode) AS schools_run FROM scope GROUP BY fn ORDER BY schools_run DESC, fn ASC LIMIT 2), districts AS (SELECT DISTINCT District FROM schools WHERE County IN ('Amador', 'Madera') AND DOCType IN ('Unified School District', 'Elementary School District', 'High School District', 'County Office of Education (COE)')) SELECT d.District AS district_name, r.fn AS first_name, (SELECT COUNT(DISTINCT s.CDSCode) FROM scope AS s WHERE s.District = d.District AND s.fn = r.fn) AS school_count FROM districts AS d CROSS JOIN ranked AS r ORDER BY d.District, r.fn", "difficulty": "challenging"}
{"question_id": 21, "db_id": "california_schools", "question": "For the 2014-2015 academic year, what was the average number of enrolled students aged 5 to 17 eligible for free or reduced price meals per Youth Authority school? Count every Youth Authority school regardless of its status (active, closed, or merged), and treat a Youth Authority school with no meal-program record as zero. Please give me just that one number, rounded to two decimal places.", "evidence": "A Youth Authority school is a school the state directory classifies as a Youth Authority Facility.", "SQL": "SELECT ROUND(SUM(COALESCE(T1.`FRPM Count (Ages 5-17)`, 0.0)) * 1.0 / COUNT(T2.CDSCode), 2) AS avg_frpm_ages_5_17 FROM schools AS T2 LEFT JOIN frpm AS T1 ON T1.CDSCode = T2.CDSCode WHERE T2.SOCType LIKE '%Youth Authority%'", "difficulty": "challenging"}
{"question_id": 22, "db_id": "california_schools", "question": "I have a school's CDS code from a separate list of Alameda County schools on Breakfast Provision 2, and I need to confirm which school it is. For the school with CDS code 1612590136051, please give me the school name and the educational instruction level name. This CDS code identifies exactly one school, so return only that school.", "evidence": "Breakfast Provision 2: the NSLP provision status category the school participates in. CDS code 1612590136051: the school identifier being asked about.", "SQL": "SELECT s.School, s.EILName FROM schools AS s INNER JOIN frpm AS f ON s.CDSCode = f.CDSCode WHERE f.`NSLP Provision Status` = 'Breakfast Provision 2' AND f.`County Name` = 'Alameda' AND CAST(s.CDSCode AS SIGNED) = 1612590136051", "difficulty": "challenging"}
{"question_id": 23, "db_id": "california_schools", "question": "I'm looking at the schools that the State Board of Education directly runs or charters. Which individual school among them had the most students score at least 1500 on the SAT? Please give me that school's name and its administrator's email address. If two schools tie on that count, list both.", "evidence": "Schools run or chartered by the State Board of Education are identified by their district ownership type.", "SQL": "SELECT T2.School, T2.AdmEmail1 FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.DOCType = 'State Board of Education' AND T1.rtype = 'S' AND T1.NumGE1500 = (SELECT MAX(T3.NumGE1500) FROM satscores AS T3 INNER JOIN schools AS T4 ON T3.cds = T4.CDSCode WHERE T4.DOCType = 'State Board of Education' AND T3.rtype = 'S')", "difficulty": "challenging"}
{"question_id": 24, "db_id": "california_schools", "question": "We're relocating to far Northern California and want to know how far north California's middle schools reach. A middle school means a school serving the middle grades, the level between elementary school and high school — count it as a middle school if either its school type or its school name marks it as serving the middle grades, so a junior high school whose name says 'Middle' counts. Include both open and closed schools. Please tell me which middle school is located furthest north in California, along with its school type (the value of the field named 'School Type'), its school name, and its latitude in degrees. If several middle schools tie for the highest latitude, list all of them.", "evidence": "middle school: a school serving the middle grades, the level between elementary school and high school", "SQL": "SELECT T1.`School Type`, T1.`School Name`, T2.Latitude FROM frpm AS T1 INNER JOIN schools AS T2 ON T1.CDSCode = T2.CDSCode WHERE (T1.`School Type` LIKE '%Middle%' OR T1.`School Name` LIKE '%Middle%') AND T2.Latitude = (SELECT MAX(T2b.Latitude) FROM frpm AS T1b INNER JOIN schools AS T2b ON T1b.CDSCode = T2b.CDSCode WHERE T1b.`School Type` LIKE '%Middle%' OR T1b.`School Name` LIKE '%Middle%')", "difficulty": "challenging"}
{"question_id": 25, "db_id": "california_schools", "question": "I'm working on a story about campuses Los Angeles County opened during 2007 and the SAT participation they drew. What was the average number of SAT test takers per school across Los Angeles County schools that opened during 2007 and are run by a school district? Please give me that single number, rounded to two decimals. A few things to keep in mind: a county office of education counts as the school district for the schools it runs; \"opened during 2007\" means the opening date falls in calendar year 2007; and a school with no SAT record counts as zero test takers.", "evidence": "SAT test takers: the number of test takers recorded for the school.", "SQL": "SELECT ROUND(SUM(COALESCE(sat.NumTstTakr, 0)) * 1.0 / COUNT(*), 2) AS avg_sat_test_takers FROM schools AS s LEFT JOIN satscores AS sat ON sat.cds = s.CDSCode WHERE s.County = 'Los Angeles' AND DATE_FORMAT(s.OpenDate, '%Y') = '2007' AND (s.DOCType LIKE '%school district%' OR s.DOCType LIKE '%county office of education%')", "difficulty": "challenging"}
{"question_id": 26, "db_id": "california_schools", "question": "I'm reviewing charter school funding models and want to compare the directly funded and locally funded charters that are currently in operation. For each of the two funding categories, please give me: (1) the number of charter schools currently in operation, counting only schools the directory lists as active (open), not closed or merged; (2) total 2014-2015 K-12 enrollment; (3) the average percentage of students eligible for free or reduced-price meals, on a 0-100 scale, rounded to two decimals; and (4) the average combined SAT score (reading + math + writing) across schools that have reported scores, rounded to two decimals. Note that schools without SAT results should still count in the school count, enrollment total, and meal-eligibility average. Please give me these figures grouped by funding category.", "evidence": "Directly funded and locally funded are the two charter funding categories. Free or reduced-price meal eligibility is measured by the K-12 eligible percentage. Combined SAT score is the sum of the average reading, math and writing scores.", "SQL": "SELECT s.FundingType AS funding_category, COUNT(*) AS operating_charter_schools, SUM(f.`Enrollment (K-12)`) AS total_k12_enrollment, ROUND(AVG(f.`Percent (%) Eligible FRPM (K-12)`) * 100, 2) AS avg_frpm_percentage, ROUND(AVG(sat.AvgScrRead + sat.AvgScrMath + sat.AvgScrWrite), 2) AS avg_combined_sat FROM schools AS s LEFT JOIN frpm AS f ON f.CDSCode = s.CDSCode LEFT JOIN satscores AS sat ON sat.cds = s.CDSCode WHERE s.Charter = 1 AND s.StatusType = 'Active' AND s.FundingType IN ('Directly funded', 'Locally funded') GROUP BY s.FundingType ORDER BY funding_category", "difficulty": "challenging"}
{"question_id": 27, "db_id": "california_schools", "question": "Among California's state special schools, which one begins enrolling students at the latest grade level? Please give me: the school's name, the earliest grade level covered by its K-12 enrollment, its K-12 enrollment, and how many SAT test takers it had. In the grade-level codes, P means pre-kindergarten and K means kindergarten, and grades progress from pre-kindergarten to kindergarten to grades 1 through 12 — so a school starting at grade 1 starts later than one starting at kindergarten. If a state special school has no SAT record, still consider it a candidate and report it as having 0 SAT test takers. If two schools start at the same grade level, prefer the one with the larger K-12 enrollment; if still tied, the one whose name comes first alphabetically. The data is for the 2014-2015 school year.", "evidence": "A state special school is a school operated by the state of California that serves students with special needs, such as the schools for the deaf or the blind.", "SQL": "SELECT s.School AS school_name, f.`Low Grade` AS starting_grade, f.`Enrollment (K-12)` AS k12_enrollment, COALESCE(t.NumTstTakr, 0) AS sat_test_takers FROM schools AS s JOIN frpm AS f ON f.CDSCode = s.CDSCode LEFT JOIN satscores AS t ON t.cds = s.CDSCode WHERE s.DOCTYPE = 'State Special Schools' ORDER BY CASE f.`Low Grade` WHEN 'P' THEN 0 WHEN 'K' THEN 1 ELSE CAST(f.`Low Grade` AS SIGNED) + 1 END DESC, f.`Enrollment (K-12)` DESC, s.School ASC LIMIT 1", "difficulty": "challenging"}
{"question_id": 28, "db_id": "california_schools", "question": "I'm putting together a brief on SAT participation among California's larger public schools. How many individual named school sites in the state with a K-12 enrollment over 500 and a highest grade served of 8 or below had no SAT test takers? I just need the school_count, a single whole number. Please count a school as an individual school site with a name - district and county offices of education are not schools. Include every qualifying school site statewide even if it shows no SAT results at all; such a site simply had no test takers. By highest grade served I mean the top grade level the school serves, as a grade number from 1 through 12.", "evidence": "", "SQL": "SELECT COUNT(*) AS school_count FROM schools AS s JOIN frpm AS f ON f.CDSCode = s.CDSCode LEFT JOIN satscores AS t ON t.cds = s.CDSCode WHERE NOT s.School IS NULL AND f.`Enrollment (K-12)` > 500 AND CAST(f.`High Grade` AS SIGNED) BETWEEN 1 AND 8 AND COALESCE(t.NumTstTakr, 0) = 0", "difficulty": "challenging"}
{"question_id": 29, "db_id": "california_schools", "question": "I'm studying charter schools run by county offices of education. Using the K-12 school meal program records, for the charter schools these county offices operate, broken down by charter funding type (directly funded and locally funded only), I'd like to know: how many are currently operating, their total K-12 enrollment, and their total number of FRPM-eligible K-12 students. A school counts as currently operating only if its status is Active. Please give me one row per funding type, with directly funded first.", "evidence": "FRPM means free or reduced price meal eligibility.", "SQL": "SELECT f.`Charter Funding Type` AS funding_type, COUNT(*) AS active_charter_schools, SUM(f.`Enrollment (K-12)`) AS total_k12_enrollment, SUM(f.`FRPM Count (K-12)`) AS total_frpm_students FROM frpm AS f INNER JOIN schools AS s ON f.CDSCode = s.CDSCode WHERE f.`Charter School (Y/N)` = 1 AND f.`District Type` = 'County Office of Education (COE)' AND f.`Charter Funding Type` IN ('Directly funded', 'Locally funded') AND s.StatusType = 'Active' GROUP BY f.`Charter Funding Type` ORDER BY CASE f.`Charter Funding Type` WHEN 'Directly funded' THEN 1 ELSE 2 END", "difficulty": "challenging"}
{"question_id": 30, "db_id": "california_schools", "question": "I'm documenting now-closed California schools whose students performed best on the SAT writing section, and I need the runner-up. Among schools whose status is Closed (not Active, Merged or Pending), and which have an average SAT writing score, can you tell me which school had the second-highest average SAT writing score? By second-highest I mean the best score strictly below the highest – if several schools share that score, please list them all. For each school, give me its name, its own district and county, and its average SAT writing score.", "evidence": "SAT writing score: the average writing score of the school's SAT test takers.", "SQL": "WITH j AS (SELECT T2.School AS School, T2.District AS District, T2.County AS County, T1.AvgScrWrite AS AvgScrWrite FROM satscores AS T1 INNER JOIN schools AS T2 ON T1.cds = T2.CDSCode WHERE T2.StatusType = 'Closed' AND NOT T1.AvgScrWrite IS NULL AND NOT T1.sname IS NULL) SELECT School, District, County, AvgScrWrite FROM j WHERE AvgScrWrite = (SELECT MAX(AvgScrWrite) FROM j WHERE AvgScrWrite < (SELECT MAX(AvgScrWrite) FROM j))", "difficulty": "challenging"}
{"question_id": 31, "db_id": "california_schools", "question": "I'm a parent looking at high schools in California, and I want to know how often a school that's still open has no seniors taking the SAT at all. How many currently open public high schools in California had zero students take the SAT? By 'currently open' I mean the school's status is Active, not closed or merged. By 'high school' I mean a school whose educational instruction level is High School. Please count a school that has no SAT record at all as having zero test takers. I just want that one number.", "evidence": "SAT test takers: the number of test takers recorded for the school in the SAT scores data.", "SQL": "SELECT COUNT(*) AS zero_taker_open_high_schools FROM schools AS sc LEFT JOIN satscores AS s ON sc.CDSCode = s.cds WHERE sc.StatusType = 'Active' AND sc.EILName = 'High School' AND COALESCE(s.NumTstTakr, 0) = 0", "difficulty": "challenging"}
{"question_id": 32, "db_id": "california_schools", "question": "I'm planning a targeted meal-support pilot and want to compare one school against similar schools in our county. The county I mean is the one where Fremont High (CDS code 1612590125716) is located - please identify the county by that CDS code, not by the school name. For that county, please look at all K-12 schools with more than 500 free meals and fewer than 700 FRPM meals, and give me back: the county name; the number of schools; the average free-meal percentage and the average FRPM percentage, both on a 0-100 scale with each school's own percentage rounded to 2 decimals before averaging; the number of charter schools and the number of non-charter schools (charter vs. non-charter per the charter indicator in the frpm data); and the average SAT score, where a school's SAT score is the sum of its three SAT section averages, counted only for schools that actually have SAT records, with no SAT record meaning the school is simply excluded from that average. Please round the reported averages to 2 decimals.", "evidence": "Free meal percentage = free meal count (K-12) / enrollment (K-12) * 100; FRPM percentage = FRPM count (K-12) / enrollment (K-12) * 100; charter school = charter indicator 1, non-charter = charter indicator 0.", "SQL": "WITH TargetCounty AS (SELECT `County Name` AS CountyName FROM frpm WHERE CAST(CDSCode AS SIGNED) = 1612590125716), Cohort AS (SELECT f.CDSCode, ROUND(f.`Free Meal Count (K-12)` / f.`Enrollment (K-12)` * 100, 2) AS FreePct, ROUND(f.`FRPM Count (K-12)` / f.`Enrollment (K-12)` * 100, 2) AS FRPMPct, f.`Charter School (Y/N)` AS CharterFlag, sd.AvgScrRead + sd.AvgScrMath + sd.AvgScrWrite AS SATScore FROM frpm AS f JOIN TargetCounty AS t ON f.`County Name` = t.CountyName LEFT JOIN satscores AS sd ON f.CDSCode = sd.cds WHERE f.`Free Meal Count (K-12)` > 500 AND f.`FRPM Count (K-12)` < 700) SELECT (SELECT CountyName FROM TargetCounty) AS county_name, COUNT(*) AS school_count, ROUND(AVG(FreePct), 2) AS avg_free_meal_pct, ROUND(AVG(FRPMPct), 2) AS avg_frpm_pct, SUM(CASE WHEN CharterFlag = 1 THEN 1 ELSE 0 END) AS charter_count, SUM(CASE WHEN CharterFlag = 0 THEN 1 ELSE 0 END) AS non_charter_count, ROUND(AVG(SATScore), 2) AS avg_sat_score FROM Cohort", "difficulty": "challenging"}
{"question_id": 33, "db_id": "california_schools", "question": "I'm studying the 1980 growth of public schooling in San Diego County. What was the average number of schools per month that opened in San Diego County in 1980 under a school district's jurisdiction? I need just that single number. Please average over all 12 months of 1980 (months with no openings count as zero), and give me the exact average without rounding.", "evidence": "A school district is a local education agency that runs K-12 public schools; it is an elementary school district, a high school district, or a unified school district.", "SQL": "SELECT CAST(COUNT(*) AS FLOAT) / 12 AS monthly_average FROM schools WHERE County = 'San Diego' AND DATE_FORMAT(OpenDate, '%Y') = '1980' AND DOCType IN ('Elementary School District', 'High School District', 'Unified School District')", "difficulty": "challenging"}
{"question_id": 34, "db_id": "california_schools", "question": "Among California schools whose students have an average SAT Math score above 400, what percentage offer virtual instruction, either exclusively or in part? Please give me a single percentage value rounded to one decimal place.", "evidence": "In the school directory, the exclusive-virtual category is coded 'F' and the partial-virtual category is coded 'P'.", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN s.`Virtual` IN ('F', 'P') THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct FROM satscores AS sat JOIN schools AS s ON sat.cds = s.CDSCode WHERE sat.rtype = 'S' AND sat.AvgScrMath > 400", "difficulty": "challenging"}
{"question_id": 35, "db_id": "california_schools", "question": "A parent is asking about a school and could only give me the CDS code 1612590137943. Can you look up that school and give me its name, county, district, and city; its K-12 enrollment; the number of K-12 students eligible for free or reduced price meals and the percentage eligible (report the percentage exactly as it appears, without rounding); and the SAT results - number of test takers, average reading score, average math score, average writing score, and the number of test takers whose total score is at least 1500?", "evidence": "CDS code: the state's County-District-School identification code assigned to each school; FRPM: the Free or Reduced Price Meal program, where the FRPM count is the number of students eligible.", "SQL": "SELECT s.School AS school_name, s.County AS county, s.District AS district, s.City AS city, f.`Enrollment (K-12)` AS enrollment_k12, f.`FRPM Count (K-12)` AS frpm_count, f.`Percent (%) Eligible FRPM (K-12)` AS pct_eligible_frpm, sat.NumTstTakr AS num_sat_takers, sat.AvgScrRead AS avg_reading, sat.AvgScrMath AS avg_math, sat.AvgScrWrite AS avg_writing, sat.NumGE1500 AS num_ge_1500 FROM schools AS s JOIN frpm AS f ON f.CDSCode = s.CDSCode LEFT JOIN satscores AS sat ON sat.cds = s.CDSCode WHERE CAST(s.CDSCode AS SIGNED) = 1612590137943", "difficulty": "challenging"}
{"question_id": 36, "db_id": "california_schools", "question": "I'm putting together a profile of Alameda County high schools, focusing on economic disadvantage among schools that serve up through 12th grade. Among those schools, can you tell me which one has the highest free meal rate? For each school you identify, give me one line with: the school name, its free meal rate to 4 decimal places, whether it is a charter school (Yes/No/Unknown), the grades it serves, and its SAT performance level (Below Average, Average, Above Average, or No SAT Data). Please use the school's grade span of enrollment from the school directory (the GSserved field of the schools table) both to decide whether it serves up through 12th grade and for the grades-it-serves column-do not use the free-meal program record's Low Grade/High Grade for either. If several schools tie for the highest free meal rate, list every one of them.", "evidence": "Free meal rate = Free Meal Count (K-12) / Enrollment (K-12). SAT performance level is based on the SAT total (Reading + Math + Writing): Below Average if below 1200, Average if 1200 to 1500, Above Average if above 1500, and 'No SAT Data' if no SAT scores are available.", "SQL": "WITH cohort AS (SELECT f.`School Name` AS school_name, f.`Free Meal Count (K-12)` * 1.0 / f.`Enrollment (K-12)` AS free_rate, sc.Charter, sc.GSserved, s.AvgScrRead, s.AvgScrMath, s.AvgScrWrite FROM frpm AS f LEFT JOIN schools AS sc ON sc.CDSCode = f.CDSCode LEFT JOIN satscores AS s ON s.cds = f.CDSCode WHERE f.`County Name` = 'Alameda' AND SUBSTRING(sc.GSserved, -2) = '12') SELECT school_name, ROUND(free_rate, 4) AS highest_free_meal_rate, CASE WHEN Charter = 1 THEN 'Yes' WHEN Charter = 0 THEN 'No' ELSE 'Unknown' END AS is_charter, GSserved AS grades_served, CASE WHEN AvgScrRead IS NULL THEN 'No SAT Data' WHEN AvgScrRead + AvgScrMath + AvgScrWrite < 1200 THEN 'Below Average' WHEN AvgScrRead + AvgScrMath + AvgScrWrite <= 1500 THEN 'Average' ELSE 'Above Average' END AS sat_performance FROM cohort WHERE free_rate = (SELECT MAX(f2.`Free Meal Count (K-12)` * 1.0 / f2.`Enrollment (K-12)`) FROM frpm AS f2 JOIN schools AS s2 ON s2.CDSCode = f2.CDSCode WHERE f2.`County Name` = 'Alameda' AND SUBSTRING(s2.GSserved, -2) = '12')", "difficulty": "challenging"}
{"question_id": 37, "db_id": "california_schools", "question": "Could you pull a full profile for the school with CDS code 7618040113118? I need its name, phone number, website, average SAT reading, math and writing scores, whether it is a charter school, its K-12 enrollment for the 2014-2015 academic year, and the percentage of its students eligible for free or reduced price meals on a 0-100 scale rounded to two decimal places. Alongside that, please find the highest average SAT math score achieved by any active school with at least 10 SAT test takers – if several schools tie for the highest, just give me that single score – and how far below that highest score this school's math score falls.", "evidence": "CDS code is the California Department of Education's school identifier; a charter school is one with charter status recorded as 1.", "SQL": "WITH Benchmark AS (SELECT MAX(t.AvgScrMath) AS TopMath FROM satscores AS t INNER JOIN schools AS s ON s.CDSCode = t.cds WHERE s.StatusType = 'Active' AND t.NumTstTakr >= 10) SELECT s.School AS `School Name`, s.Phone AS `Phone Number`, s.Website AS `Website`, t.AvgScrRead AS `Average SAT Reading Score`, t.AvgScrMath AS `Average SAT Math Score`, t.AvgScrWrite AS `Average SAT Writing Score`, f.`Charter School (Y/N)` AS `Charter School Status`, f.`Enrollment (K-12)` AS `K-12 Enrollment (2014-2015)`, ROUND(f.`Percent (%) Eligible FRPM (K-12)` * 100, 2) AS `Percent Eligible Free/Reduced Price Meals`, b.TopMath AS `Highest Average Math Score`, b.TopMath - t.AvgScrMath AS `Gap Below Highest Math Score` FROM schools AS s INNER JOIN satscores AS t ON t.cds = s.CDSCode LEFT JOIN frpm AS f ON f.CDSCode = s.CDSCode AND f.`Academic Year` = '2014-2015' CROSS JOIN Benchmark AS b WHERE CAST(s.CDSCode AS SIGNED) = 7618040113118", "difficulty": "challenging"}
{"question_id": 38, "db_id": "california_schools", "question": "I'm mapping where exclusively virtual schools are concentrated. For the five counties with the most exclusively virtual schools - if several counties tie with the fifth-highest count, include all of them - please give me for each county: the county name, how many exclusively virtual schools it has, and the name of the exclusively virtual school in that county with the highest average SAT reading score. If several schools tie for the highest average reading score in a county, list each of them. If none of the county's exclusively virtual schools has a reported reading average, show 'None' as the school name.", "evidence": "An exclusively virtual school is one whose Virtual field holds the code 'F'.", "SQL": "WITH virtual_counts AS (SELECT County, COUNT(*) AS virtual_schools FROM schools WHERE `Virtual` = 'F' GROUP BY County), top_counties AS (SELECT County, virtual_schools FROM virtual_counts WHERE virtual_schools >= (SELECT MIN(virtual_schools) FROM (SELECT virtual_schools FROM virtual_counts ORDER BY virtual_schools DESC, County LIMIT 5) AS __photo_derived_1)), best AS (SELECT s.County, s.School, RANK() OVER (PARTITION BY s.County ORDER BY sat.AvgScrRead DESC) AS r FROM schools AS s JOIN satscores AS sat ON s.CDSCode = sat.cds WHERE s.`Virtual` = 'F' AND NOT sat.AvgScrRead IS NULL) SELECT t.County, t.virtual_schools, COALESCE(b.School, 'None') AS School FROM top_counties AS t LEFT JOIN best AS b ON b.County = t.County AND b.r = 1 ORDER BY t.virtual_schools DESC, t.County", "difficulty": "challenging"}
{"question_id": 39, "db_id": "california_schools", "question": "I'm comparing online-only schooling options. I'd like to know, for Santa Barbara County and for the county that contains the school with CDS code 1100170109835 (which identifies one school), how many exclusive-virtual schools are in each county. Please give me each county's name with its number of exclusive-virtual schools, listing the county with the larger number first, or alphabetically by county name if they tie.", "evidence": "A school counts as exclusive-virtual only if its virtual-instruction category is coded 'F'.", "SQL": "WITH target AS (SELECT County FROM schools WHERE CAST(CDSCode AS SIGNED) = 1100170109835), cands AS (SELECT County FROM target UNION SELECT 'Santa Barbara') SELECT c.County AS County, (SELECT COUNT(*) FROM schools AS s WHERE s.County = c.County AND s.`Virtual` = 'F') AS num FROM cands AS c ORDER BY num DESC, c.County", "difficulty": "challenging"}
{"question_id": 40, "db_id": "california_schools", "question": "I'm studying how concentrated economic need relates to SAT outcomes in California public schools. Among regular, non-charter schools with more than 100 K-12 students, I'd like two extremes plus one benchmark school: the school with the largest count of FRPM-eligible students, the school with the smallest FRPM share (the proportion of its K-12 enrollment that is FRPM-eligible – smallest by that share, not the raw count), and the school with CDS code 4615150435602 from my notes. If a school answers more than one part, report it once per part, and label each row with which part it answers ('largest FRPM-eligible count', 'smallest FRPM share', or 'the CDS code from my notes', in that order). Include ties. For each school, please give: school name, county, city, full mailing address as four columns (mailing street, mailing city, mailing state, mailing ZIP), website, K-12 enrollment, FRPM-eligible student count, FRPM share, average total SAT score (reading + math + writing) among its SAT takers, percentage of its SAT takers scoring 1500 or more, opening date, and status ('closed' if a closing date is recorded, otherwise 'open'). Nothing else, please.", "evidence": "CDS code: the California Department of Education's identification code for a school; the benchmark school in my notes is identified by CDS code 4615150435602.", "SQL": "WITH cohort AS (SELECT f.CDSCode, f.`School Name` AS SchoolName, f.`FRPM Count (K-12)` AS FRPMCount, f.`Enrollment (K-12)` AS Enrollment, f.`FRPM Count (K-12)` * 1.0 / f.`Enrollment (K-12)` AS FRPMShare, CAST(f.CDSCode AS SIGNED) AS code_num FROM frpm AS f WHERE f.`Charter School (Y/N)` = 0 AND f.`Enrollment (K-12)` > 100) SELECT 'largest FRPM-eligible count' AS RequestPart, c.SchoolName AS SchoolName, s.County AS County, s.City AS City, s.MailStreet AS MailingStreet, s.MailCity AS MailingCity, s.MailState AS MailingState, s.MailZip AS MailingZip, s.Website AS Website, c.Enrollment AS Enrollment, c.FRPMCount AS FRPMCount, c.FRPMShare AS FRPMShare, t.AvgScrRead + t.AvgScrMath + t.AvgScrWrite AS AvgTotalSAT, CAST(t.NumGE1500 * 100.0 AS DOUBLE) / NULLIF(t.NumTstTakr, 0) AS Pct1500Plus, s.OpenDate AS OpenDate, CASE WHEN NOT s.ClosedDate IS NULL THEN 'closed' ELSE 'open' END AS SchoolStatus FROM cohort AS c JOIN schools AS s ON c.code_num = CAST(s.CDSCode AS SIGNED) LEFT JOIN satscores AS t ON c.code_num = CAST(t.cds AS SIGNED) WHERE c.FRPMCount = (SELECT MAX(x.FRPMCount) FROM cohort AS x) UNION ALL SELECT 'smallest FRPM share', c.SchoolName, s.County, s.City, s.MailStreet, s.MailCity, s.MailState, s.MailZip, s.Website, c.Enrollment, c.FRPMCount, c.FRPMShare, t.AvgScrRead + t.AvgScrMath + t.AvgScrWrite, CAST(t.NumGE1500 * 100.0 AS DOUBLE) / NULLIF(t.NumTstTakr, 0), s.OpenDate, CASE WHEN NOT s.ClosedDate IS NULL THEN 'closed' ELSE 'open' END FROM cohort AS c JOIN schools AS s ON c.code_num = CAST(s.CDSCode AS SIGNED) LEFT JOIN satscores AS t ON c.code_num = CAST(t.cds AS SIGNED) WHERE c.FRPMShare = (SELECT MIN(x.FRPMShare) FROM cohort AS x) UNION ALL SELECT 'the CDS code from my notes', c.SchoolName, s.County, s.City, s.MailStreet, s.MailCity, s.MailState, s.MailZip, s.Website, c.Enrollment, c.FRPMCount, c.FRPMShare, t.AvgScrRead + t.AvgScrMath + t.AvgScrWrite, CAST(t.NumGE1500 * 100.0 AS DOUBLE) / NULLIF(t.NumTstTakr, 0), s.OpenDate, CASE WHEN NOT s.ClosedDate IS NULL THEN 'closed' ELSE 'open' END FROM cohort AS c JOIN schools AS s ON c.code_num = CAST(s.CDSCode AS SIGNED) LEFT JOIN satscores AS t ON c.code_num = CAST(t.cds AS SIGNED) WHERE c.code_num = 4615150435602", "difficulty": "challenging"}
{"question_id": 41, "db_id": "california_schools", "question": "I'm auditing FRPM enrollment reporting and need to contact some elementary and middle schools. Please list the name and street address of every named school whose K-12 enrollment exceeds its enrollment of students aged 5-17 by more than 30 students, and whose highest grade of enrollment is grade 8 or below. Kindergarten counts as grade 8 or below. Give me one row per school; any order is fine.", "evidence": "K-12 enrollment is enrollment counted for kindergarten through grade 12. Enrollment of ages 5-17 is enrollment counted for students aged 5 through 17. Highest grade of enrollment is the highest grade level the school enrolls students in (e.g., grade 8 for a school serving kindergarten through grade 8).", "SQL": "SELECT s.School, s.Street FROM schools AS s JOIN frpm AS f ON f.`CDSCode` = s.`CDSCode` WHERE NOT s.School IS NULL AND f.`Enrollment (K-12)` - f.`Enrollment (Ages 5-17)` > 30 AND (f.`High Grade` = 'K' OR (f.`High Grade` = CAST(CAST(f.`High Grade` AS SIGNED) AS CHAR) AND CAST(f.`High Grade` AS SIGNED) <= 8)) ORDER BY s.`CDSCode`", "difficulty": "challenging"}
{"question_id": 42, "db_id": "california_schools", "question": "I'm auditing high-school-level campuses that draw enrollments beyond their surrounding school-age population. Can you give me a list of schools where the K-12 enrollment exceeds the ages-5-17 enrollment by more than 30, limited to schools whose lowest served grade is grade 9 or a later grade (a school's lowest served grade being the low end of the grade range reported in the same enrollment record as its K-12 and ages-5-17 counts)? For each school, I just need the school name and street address. Please order the results by the school's CDS code, smallest first.", "evidence": "CDS code: a school's identifier in the California schools data.", "SQL": "SELECT s.School, s.Street FROM schools AS s JOIN frpm AS f ON f.`CDSCode` = s.`CDSCode` WHERE NOT s.School IS NULL AND f.`Enrollment (K-12)` - f.`Enrollment (Ages 5-17)` > 30 AND CAST(f.`Low Grade` AS SIGNED) BETWEEN 9 AND 12 ORDER BY s.CDSCode", "difficulty": "challenging"}
{"question_id": 43, "db_id": "california_schools", "question": "I'm researching where high SAT performance coexists with concentrated poverty, to help target college-access support by county. For the 2014-15 academic year, for each county, how many schools had both a K-12 free-meal eligibility rate above 0.1 and at least one SAT taker scoring 1500 or higher on the school's own SAT record? Please list only counties that have at least one such school, with the county name and the number of its qualifying schools, sorted from most such schools to fewest, and alphabetically by county name when counties tie.", "evidence": "K-12 free-meal eligibility rate: the share of a school's K-12 enrollment that is eligible for free meals (free meal count divided by K-12 enrollment).", "SQL": "SELECT s.cname AS county, COUNT(*) AS qualifying_schools FROM satscores AS s JOIN frpm AS f ON f.CDSCode = s.cds WHERE s.rtype = 'S' AND s.NumGE1500 > 0 AND f.`Enrollment (K-12)` > 0 AND 1.0 * f.`Free Meal Count (K-12)` / f.`Enrollment (K-12)` > 0.1 GROUP BY s.cname ORDER BY qualifying_schools DESC, county ASC", "difficulty": "challenging"}
{"question_id": 44, "db_id": "california_schools", "question": "I have a school on file with CDS code 1611430131177. Find the school in the same county as that school whose own SAT record shows the most students scoring at least 1500 (not a district-wide roll-up). If two schools tie on that count, use the one with the smaller CDS code. Send me that school's administrator's first and last name.", "evidence": "CDS code: the County-District-School identifier assigned to each school; scoring at least 1500: a test taker whose combined SAT score is 1500 or higher.", "SQL": "SELECT s.AdmFName1, s.AdmLName1 FROM satscores AS x JOIN schools AS s ON s.CDSCode = x.cds JOIN frpm AS f ON f.CDSCode = x.cds WHERE x.rtype = 'S' AND s.County = (SELECT County FROM schools WHERE CAST(CDSCode AS SIGNED) = 1611430131177) ORDER BY x.NumGE1500 DESC, CAST(f.`School Code` AS SIGNED) LIMIT 1", "difficulty": "challenging"}
{"question_id": 45, "db_id": "california_schools", "question": "I'm working on a story about the largest schools in the state with the worst SAT excellence rates. Among schools where at least 700 students took the SAT, can you find the school with the lowest SAT excellence rate? If several schools tie for the lowest rate, go with the one with the smallest school code. I just need that school's street, city, ZIP code and state so I can visit and request an interview.", "evidence": "The SAT excellence rate is the share of SAT test takers scoring at least 1500. A school code is a number.", "SQL": "SELECT s.Street, s.City, s.Zip, s.State FROM satscores AS sat JOIN schools AS s ON s.CDSCode = sat.cds LEFT JOIN frpm AS f ON f.CDSCode = sat.cds WHERE sat.rtype = 'S' AND NOT sat.NumGE1500 IS NULL AND sat.NumTstTakr >= 700 ORDER BY 1.0 * sat.NumGE1500 / sat.NumTstTakr ASC, CAST(f.`School Code` AS SIGNED) ASC LIMIT 1", "difficulty": "challenging"}
{"question_id": 46, "db_id": "california_schools", "question": "I'm planning reviews of Provision 2 meal programs under the NSLP and want to see which cities concentrate magnet schools under that provision. For each city that has at least one, can you give me the number of the city's magnet schools that run a Provision 2 meal program? Use the city where the school is located, not its mailing city. Also, if a school's NSLP entry lists multiple provision types, don't count it as running Provision 2.", "evidence": "NSLP is the National School Lunch Program. Provision 2 is a federal provision under the NSLP that lets a school serve meals at no charge to all students regardless of family income.", "SQL": "SELECT s.City AS City, COUNT(*) AS magnet_schools FROM frpm AS f JOIN schools AS s ON f.CDSCode = s.CDSCode WHERE s.Magnet = 1 AND f.`NSLP Provision Status` LIKE '%Provision 2%' GROUP BY s.City ORDER BY magnet_schools DESC, City", "difficulty": "challenging"}
{"question_id": 47, "db_id": "california_schools", "question": "I'm preparing a mailing campaign and need a list of public high schools in Los Angeles County that have more than 500 free or reduced-price meal recipients ages 5-17. By public high schools I mean every public high-school category in the meal program report - regular high schools, continuation high schools, and high schools in single-school districts - not just regular ones; middle and junior high schools don't count. For each school, please give me the school name exactly as listed in the school directory, plus the campus (physical) street address - not a mailing or post-office address - along with the city, state and ZIP code, each as a separate field. Schools sharing a name are separate schools, so one row per school. Please sort the list by school name.", "evidence": "'Free or reduced-price meal recipients ages 5-17' refers to the count reported in the meal program report for students ages 5-17 receiving free or reduced-price meals.", "SQL": "SELECT s.School AS school_name, s.Street, s.City, s.State, s.Zip FROM frpm AS f JOIN schools AS s ON f.CDSCode = s.CDSCode WHERE f.`County Name` = 'Los Angeles' AND f.`School Type` LIKE '%High School%' AND f.`School Type` NOT LIKE '%Junior%' AND f.`FRPM Count (Ages 5-17)` > 500 ORDER BY s.School COLLATE utf8mb4_bin, s.CDSCode", "difficulty": "challenging"}
{"question_id": 48, "db_id": "california_schools", "question": "I'd like to compare SAT participation across counties in California that run magnet schools under Provision 2 of the National School Lunch Program. For every county with at least one Provision 2 magnet school, can you give me the county name and the total number of SAT test takers from those schools? Please include every such county even if the total is 0, and list them in any order.", "evidence": "Provision 2 school: a school whose NSLP Provision Status is Provision 2. Magnet school: a school identified as a magnet school or providing a magnet program.", "SQL": "SELECT s.County AS county, SUM(COALESCE(sc.NumTstTakr, 0)) AS total_sat_test_takers FROM schools AS s INNER JOIN frpm AS f ON s.CDSCode = f.CDSCode LEFT JOIN satscores AS sc ON sc.cds = s.CDSCode WHERE s.Magnet = 1 AND f.`NSLP Provision Status` = 'Provision 2' GROUP BY s.County ORDER BY total_sat_test_takers DESC, s.County", "difficulty": "challenging"}
{"question_id": 49, "db_id": "card_games", "question": "List the IDs of borderless card printings for which Card Kingdom lacks a regular-version listing or a foil-version listing.", "evidence": "", "SQL": "SELECT id FROM cards WHERE borderColor = 'borderless' AND (cardKingdomId IS NULL OR cardKingdomFoilId IS NULL) ORDER BY id", "difficulty": "simple"}
{"question_id": 50, "db_id": "card_games", "question": "Which distinct combinations of card name, artist, and promotional-printing flag occur among the printings tied for the most rulings?", "evidence": "", "SQL": "WITH ruling_counts AS (SELECT uuid, COUNT(*) AS n FROM rulings GROUP BY uuid), max_count AS (SELECT MAX(n) AS n FROM ruling_counts) SELECT DISTINCT c.name, c.artist, c.isPromo FROM cards AS c JOIN ruling_counts AS rc ON c.uuid = rc.uuid JOIN max_count AS mx ON rc.n = mx.n ORDER BY c.name, c.artist, c.isPromo", "difficulty": "moderate"}
{"question_id": 51, "db_id": "card_games", "question": "What percentage of all card printings have a Simplified Chinese translation? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * (SELECT COUNT(DISTINCT c.uuid) FROM cards AS c JOIN foreign_data AS f ON f.uuid = c.uuid WHERE f.language = 'Chinese Simplified') / NULLIF((SELECT COUNT(*) FROM cards), 0), 2)", "difficulty": "moderate"}
{"question_id": 52, "db_id": "card_games", "question": "What rules text is printed on Benalish Knight? Return the distinct text as one line.", "evidence": "", "SQL": "SELECT DISTINCT REPLACE(text, CHAR(10), ' ') FROM cards WHERE name = 'Benalish Knight' AND NOT text IS NULL", "difficulty": "simple"}
{"question_id": 53, "db_id": "card_games", "question": "Among all Story Spotlight card printings, what percentage have a French translation? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * (SELECT COUNT(DISTINCT c.uuid) FROM cards AS c JOIN foreign_data AS f ON f.uuid = c.uuid WHERE c.isStorySpotlight = 1 AND f.language = 'French') / NULLIF((SELECT COUNT(*) FROM cards WHERE isStorySpotlight = 1), 0), 2)", "difficulty": "challenging"}
{"question_id": 54, "db_id": "card_games", "question": "What are the cards belong to duel deck a? List the ID.", "evidence": "", "SQL": "SELECT id FROM cards WHERE duelDeck = 'a'", "difficulty": "simple"}
{"question_id": 55, "db_id": "card_games", "question": "How many distinct white-bordered card printings are banned in at least one play format?", "evidence": "", "SQL": "SELECT COUNT(DISTINCT c.id) FROM cards AS c JOIN legalities AS l ON l.uuid = c.uuid WHERE l.status = 'Banned' AND c.borderColor = 'white'", "difficulty": "simple"}
{"question_id": 56, "db_id": "card_games", "question": "How many distinct card printings with no recorded power value or a variable power expression have at least one ruling mentioning 'triggered ability'?", "evidence": "An asterisk anywhere in a power expression denotes variable power.", "SQL": "SELECT COUNT(DISTINCT T1.id) FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE (T1.power IS NULL OR T1.power LIKE '%*%') AND T2.text LIKE '%triggered ability%'", "difficulty": "moderate"}
{"question_id": 57, "db_id": "card_games", "question": "What percentage of cards with format commander and legal status do not have a content warning?", "evidence": "", "SQL": "SELECT CAST(SUM(CASE WHEN T1.hasContentWarning = 0 THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(T1.id) FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T2.format = 'commander' AND T2.status = 'Legal'", "difficulty": "challenging"}
{"question_id": 58, "db_id": "card_games", "question": "Among card printings with no recorded power value or a variable power expression, what percentage have a French translation? Round to two decimals.", "evidence": "An asterisk anywhere in a power expression denotes variable power.", "SQL": "SELECT ROUND(100.0 * (SELECT COUNT(DISTINCT c.uuid) FROM cards AS c JOIN foreign_data AS f ON f.uuid = c.uuid WHERE (c.power IS NULL OR c.power LIKE '%*%') AND f.language = 'French') / NULLIF((SELECT COUNT(*) FROM cards WHERE power IS NULL OR power LIKE '%*%'), 0), 2)", "difficulty": "challenging"}
{"question_id": 59, "db_id": "card_games", "question": "Among the sets in the block \"Ice Age\", how many of them have an Italian translation?", "evidence": "", "SQL": "SELECT COUNT(DISTINCT T1.id) FROM sets AS T1 INNER JOIN set_translations AS T2 ON T2.setCode = T1.code WHERE T1.block = 'Ice Age' AND T2.language = 'Italian' AND NOT T2.translation IS NULL", "difficulty": "moderate"}
{"question_id": 60, "db_id": "card_games", "question": "What percentage of Coldsnap card printings have both a Card Kingdom regular-product ID and foil-product ID recorded?", "evidence": "", "SQL": "SELECT CAST(SUM(CASE WHEN NOT T1.cardKingdomFoilId IS NULL AND NOT T1.cardKingdomId IS NULL THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(T1.id) FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Coldsnap'", "difficulty": "challenging"}
{"question_id": 61, "db_id": "card_games", "question": "Which play format has the most banned card-printing records? Give that format and the distinct names of its banned cards.", "evidence": "", "SQL": "SELECT format, name FROM (SELECT l.format, c.name, MIN(c.uuid) AS sort_uuid FROM legalities AS l JOIN cards AS c ON c.uuid = l.uuid WHERE l.status = 'Banned' AND l.format = (SELECT format FROM legalities WHERE status = 'Banned' GROUP BY format ORDER BY COUNT(*) DESC, format LIMIT 1) GROUP BY l.format, c.name) AS banned_names ORDER BY sort_uuid", "difficulty": "moderate"}
{"question_id": 62, "db_id": "card_games", "question": "I collect promotional printings and play Brawl. How many different creature cards that have a promotional printing can serve as a Brawl commander? I just want a single number back.", "evidence": "A promotional printing is a printing of a card made as a promotion, as opposed to a regular set printing. Brawl is a Magic: The Gathering format; the deck's commander is the card that leads it, and only certain cards are legal as a Brawl commander.", "SQL": "SELECT COUNT(DISTINCT name) AS creature_cards_legal_brawl_commanders FROM cards WHERE isPromo = 1 AND LOCATE('Creature', types) > 0 AND LOCATE('''brawl'': True', leadershipSkills) > 0", "difficulty": "challenging"}
{"question_id": 63, "db_id": "card_games", "question": "I'm cataloguing how the frame styles on Tarmogoyf's printings evolved over time. What is the number of years between the oldest and the newest frame style used on the printings of Tarmogoyf? The span in years is the newer year minus the older year.", "evidence": "Frame style version means the year a card's frame style dates from.", "SQL": "SELECT MAX(CAST(frameVersion AS SIGNED)) - MIN(CAST(frameVersion AS SIGNED)) AS years_between FROM cards WHERE name = 'Tarmogoyf' AND frameVersion = CAST(CAST(frameVersion AS SIGNED) AS CHAR)", "difficulty": "challenging"}
{"question_id": 64, "db_id": "card_games", "question": "How many black-border cards with power 10 or greater are available on Magic: The Gathering Online? I just want a single number.", "evidence": "Black-border cards are the tournament-legal Magic cards, excluding the joke silver-bordered sets. Power is the first number in the lower-right corner of a creature card.", "SQL": "SELECT COUNT(id) FROM cards WHERE borderColor = 'black' AND availability LIKE '%mtgo%' AND CAST(power AS SIGNED) >= 10", "difficulty": "challenging"}
{"question_id": 65, "db_id": "card_games", "question": "I have the count of sets with fewer than five translations of their name — now I need the gap in cards to size the translation budget. Can you give me the total number of cards contained in those sets? A few things to keep in mind: 'fewer than five' is strict, so a set with exactly five translations doesn't count. All sets count regardless of type or release (core set, expansion, promotional, online-only, etc.). If two languages have the identical translated name string for a set, that's one translation, not two. And a set's card count should be its full size, including promotional and related supplemental printings.", "evidence": "A 'translation of a set's name' means the localized name of the set in another language, e.g. its French or Simplified Chinese name.", "SQL": "SELECT SUM(totalSetSize) AS total_cards FROM sets WHERE (SELECT COUNT(DISTINCT translation) FROM set_translations WHERE setCode = sets.code) < 5", "difficulty": "challenging"}
{"question_id": 66, "db_id": "card_games", "question": "I'm preparing a multilingual catalog and want to gauge how much localizable content exists per kind of set. For every set type, I need the number of sets of that type that have an officially translated name, and the total number of cards in those sets. Please include every set type in the results, even ones where no set has an officially translated name (show zero for both values in that case), and sort the results alphabetically by set type.", "evidence": "Set type: the expansion type of a set, such as core, expansion or promo. Officially translated name: the set's name rendered in another language, such as Italian or Chinese Traditional.", "SQL": "SELECT s.type, SUM(CASE WHEN EXISTS(SELECT 1 FROM set_translations AS t WHERE t.setCode = s.code) THEN 1 ELSE 0 END) AS sets_with_translation, SUM(CASE WHEN EXISTS(SELECT 1 FROM set_translations AS t WHERE t.setCode = s.code) THEN s.totalSetSize ELSE 0 END) AS total_cards FROM sets AS s GROUP BY s.type ORDER BY s.type", "difficulty": "challenging"}
{"question_id": 67, "db_id": "card_games", "question": "How many rulings were issued for Mishra's Factory on the latest date any ruling for it exists? By \"latest date\" I mean the most recent calendar date on which any ruling for the card exists, and by Mishra's Factory I mean the card by that name across all of its printings. I only want that count.", "evidence": "ruling: an official rules statement issued for a card on a given date", "SQL": "SELECT COUNT(DISTINCT T2.text) AS ruling_count FROM cards AS T1 INNER JOIN rulings AS T2 ON T1.uuid = T2.uuid WHERE T1.name = 'Mishra''s Factory' AND T2.date = (SELECT MAX(T4.date) FROM cards AS T3 INNER JOIN rulings AS T4 ON T3.uuid = T4.uuid WHERE T3.name = 'Mishra''s Factory')", "difficulty": "challenging"}
{"question_id": 68, "db_id": "card_games", "question": "Which artist has illustrated the most different creature cards, and how many different creature cards is that? I'd like each artist's name along with their count of different creature cards. If two artists are tied for the most, list both.", "evidence": "A creature card is a card whose card types include Creature.", "SQL": "SELECT artist, COUNT(DISTINCT name) AS distinct_creatures FROM cards WHERE types LIKE '%Creature%' GROUP BY artist HAVING COUNT(DISTINCT name) = (SELECT MAX(cnt) FROM (SELECT COUNT(DISTINCT name) AS cnt FROM cards WHERE types LIKE '%Creature%' GROUP BY artist) AS __photo_derived_1) ORDER BY artist", "difficulty": "challenging"}
{"question_id": 69, "db_id": "card_games", "question": "I'm putting together a showcase of zero-mana-cost cards. What is the newest frame version used by any card with a converted mana cost of 0? Please give me that frame version value, and the number of cards in the database that use that frame version. The count should cover all cards in the database, not just the zero-cost ones. If several frame versions tie as the newest, give me each of them with its own count.", "evidence": "Frame version: the edition of the card frame style a printing uses.", "SQL": "SELECT frameVersion, COUNT(*) AS card_count FROM cards WHERE CAST(frameVersion AS FLOAT) = (SELECT MAX(CAST(frameVersion AS FLOAT)) FROM cards WHERE convertedManaCost = 0) GROUP BY frameVersion", "difficulty": "challenging"}
{"question_id": 70, "db_id": "card_games", "question": "I'm tracking printings of Tarmogoyf. Of all its printings, which frame version is the newest? Please give me the year that identifies that latest frame version, and the percentage of the card's printings that use it, rounded to two decimal places. The percentage should be over all printings of the card.", "evidence": "A printing is an occurrence of the card in a set; a frame version is the version of the card frame style of a printing.", "SQL": "WITH target AS (SELECT MAX(CAST(frameVersion AS SIGNED)) AS yr FROM cards WHERE name = 'Tarmogoyf') SELECT t.yr AS frame_version_year, ROUND(CAST(SUM(CASE WHEN CAST(c.frameVersion AS SIGNED) = t.yr THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(c.id), 2) AS percentage FROM cards AS c CROSS JOIN target AS t WHERE c.name = 'Tarmogoyf' GROUP BY t.yr", "difficulty": "challenging"}
{"question_id": 71, "db_id": "card_games", "question": "I'm building an artifact-heavy Commander deck and want to know the size of the pool of zero-cost cards available to me. How many different cards have a printed mana cost of {0} and are legal in Commander? A card is legal in Commander if its Commander legality entry is marked Legal.", "evidence": "Printed mana cost of 0 means the cost shown on the card is {0}. Commander is a format of play in which any card marked Legal for that format is playable.", "SQL": "SELECT COUNT(DISTINCT c.name) AS different_cards FROM cards AS c JOIN legalities AS l ON c.uuid = l.uuid WHERE c.manaCost = '{0}' AND l.format = 'commander' AND l.status = 'Legal'", "difficulty": "challenging"}
{"question_id": 72, "db_id": "card_games", "question": "I'm brewing and looking for cards that combine two keyword abilities. How many cards in the collection have both Flying and Cycling? Note that each printing counts as its own card, and a card only counts if it has both keywords.", "evidence": "Flying and Cycling are keyword abilities in Magic: The Gathering.", "SQL": "SELECT COUNT(*) AS card_count FROM cards WHERE LOCATE(CONCAT(',', 'Flying', ','), CONCAT(',', keywords, ',')) > 0 AND LOCATE(CONCAT(',', 'Cycling', ','), CONCAT(',', keywords, ',')) > 0", "difficulty": "challenging"}
{"question_id": 73, "db_id": "card_games", "question": "I'm comparing how mana-cheap Magic: The Gathering sets have become over time. For two sets — the set where Abyssal Horror was first printed, and the most recently released set in the database — I want one row per set with the set name and the percentage of that set's cards that have a mana cost whose converted mana cost is 3 or less, rounded to two decimal places. By \"first printed\", I mean the set with the earliest release date among the sets Abyssal Horror appears in; if several share that earliest date, use the one whose set code comes first alphabetically. For the most recent set, use the latest release date among all sets; if several share that date, again take the one whose set code comes first alphabetically. By \"converted mana cost\" I mean the card's mana value, and a card counts as having a mana cost only if a mana cost is printed on it.", "evidence": "Converted mana cost means the card's mana value; a card has a mana cost when a mana cost is printed on the card.", "SQL": "WITH first_set AS (SELECT s.code, s.name, s.releaseDate FROM sets AS s WHERE s.code IN (SELECT c.setCode FROM cards AS c WHERE c.name = 'Abyssal Horror') ORDER BY s.releaseDate ASC, s.code ASC LIMIT 1), latest_set AS (SELECT s.code, s.name, s.releaseDate FROM sets AS s ORDER BY s.releaseDate DESC, s.code ASC LIMIT 1), chosen AS (SELECT code, name, releaseDate FROM first_set UNION ALL SELECT code, name, releaseDate FROM latest_set) SELECT ch.name AS set_name, ROUND(CAST(SUM(CASE WHEN NOT c.manaCost IS NULL AND c.manaCost <> '' AND c.convertedManaCost <= 3 THEN 1 ELSE 0 END) AS FLOAT) * 100.0 / COUNT(c.id), 2) AS pct FROM chosen AS ch JOIN cards AS c ON c.setCode = ch.code GROUP BY ch.code, ch.name, ch.releaseDate ORDER BY ch.releaseDate ASC", "difficulty": "challenging"}
{"question_id": 74, "db_id": "card_games", "question": "How many different cards have ever been printed as a release promotion? I just need a single number, covering all printings across the game's entire history with no time restriction. Note that a prerelease printing is a different promotion type and shouldn't be counted as a release promotion.", "evidence": "A release promotion is a promotional printing whose promotion type is 'release'.", "SQL": "SELECT COUNT(DISTINCT name) AS release_promo_cards FROM cards WHERE REPLACE(promoTypes, 'prerelease', '') LIKE '%release%'", "difficulty": "challenging"}
{"question_id": 75, "db_id": "card_games", "question": "I'm cataloguing the Abzan clan's cards and need this: among the cards with the Abzan watermark, which one comes last in its set's numbering - i.e. has the highest collector number? Please give me the card's name, its collector number, and how many foreign-language printings exist for that card. If several Abzan-watermarked cards tie for the highest collector number, list every one of them, each with its own count of foreign-language printings. Count each foreign-language edition record of the card as one printing.", "evidence": "Abzan watermark: the clan mark printed on the card. Collector number: the number of the card within the set it was printed in. Foreign-language printing: the foreign-language edition record of a card.", "SQL": "SELECT c.name AS card_name, c.number AS collector_number, COUNT(f.id) AS foreign_printings FROM cards AS c LEFT JOIN foreign_data AS f ON f.uuid = c.uuid WHERE c.watermark = 'abzan' AND CAST(c.number AS SIGNED) = (SELECT MAX(CAST(number AS SIGNED)) FROM cards WHERE watermark = 'abzan') GROUP BY c.uuid, c.name, c.number ORDER BY c.name", "difficulty": "challenging"}
{"question_id": 76, "db_id": "card_games", "question": "I'm profiling the weak end of the white-bordered printings. How many white-bordered cards have a power less than 3? I just need that single count - only white-bordered cards are in scope, and please don't include anything else in the answer.", "evidence": "Power is a card's combat strength. A card whose power is shown as * has no known power.", "SQL": "SELECT COUNT(*) AS weak_attackers FROM cards WHERE borderColor = 'white' AND NOT power IS NULL AND power <> '*' AND power = CAST(CAST(power AS SIGNED) AS CHAR) AND CAST(power AS SIGNED) < 3", "difficulty": "challenging"}
{"question_id": 77, "db_id": "card_games", "question": "I'm putting together a showcase of instant-speed cards from Magic: The Gathering. Which cards in the Dark Ascension set have the Flash keyword and, among those, the highest converted mana cost? Please list just the card names, one row per card, alphabetically by name, and include every card that ties on that highest cost.", "evidence": "Dark Ascension is the Magic: The Gathering set named 'Dark Ascension'. Flash is the keyword that lets a card be cast any time you could cast an instant. Converted mana cost is the total amount of mana a card costs to cast.", "SQL": "SELECT T1.name FROM cards AS T1 INNER JOIN sets AS T2 ON T2.code = T1.setCode WHERE T2.name = 'Dark Ascension' AND LOCATE(CONCAT(',', 'Flash', ','), CONCAT(',', T1.keywords, ',')) > 0 AND T1.convertedManaCost = (SELECT MAX(T3.convertedManaCost) FROM cards AS T3 INNER JOIN sets AS T4 ON T4.code = T3.setCode WHERE T4.name = 'Dark Ascension' AND LOCATE(CONCAT(',', 'Flash', ','), CONCAT(',', T3.keywords, ',')) > 0) ORDER BY T1.name ASC", "difficulty": "challenging"}
{"question_id": 78, "db_id": "card_games", "question": "I'm preparing localized set icon assets and need to know the foreign-language name coverage of every Magic: The Gathering set released in 2020. For each set released in 2020 (meaning its release date falls within the calendar year 2020), please give me the set's name, its keyrune code, and the number of languages in which the set has an official translated name. Nothing else.", "evidence": "keyrune code: the code for the set's image icon; official translated name: the set's name rendered in a foreign language by the game's publisher.", "SQL": "SELECT s.name, s.keyruneCode, COUNT(DISTINCT st.language) AS translated_languages FROM sets AS s LEFT JOIN set_translations AS st ON st.setCode = s.code AND NOT st.translation IS NULL WHERE DATE_FORMAT(s.releaseDate, '%Y') = '2020' GROUP BY s.id, s.name, s.keyruneCode ORDER BY s.name", "difficulty": "challenging"}
{"question_id": 79, "db_id": "card_games", "question": "I'm sizing a catalogue page of 2017 sets that were localized for international markets. How many cards were there in total across the Magic: The Gathering sets released in 2017 (between January 1 and December 31, 2017) that have a name in a language other than English? A set counts as localized if its name has a foreign-language translation. Include every card in each qualifying set, counting promotional and related supplemental printings as part of the set. I just need the single total across all qualifying sets, not per-set numbers.", "evidence": "A foreign-language translation is a set's name rendered in a language other than English (e.g. Chinese Simplified, German, Spanish).", "SQL": "SELECT SUM(s.totalSetSize) AS total_cards FROM sets AS s WHERE s.releaseDate BETWEEN '2017-01-01' AND '2017-12-31' AND EXISTS(SELECT 1 FROM set_translations AS t WHERE t.setCode = s.code)", "difficulty": "challenging"}
{"question_id": 80, "db_id": "card_games", "question": "I've already looked at the heavy hitters in duel deck B (the 'b' deck). Now I want to check the light end: how many cards in duel deck B are not available in foil and have attack power below 3? Note that 'below 3' means strictly below 3 — a power of exactly 3 doesn't count.", "evidence": "", "SQL": "SELECT COUNT(*) AS card_count FROM cards WHERE duelDeck = 'b' AND hasFoil = 0 AND NOT power IS NULL AND power = TRIM(CAST(power AS SIGNED)) AND CAST(power AS FLOAT) < 3", "difficulty": "challenging"}
{"question_id": 81, "db_id": "card_games", "question": "I'm writing a spotlight piece on card artists, and I need to know: among black-bordered cards that are obtainable on Magic Arena and have a printed power of 10 or greater, which artist illustrated the most of them? Please give me the artist's name and the number of those cards they illustrated. A card counts even if it's also available outside Arena, as long as it can be obtained on Arena. If several artists tie for the most, list every one of them along with that count.", "evidence": "Black border means the card's border color is black; power is the combat strength printed on a creature card, and '10 or greater' means the printed power reads as a number that is at least 10 (10, 11, 12, and so on).", "SQL": "WITH counts AS (SELECT artist, COUNT(*) AS card_count FROM cards WHERE borderColor = 'black' AND LOWER(availability) LIKE '%arena%' AND CAST(power AS SIGNED) >= 10 GROUP BY artist) SELECT artist, card_count FROM counts WHERE card_count = (SELECT MAX(card_count) FROM counts)", "difficulty": "challenging"}
{"question_id": 82, "db_id": "card_games", "question": "I'm going through my paper collection before sharing it publicly, and I want to check something about the cards Wizards of the Coast has flagged. How many different cards are there that carry a sensitive content warning, are available in paper form, and have never been available on Magic Online (MTGO)? I just need that one count.", "evidence": "MTGO means Magic: The Gathering Online, the official online version of the game. A sensitive content warning means Wizards of the Coast has marked the card for having sensitive content.", "SQL": "SELECT COUNT(*) AS card_count FROM (SELECT name FROM cards WHERE hasContentWarning = 1 GROUP BY name HAVING MAX(CASE WHEN availability LIKE '%paper%' THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN availability LIKE '%mtgo%' THEN 1 ELSE 0 END) = 0) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 83, "db_id": "card_games", "question": "Hi! I'm preparing a licensing brief for our Japanese partner about Magic: The Gathering localization coverage. Could you pull a report of every expansion type (core, expansion, promo, etc.), showing for each one how many sets of that type carry a Japanese name entry? A Japanese name entry means the set's name-translations include a Japanese-language entry giving the set's name in Japanese. Please include every expansion type in the report even if none of its sets have such an entry (show 0 for those), and sort the results alphabetically by expansion type. Nothing else needed - just the expansion type and the count.", "evidence": "Japanese name entry: an entry in the set's name-translations whose language is Japanese and which gives the set's name in Japanese.", "SQL": "SELECT s.type AS expansion_type, COUNT(DISTINCT CASE WHEN st.language = 'Japanese' AND NOT st.translation IS NULL AND TRIM(st.translation) <> '' THEN s.code END) AS japanese_named_sets FROM sets AS s LEFT JOIN set_translations AS st ON st.setCode = s.code GROUP BY s.type ORDER BY s.type", "difficulty": "challenging"}
{"question_id": 84, "db_id": "card_games", "question": "I'm cataloguing Arena-exclusive illustrated art of big creatures. How many artists have illustrated at least one black-bordered card that is available on Arena but never on Magic Online and has a fixed printed power of at least 5? I want just the number of artists, nothing else. Count across all printings in the collection with no time restriction. Note that a card whose power varies is not a fixed number, so it shouldn't count as power 5 or more.", "evidence": "Arena and Magic Online are online platforms; a card's availability lists every platform it can be played on: 'arena' is Arena and 'mtgo' is Magic Online. Power is the attack strength printed on a creature card. Black-bordered refers to the standard card border color black.", "SQL": "SELECT COUNT(DISTINCT artist) AS artists FROM cards WHERE borderColor = 'black' AND availability LIKE '%arena%' AND availability NOT LIKE '%mtgo%' AND CAST(power AS FLOAT) >= 5", "difficulty": "challenging"}
{"question_id": 85, "db_id": "card_games", "question": "I collect trading cards, and one of my favorites is Ancestor's Chosen. Of all the sets that include this card, look at the one released most recently - if several sets share that latest release date, consider them together. How many creature cards in that set (or sets) have power greater than toughness? I just want that single count, nothing else.", "evidence": "Power is the attack strength printed on a creature card; toughness is the defense strength printed on a creature card.", "SQL": "SELECT COUNT(*) AS power_over_toughness FROM cards WHERE types LIKE '%Creature%' AND CAST(power AS FLOAT) > CAST(toughness AS FLOAT) AND setCode IN (SELECT c2.setCode FROM cards AS c2 JOIN sets AS s2 ON s2.code = c2.setCode WHERE c2.name = 'Ancestor''s Chosen' AND s2.releaseDate = (SELECT MAX(s3.releaseDate) FROM sets AS s3 JOIN cards AS c3 ON c3.setCode = s3.code WHERE c3.name = 'Ancestor''s Chosen'))", "difficulty": "challenging"}
{"question_id": 86, "db_id": "card_games", "question": "Among the Commander-leadable cards that the Card Kingdom catalog lists for both a foil printing and a regular non-foil printing – cards listed for only one of the two printings don't count – I want the single most recent card frame year (the latest calendar year among the frame versions), and the count of cards in that group whose frame version is that year. Please return just that one row: the frame year and its card count.", "evidence": "A card 'may lead a Commander deck' if it can be the deck's commander – the one card that leads the deck and sets its color identity – not merely be included among the deck's other cards.", "SQL": "WITH cmd AS (SELECT frameVersion, SUBSTRING(leadershipSkills, LOCATE('commander', leadershipSkills)) AS tail FROM cards WHERE NOT cardKingdomId IS NULL AND NOT cardKingdomFoilId IS NULL) SELECT frameVersion AS frame_year, COUNT(*) AS card_count FROM cmd WHERE SUBSTRING(tail, CHAR_LENGTH('commander') + CHAR_LENGTH('True'), CHAR_LENGTH('True')) = 'True' GROUP BY frameVersion ORDER BY CAST(frameVersion AS SIGNED) DESC LIMIT 1", "difficulty": "challenging"}
{"question_id": 87, "db_id": "card_games", "question": "I'm compiling the official rulings archive for the Magic: The Gathering card Fireball. How many official rulings have ever been issued for Fireball? I need the total across all time, with no date restriction.", "evidence": "A ruling is an official clarification issued by Wizards of the Coast about how a card works.", "SQL": "SELECT COUNT(*) AS ruling_count FROM (SELECT DISTINCT r.date, r.text FROM rulings AS r INNER JOIN cards AS c ON r.uuid = c.uuid WHERE c.name = 'Fireball') AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 88, "db_id": "card_games", "question": "Which card whose original type is 'Creature - Elf' has received the most rulings, and how many rulings has it received? I want the card name and the number of rulings. A card and all of its printings/reprints count as one and the same card. If several cards tie for the most rulings, list every one of them.", "evidence": "A ruling is an official rules clarification issued for a card, on the date it was issued.", "SQL": "WITH elf_cards AS (SELECT DISTINCT name FROM cards WHERE originalType = 'Creature - Elf'), elf_rulings AS (SELECT c.name, r.date, r.text FROM cards AS c JOIN rulings AS r ON c.uuid = r.uuid WHERE c.name IN (SELECT name FROM elf_cards) GROUP BY c.name, r.date, r.text), counts AS (SELECT name, COUNT(*) AS ruling_count FROM elf_rulings GROUP BY name) SELECT name, ruling_count FROM counts WHERE ruling_count = (SELECT MAX(ruling_count) FROM counts) ORDER BY name", "difficulty": "challenging"}
{"question_id": 89, "db_id": "card_games", "question": "I'm reviewing the very first cards in the database and want to compare how widely accepted white cards are versus black cards across play formats. For each card color that appears among the cards with ID 1 through 20, please tell me the card color and the number of play formats in which cards of that color are legal. A card only counts as legal in a format if its legality status for that format is 'Legal' - banned or restricted doesn't count.", "evidence": "Formats of play: the game formats a card is permitted in, such as commander or vintage.", "SQL": "SELECT T1.colors AS color, COUNT(DISTINCT T2.format) AS format_count FROM cards AS T1 INNER JOIN legalities AS T2 ON T1.uuid = T2.uuid WHERE T1.id BETWEEN 1 AND 20 AND T2.status = 'Legal' GROUP BY T1.colors ORDER BY T1.colors", "difficulty": "challenging"}
{"question_id": 90, "db_id": "card_games", "question": "I'm tracking John Avon's artwork. Among his cards that exist as powerful foils, what is the most recent frame year, and how many of those cards carry it? If several years are tied for most recent, give each year with its own count. Match John Avon on the illustrator's name.", "evidence": "powerful foil: a card whose Card Kingdom identifiers are both present – the regular identifier and the foil identifier.", "SQL": "SELECT frameVersion AS frame_year, COUNT(id) AS card_count FROM cards WHERE artist = 'John Avon' AND NOT cardKingdomId IS NULL AND NOT cardKingdomFoilId IS NULL GROUP BY frameVersion HAVING CAST(frameVersion AS SIGNED) = (SELECT MAX(CAST(frameVersion AS SIGNED)) FROM cards WHERE artist = 'John Avon' AND NOT cardKingdomId IS NULL AND NOT cardKingdomFoilId IS NULL)", "difficulty": "challenging"}
{"question_id": 91, "db_id": "card_games", "question": "I play paper Magic and I'm building a pauper deck. How many printings of cards illustrated by Erica Yang are legal in the pauper format and exist as paper (physically printed) cards? I want just a single count of printings, with each printing counted separately.", "evidence": "Pauper is a Magic: The Gathering format where only common-rarity cards are legal; a printing is a specific physical or digital release of a card in a set; 'legal in pauper' means the card's pauper legality status is Legal; 'paper' means a physical printed card.", "SQL": "SELECT COUNT(*) AS paper_pauper_printings FROM cards AS c INNER JOIN legalities AS l ON c.uuid = l.uuid WHERE c.artist = 'Erica Yang' AND l.format = 'pauper' AND l.status = 'Legal' AND c.availability LIKE '%paper%'", "difficulty": "challenging"}
{"question_id": 92, "db_id": "card_games", "question": "I keep a Card Kingdom catalogue and want to list the creature cards that Card Kingdom stocks in both foil and non-foil printings. A card counts as stocked in both printings when both its Card Kingdom Foil id and its Card Kingdom id are present. Please give me one row per card, with each card's Card Kingdom Foil id and Card Kingdom id, and nothing else. I only need the three cards with the lowest Card Kingdom Foil ids in alphabetical order, with ties broken by the Card Kingdom id.", "evidence": "Card Kingdom Foil id: the retailer's identifier for the foil printing; Card Kingdom id: the retailer's identifier for the non-foil printing.", "SQL": "SELECT cardKingdomFoilId, cardKingdomId FROM cards WHERE NOT cardKingdomFoilId IS NULL AND NOT cardKingdomId IS NULL AND types LIKE '%Creature%' ORDER BY cardKingdomFoilId, cardKingdomId LIMIT 3", "difficulty": "challenging"}
{"question_id": 93, "db_id": "card_games", "question": "Among the cards carrying the boros watermark that were printed in a foreign language, which card type is the most common, and how many of those cards have that type? If several types tie for the most, list all of them with their counts.", "evidence": "\"Boros watermark\" refers to the guild watermark appearing on cards of the Boros guild; \"printed in a foreign language\" means the card was printed in any language other than English.", "SQL": "WITH counted AS (SELECT T1.type AS card_type, COUNT(DISTINCT T1.uuid) AS card_count FROM cards AS T1 INNER JOIN foreign_data AS T2 ON T1.uuid = T2.uuid WHERE T1.watermark = 'boros' GROUP BY T1.type) SELECT card_type, card_count FROM counted WHERE card_count = (SELECT MAX(card_count) FROM counted) ORDER BY card_type", "difficulty": "challenging"}
{"question_id": 94, "db_id": "card_games", "question": "Among the Magic: The Gathering cards whose watermark is one of the ten Ravnica guild symbols (Azorius, Boros, Dimir, Golgari, Gruul, Izzet, Orzhov, Rakdos, Selesnya, Simic), which guild has the most cards that were printed in another language, and how many of that guild's cards is that? If several guilds tie for the most, give me each tied guild along with the number.", "evidence": "A Ravnica guild is the guild a card's watermark belongs to; a card 'printed in another language' is a card that exists in a language edition other than English.", "SQL": "WITH counted AS (SELECT c.watermark AS guild, COUNT(DISTINCT c.uuid) AS number_of_cards FROM cards AS c INNER JOIN foreign_data AS f ON f.uuid = c.uuid WHERE c.watermark IN ('azorius', 'boros', 'dimir', 'golgari', 'gruul', 'izzet', 'orzhov', 'rakdos', 'selesnya', 'simic') GROUP BY c.watermark) SELECT guild, number_of_cards FROM counted WHERE number_of_cards = (SELECT MAX(number_of_cards) FROM counted) ORDER BY guild", "difficulty": "challenging"}
{"question_id": 95, "db_id": "card_games", "question": "I'm cataloguing the guild cards. Among the cards that carry the Azorius watermark and were printed in at least one foreign language, how many cards are there of each card type? For each card type, please give me the card type exactly as printed, including any supertypes and subtypes, along with the number of cards of that type. List every card type that qualifies, sorted from the largest count to the smallest, and alphabetically by card type when counts are equal.", "evidence": "", "SQL": "SELECT c.type, COUNT(DISTINCT c.uuid) AS number_of_cards FROM cards AS c INNER JOIN foreign_data AS f ON f.uuid = c.uuid WHERE c.watermark = 'azorius' GROUP BY c.type ORDER BY number_of_cards DESC, c.type ASC", "difficulty": "challenging"}
{"question_id": 96, "db_id": "card_games", "question": "I'm cataloguing modern-frame printings. How many different cards that have a text box were printed with a frame version of 2015 or a later year? I just need that single count.", "evidence": "Frame version: the version of the card frame style, given as the year the frame style was introduced.", "SQL": "SELECT COUNT(DISTINCT name) AS number_of_cards FROM cards WHERE isTextless = 0 AND CAST(frameVersion AS SIGNED) >= 2015", "difficulty": "challenging"}
{"question_id": 97, "db_id": "card_games", "question": "I'm putting together a showcase of promotional cards and need a list of card names. I want the names of the cards that have a promotional printing and have multiple faces on the same card, but only those printed in the most recent card frame version. A card's frame version is the year its frame style was introduced, so the most recent frame version is the one with the latest year - and it should be the newest frame style overall, not just among promotional multi-faced cards. Please list each card's name once.", "evidence": "A promotional printing is a printing of a card that was given out for promotional purposes. A card with multiple faces has multiple faces printed on the same card.", "SQL": "SELECT DISTINCT name FROM cards WHERE isPromo = 1 AND NOT side IS NULL AND CAST(frameVersion AS SIGNED) = (SELECT MAX(CAST(frameVersion AS SIGNED)) FROM cards)", "difficulty": "challenging"}
{"question_id": 98, "db_id": "card_games", "question": "I'm putting together a retrospective of promotional cards. Can you get me the card name of every promotional card that has multiple faces printed on it (like split, transform, or adventure cards) and was originally released in 2019? By \"originally released\" I mean the card's own first-release date, not the release date of the set its promotional printing belongs to, and \"in 2019\" means January 1 through December 31, 2019. If a card has more than one promotional printing from that year, list it just once. I only want the card names, nothing else.", "evidence": "", "SQL": "SELECT DISTINCT name FROM cards WHERE isPromo = 1 AND NOT side IS NULL AND SUBSTRING(originalReleaseDate, 1, 4) = '2019'", "difficulty": "challenging"}
{"question_id": 99, "db_id": "card_games", "question": "I'm researching printings of the Magic: The Gathering card Tarmogoyf. I want to identify every reprint of Tarmogoyf that was published in a card frame style that was already at least 10 full years old when the set came out. Please give me the set name and release date of every set that qualifies, not just one. Two rules: the frame version is the year that frame style dates from (the frame style itself, not any frame artwork effects), and 'at least 10 full years' is inclusive, measured between the frame version's year and the set's release year.", "evidence": "Frame version: the year the card frame style of a printing dates from.", "SQL": "SELECT s.name AS set_name, s.releaseDate AS release_date FROM cards AS c INNER JOIN sets AS s ON s.code = c.setCode WHERE c.name = 'Tarmogoyf' AND c.frameVersion REGEXP '^[0-9]+$' AND CAST(c.frameVersion AS SIGNED) = c.frameVersion AND CAST(DATE_FORMAT(s.releaseDate, '%Y') AS SIGNED) - CAST(c.frameVersion AS SIGNED) >= 10", "difficulty": "challenging"}
{"question_id": 100, "db_id": "card_games", "question": "I'm cataloguing European releases of Counterspell. How many of its printings were released with both a French and an Italian localization? I just need the count as a single number.", "evidence": "A printing is one release of the card identified by its set and its card number in that set; 'Counterspell' is the English card name as catalogued.", "SQL": "SELECT COUNT(DISTINCT c.id) FROM cards AS c WHERE c.name = 'Counterspell' AND EXISTS (SELECT 1 FROM foreign_data AS f WHERE f.uuid = c.uuid AND f.language = 'French') AND EXISTS (SELECT 1 FROM foreign_data AS f WHERE f.uuid = c.uuid AND f.language = 'Italian')", "difficulty": "challenging"}
{"question_id": 101, "db_id": "card_games", "question": "I'm putting together a localization report. Find the sets that belong to the same expansion type as \"From the Vault: Lore\" – include that set itself if it qualifies. Among those, which sets never received a name in any foreign language? For each one, give me the set's name and its release date. List each qualifying set once, from the earliest release date to the latest. Don't include anything else.", "evidence": "Expansion type means the category a set belongs to, such as core, expansion or masters.", "SQL": "SELECT s.name, s.releaseDate FROM sets AS s WHERE s.type = (SELECT type FROM sets WHERE name = 'From the Vault: Lore') AND NOT EXISTS(SELECT 1 FROM set_translations AS t WHERE t.setCode = s.code AND NOT t.translation IS NULL) ORDER BY s.releaseDate", "difficulty": "challenging"}
{"question_id": 102, "db_id": "card_games", "question": "Which set contains the Aven Mindcensor printing that uses the newest card frame? I want the set's name and its release date. Count every printing, including promotional and online-only ones. If several printings share the newest frame, use the most recently released one; if the release dates tie too, list each such set once. Please give me the set name, not its code.", "evidence": "Frame version: the frame style used for a printing; frame styles are identified by the year that style was introduced.", "SQL": "SELECT DISTINCT s.name AS setName, s.releaseDate FROM cards AS c JOIN sets AS s ON s.code = c.setCode WHERE c.name = 'Aven Mindcensor' AND CAST(c.frameVersion AS SIGNED) = (SELECT MAX(CAST(frameVersion AS SIGNED)) FROM cards WHERE name = 'Aven Mindcensor') AND s.releaseDate = (SELECT MAX(s2.releaseDate) FROM cards AS c2 JOIN sets AS s2 ON s2.code = c2.setCode WHERE c2.name = 'Aven Mindcensor' AND CAST(c2.frameVersion AS SIGNED) = (SELECT MAX(CAST(frameVersion AS SIGNED)) FROM cards WHERE name = 'Aven Mindcensor'))", "difficulty": "challenging"}
{"question_id": 103, "db_id": "card_games", "question": "I'm auditing which recent products were never localized for Spanish-speaking markets. Can you find every set released in calendar year 2020 that has no Spanish name? For each of those, I just need the set code and the set's release date.", "evidence": "By \"Spanish name\" I mean the Spanish-language version of a set's name.", "SQL": "SELECT s.code, s.releaseDate FROM sets AS s WHERE s.releaseDate BETWEEN '2020-01-01' AND '2020-12-31' AND NOT EXISTS(SELECT 1 FROM set_translations AS t WHERE t.setCode = s.code AND t.language = 'Spanish' AND NOT t.translation IS NULL) ORDER BY s.releaseDate, s.code", "difficulty": "challenging"}
{"question_id": 104, "db_id": "card_games", "question": "I'm cataloguing special-release printings illustrated by Rob Alexander. What is the total converted mana cost across all cards illustrated by Rob Alexander whose original release falls in 2013? Please give me just that total as a single number. By 'released in 2013' I mean the calendar year from 1 January through 31 December 2013, and a card's original release is the original release date recorded on the card itself—cards with no original release date recorded are out of scope. Each card printing counts separately in the total.", "evidence": "Converted mana cost: the total numeric mana value of a card, e.g. a card costing {4}{W}{W} has a converted mana cost of 6.", "SQL": "SELECT SUM(convertedManaCost) AS total_converted_mana_cost FROM cards WHERE artist = 'Rob Alexander' AND SUBSTRING(originalReleaseDate, 1, 4) = '2013'", "difficulty": "challenging"}
{"question_id": 105, "db_id": "card_games", "question": "We're planning translation work for upcoming set releases and want to know how extensively a recent release year was localized. What was the average number of languages in which sets released in 2016 had their names translated? By 'released in 2016' I mean the release date falls within calendar year 2016. Every set released in 2016 counts toward the average, including any whose names were translated into no language at all (those count as zero). A language counts for a set when the set's name is rendered in that language. Please give me just that one number, rounded to two decimals.", "evidence": "Set name translation: the set's name rendered in another language.", "SQL": "SELECT ROUND(AVG(n), 2) AS avg_languages FROM (SELECT s.id, COUNT(DISTINCT CASE WHEN NOT st.translation IS NULL AND TRIM(st.translation) <> '' THEN st.language END) AS n FROM sets AS s LEFT JOIN set_translations AS st ON s.code = st.setCode WHERE SUBSTRING(s.releaseDate, 1, 4) = '2016' GROUP BY s.id) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 106, "db_id": "card_games", "question": "For the blocks named exactly \"Masques\" and \"Mirage\", how widely were their sets localized? For each of these two blocks, give me one row with the block's name, how many of its sets have an official translated name, and the total number of cards in the base sets of those sets combined. Base set size means the number of cards in the set's base set, not counting supplementary cards. Nothing else, please.", "evidence": "", "SQL": "SELECT s.block AS block, COUNT(DISTINCT s.code) AS translated_sets, SUM(s.baseSetSize) AS total_base_set_size FROM sets AS s JOIN (SELECT DISTINCT setCode FROM set_translations) AS st ON s.code = st.setCode WHERE s.block IN ('Masques', 'Mirage') GROUP BY s.block ORDER BY s.block", "difficulty": "challenging"}
{"question_id": 107, "db_id": "card_games", "question": "I'm assembling a Japanese-language boros deck and want to check which cards need careful rules review. For every card that has a boros watermark and a Japanese printing, please give me: the Japanese card name, the English card type, and the total number of official rulings recorded for that card. A card is identified by its Japanese name together with its English card type - printings that share both count as one card, and if either differs they should be listed as separate cards. The ruling total should add up all ruling entries across every printing of that card, and if a card has no rulings, list it with a total of 0.", "evidence": "Boros watermark means the watermark is marked 'boros' on the card; a Japanese printing is the foreign data entry in Japanese; rulings are the official rules clarifications recorded for a card.", "SQL": "SELECT f.name AS japanese_card_name, c.type AS card_type, SUM((SELECT COUNT(*) FROM rulings AS r WHERE r.uuid = c.uuid)) AS ruling_count FROM cards AS c JOIN foreign_data AS f ON c.uuid = f.uuid WHERE c.watermark = 'boros' AND f.language = 'Japanese' GROUP BY f.name, c.type ORDER BY f.name COLLATE utf8mb4_bin, c.type COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 108, "db_id": "card_games", "question": "I'm putting together a localization coverage report. Among the languages into which the card sets themselves were translated (i.e., have a set translation), which language has the fewest printings whose flavor text was translated into that language? Please give me the language name and the number of such printings. If several languages tie for the fewest, list all of them, ordered alphabetically by language name.", "evidence": "Set translation: a card set's official release in another language.", "SQL": "WITH set_langs AS (SELECT DISTINCT language FROM set_translations), counts AS (SELECT fd.language, COUNT(*) AS printings FROM foreign_data AS fd WHERE fd.language IN (SELECT language FROM set_langs) AND NOT fd.flavorText IS NULL AND fd.flavorText <> '' GROUP BY fd.language) SELECT language, printings FROM counts WHERE printings = (SELECT MIN(printings) FROM counts) ORDER BY language ASC", "difficulty": "challenging"}
{"question_id": 109, "db_id": "card_games", "question": "I'm building a French-language cube and want some big finishers for it. How many different creature cards with power 10 or greater have at least one printing in a set whose name has a French translation? Please return just that single number. Note: a set qualifies based on its name having a French translation, no matter when it was released or what type of set it is, and a card counts if any of its printings comes from such a set.", "evidence": "French translation: the set's name as given in French.", "SQL": "SELECT COUNT(DISTINCT name) AS total_creature_cards FROM cards WHERE CAST(power AS FLOAT) >= 10 AND types LIKE '%Creature%' AND setCode IN (SELECT setCode FROM set_translations WHERE language = 'French' AND NOT translation IS NULL)", "difficulty": "challenging"}
{"question_id": 110, "db_id": "card_games", "question": "I'm researching the Commander banned list. Can you tell me the average mana value of the creature cards that are banned in at least one play format, considering only cards ranked in EDHRec's top 1000 most popular (ranks 1 through 1000, where rank 1 is the most popular)? Give me the average as a single number rounded to one decimal place. Keep in mind that a card printed in several sets is still just one card with one EDHRec rank and one mana value.", "evidence": "EDHRec rank: a card's popularity rank on EDHRec, from 1 (most popular) to 1000.", "SQL": "SELECT ROUND(AVG(t.cmc), 1) AS average_mana_value FROM (SELECT c.name, c.convertedManaCost AS cmc FROM cards AS c INNER JOIN legalities AS l ON l.uuid = c.uuid WHERE LOCATE('Creature', c.types) > 0 AND c.edhrecRank BETWEEN 1 AND 1000 AND l.status = 'Banned' GROUP BY c.name, c.convertedManaCost) AS t", "difficulty": "challenging"}
{"question_id": 111, "db_id": "card_games", "question": "For a stats segment on creature power creep, I want to size the middle-to-big power band: how many card printings have a power greater than 3 and at most 10? Note that 3 itself is out (strictly greater than 3), but 10 itself counts (at most 10). Just the total number of printings, please.", "evidence": "A printing is one printed appearance of a card in a set – the same card name appearing in different sets counts as several printings.", "SQL": "SELECT COUNT(*) FROM cards WHERE CAST(power AS FLOAT) > 3 AND CAST(power AS FLOAT) <= 10", "difficulty": "challenging"}
{"question_id": 112, "db_id": "card_games", "question": "I want a single number: how many card printings originally released in 2014 belong to a set that carries a Magic: The Gathering Online code. A set counts as MTGO-available only if its MTGO code is present for that set. By 2014 I mean the calendar year 2014 of the printing's original release date. Count each printing separately, even if the same card name appears in more than one set.", "evidence": "Magic: The Gathering Online (MTGO) is the official digital edition of the game; a set's MTGO code identifies that set within MTGO.", "SQL": "SELECT COUNT(*) AS printings FROM cards AS c JOIN sets AS s ON s.code = c.setCode WHERE SUBSTRING(c.originalReleaseDate, 1, 4) = '2014' AND NOT s.mtgoCode IS NULL", "difficulty": "challenging"}
{"question_id": 113, "db_id": "card_games", "question": "I'm looking at Magic: The Gathering's localization coverage. Which foreign printing language has the fewest card printings overall, and how many printings does it have? Please count only languages in which Magic sets were officially printed—exclude one-off promotional gimmick languages. If several languages tie for the fewest, list each of them with the count.", "evidence": "A printing language is a language in which Magic: The Gathering sets were officially released.", "SQL": "WITH counts AS (SELECT f.language, COUNT(*) AS printings FROM foreign_data AS f WHERE f.language IN (SELECT DISTINCT language FROM set_translations) GROUP BY f.language) SELECT language, printings FROM counts WHERE printings = (SELECT MIN(printings) FROM counts)", "difficulty": "challenging"}
{"question_id": 114, "db_id": "card_games", "question": "I'm auditing how thoroughly the Coldsnap expansion was localized into Italian. How many printings in the Coldsnap set have Italian rules text? I just need that single count.", "evidence": "By 'printing' I mean an individual card entry of a set, and by 'Italian rules text' I mean the Italian-language rules wording recorded for that printing. Coldsnap means the set named Coldsnap.", "SQL": "SELECT COUNT(DISTINCT c.uuid) AS printings_with_italian_rules_text FROM foreign_data AS f JOIN cards AS c ON c.uuid = f.uuid JOIN sets AS s ON s.code = c.setCode WHERE s.name = 'Coldsnap' AND f.language = 'Italian' AND TRIM(f.text) <> ''", "difficulty": "challenging"}
{"question_id": 115, "db_id": "card_games", "question": "Among the Commander-type expansion sets released in calendar year 2020 (1 January 2020 to 31 December 2020), I need the one with the highest total card count, so we can plan translation work. Please send me the set's id from the sets listing, its name, and the number of official languages it was released in. The total card count should include promotional and related supplemental products, but exclude Alchemy modifications. If two sets tie for the highest total card count, list each of them, ordered by set id ascending.", "evidence": "Commander: a multiplayer expansion type of the game. Alchemy modifications: online-only variant versions of cards.", "SQL": "WITH cohort AS (SELECT * FROM sets WHERE type = 'commander' AND releaseDate >= '2020-01-01' AND releaseDate <= '2020-12-31') SELECT c.id, c.name, COUNT(DISTINCT st.language) AS languages FROM cohort AS c LEFT JOIN set_translations AS st ON st.setCode = c.code WHERE c.totalSetSize = (SELECT MAX(totalSetSize) FROM cohort) GROUP BY c.id, c.name ORDER BY c.id ASC", "difficulty": "challenging"}
{"question_id": 116, "db_id": "card_games", "question": "I'm researching Magic: The Gathering's basic land card Swamp. How many foreign languages has it been printed in over its entire history? Count all printings across every set and year.", "evidence": "Swamp is the name of a Magic: The Gathering card.", "SQL": "SELECT COUNT(DISTINCT fd.language) AS language_count FROM foreign_data AS fd JOIN cards AS c ON fd.uuid = c.uuid WHERE c.name = 'Swamp'", "difficulty": "challenging"}
{"question_id": 117, "db_id": "card_games", "question": "I'm putting together a black artifact flavor-showcase section for a trade binder. How many mono-black Artifact cards have a foreign-language printing that shows flavor text in that language? By mono-black I mean black is the card's only colour, and by Artifact cards I include artifacts combined with another card type, like an Artifact Creature. I'm counting cards, not printings – a card is the same card regardless of set, print run, or language. Just give me one number.", "evidence": "In Magic colour notation, B denotes black, and a card is mono-black when black is its only colour.", "SQL": "SELECT COUNT(DISTINCT c.name) AS card_count FROM cards AS c WHERE c.colors = 'B' AND c.type LIKE '%Artifact%' AND EXISTS(SELECT 1 FROM foreign_data AS f WHERE f.uuid = c.uuid AND CHAR_LENGTH(f.flavorText) > 0)", "difficulty": "challenging"}
{"question_id": 118, "db_id": "codebase_community", "question": "What is the display name of the user who last edited the post \"Examples for teaching: Correlation does not mean causation\"?", "evidence": "", "SQL": "SELECT T2.DisplayName FROM posts AS T1 INNER JOIN users AS T2 ON T1.LastEditorUserId = T2.Id WHERE T1.Title = 'Examples for teaching: Correlation does not mean causation'", "difficulty": "moderate"}
{"question_id": 119, "db_id": "codebase_community", "question": "Which users made exactly one history entry on at least one post with at least 1,000 views? Return their distinct user IDs.", "evidence": "", "SQL": "WITH once_per_post AS (SELECT h.PostId, h.UserId FROM postHistory AS h JOIN posts AS p ON p.Id = h.PostId WHERE p.ViewCount >= 1000 AND NOT h.UserId IS NULL GROUP BY h.PostId, h.UserId HAVING COUNT(*) = 1) SELECT DISTINCT UserId FROM once_per_post ORDER BY UserId", "difficulty": "moderate"}
{"question_id": 120, "db_id": "codebase_community", "question": "What is the difference in percentage points between the 2010 and 2011 shares of all Student badges, taking the 2010 share minus the 2011 share?", "evidence": "", "SQL": "SELECT CAST(SUM(IF(DATE_FORMAT(Date, '%Y') = '2010', 1, 0)) AS FLOAT) * 100 / COUNT(Id) - CAST(SUM(IF(DATE_FORMAT(Date, '%Y') = '2011', 1, 0)) AS FLOAT) * 100 / COUNT(Id) FROM badges WHERE Name = 'Student'", "difficulty": "challenging"}
{"question_id": 121, "db_id": "codebase_community", "question": "What percentage of posts authored by Community use the R-language tag? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN p.Tags LIKE '%<r>%' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM posts AS p JOIN users AS u ON u.Id = p.OwnerUserId WHERE u.DisplayName = 'Community'", "difficulty": "challenging"}
{"question_id": 122, "db_id": "codebase_community", "question": "Which post created in 2010 had the most favorites? Return its post ID and its owner's display name.", "evidence": "", "SQL": "SELECT p.Id, u.DisplayName FROM posts AS p JOIN users AS u ON p.OwnerUserId = u.Id WHERE SUBSTRING(p.CreaionDate, 1, 4) = '2010' AND NOT p.FavoriteCount IS NULL ORDER BY p.FavoriteCount DESC, p.Id ASC LIMIT 1", "difficulty": "moderate"}
{"question_id": 123, "db_id": "codebase_community", "question": "Give the view count of the post titled 'Computer game datasets' and the display name of its last editor.", "evidence": "", "SQL": "SELECT DISTINCT p.ViewCount, u.DisplayName FROM posts AS p JOIN users AS u ON u.Id = p.LastEditorUserId WHERE LOWER(p.Title) = LOWER('Computer game datasets')", "difficulty": "moderate"}
{"question_id": 124, "db_id": "codebase_community", "question": "Give the text and author's display name for the latest ten comments on the post titled 'Analysing wind data with R', newest comment first.", "evidence": "", "SQL": "SELECT c.Text, u.DisplayName FROM comments AS c JOIN posts AS p ON c.PostId = p.Id LEFT JOIN users AS u ON c.UserId = u.Id WHERE p.Title = 'Analysing wind data with R' ORDER BY c.CreationDate DESC, c.Id DESC LIMIT 10", "difficulty": "moderate"}
{"question_id": 125, "db_id": "codebase_community", "question": "Among all posts by the user with the highest reputation, what percentage have a score above 50? Round to two decimal places.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN Score > 50 THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM posts WHERE OwnerUserId IN (SELECT Id FROM users WHERE Reputation = (SELECT MAX(Reputation) FROM users))", "difficulty": "challenging"}
{"question_id": 126, "db_id": "codebase_community", "question": "Among comments attached to existing posts with exactly one comment record in the data, how many have a score of zero?", "evidence": "", "SQL": "SELECT COUNT(*) FROM comments AS c JOIN posts AS p ON p.Id = c.PostId WHERE c.Score = 0 AND c.PostId IN (SELECT x.PostId FROM comments AS x GROUP BY x.PostId HAVING COUNT(*) = 1)", "difficulty": "simple"}
{"question_id": 127, "db_id": "codebase_community", "question": "I'd like to gauge the standing of our United Kingdom contributor community on the site. Can you give me the combined reputation of the users based in the United Kingdom who have posted on the site, as a single total? Please write the country by its full name, \"United Kingdom\", and don't substitute abbreviations. I just need the one number, not a per-user list.", "evidence": "Reputation is the score the site assigns each user. A user who has posted owns at least one item in the site's post collection.", "SQL": "SELECT SUM(u.Reputation) AS combined_reputation FROM users AS u WHERE u.Location LIKE '%United Kingdom%' AND u.Id IN (SELECT p.OwnerUserId FROM posts AS p WHERE NOT p.OwnerUserId IS NULL)", "difficulty": "challenging"}
{"question_id": 128, "db_id": "codebase_community", "question": "I want to profile the users who drop links in comment threads. What is the average age of the users who posted a comment containing a website link? Please round it to two decimal places. That single value is all I need back.", "evidence": "A comment counts as containing a website if its content contains 'http://'.", "SQL": "SELECT ROUND(AVG(T.Age), 2) AS average_age FROM (SELECT DISTINCT T2.Id, T2.Age FROM comments AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T1.Text LIKE '%http://%') AS T", "difficulty": "challenging"}
{"question_id": 129, "db_id": "codebase_community", "question": "I'm profiling how seasoned our Organizer badge holders in Germany are. Among the users who earned the Organizer badge and are based in Germany, how many had already earned 5 badges before they got the Organizer badge? Just the count, please. Note: \"before\" means strictly earlier - badges earned at the same moment as the Organizer badge don't count toward the 5, and the Organizer badge itself doesn't count as one of the 5.", "evidence": "Organizer badge: the badge whose name is Organizer.", "SQL": "WITH organizer AS (SELECT UserId, MIN(Date) AS organizer_date FROM badges WHERE Name = 'Organizer' GROUP BY UserId) SELECT COUNT(*) AS user_count FROM organizer AS o JOIN users AS u ON u.Id = o.UserId WHERE u.Location LIKE '%Germany%' AND (SELECT COUNT(*) FROM badges AS b WHERE b.UserId = o.UserId AND b.Date < o.organizer_date) >= 5", "difficulty": "challenging"}
{"question_id": 130, "db_id": "codebase_community", "question": "I'm putting together a report for the site owners on where people who started posting during 2010 were located, with a focus on India. Could you tell me how many of the users whose first post was created in 2010 are located in India? By 2010 I mean the calendar year 2010, and by India I mean the country itself, not any place whose name merely contains the word.", "evidence": "A user's first post is the earliest-created post among the posts that user owns.", "SQL": "WITH RECURSIVE fp AS (SELECT OwnerUserId AS uid, MIN(CreaionDate) AS fdate FROM posts WHERE NOT OwnerUserId IS NULL GROUP BY OwnerUserId), locs AS (SELECT u.Id AS uid, u.Location AS loc FROM users AS u JOIN fp ON fp.uid = u.Id WHERE fp.fdate >= '2010-01-01' AND fp.fdate < '2011-01-01'), parts(uid, head, tail) AS (SELECT uid, CASE WHEN LOCATE(',', loc) > 0 THEN SUBSTRING(loc, 1, LOCATE(',', loc) - 1) ELSE loc END, CASE WHEN LOCATE(',', loc) > 0 THEN SUBSTRING(loc, LOCATE(',', loc) + 1) ELSE NULL END FROM locs UNION ALL SELECT uid, CASE WHEN LOCATE(',', tail) > 0 THEN SUBSTRING(tail, 1, LOCATE(',', tail) - 1) ELSE tail END, CASE WHEN LOCATE(',', tail) > 0 THEN SUBSTRING(tail, LOCATE(',', tail) + 1) ELSE NULL END FROM parts WHERE NOT tail IS NULL) SELECT COUNT(*) AS users_in_india FROM parts WHERE TRIM(head) = 'India'", "difficulty": "challenging"}
{"question_id": 131, "db_id": "codebase_community", "question": "I'm profiling the authors behind poorly received R posts to see if they tend to be low-reputation members. Can you give me the average reputation of the users who own posts tagged with the R tag that have a score below 20? Just the single number, rounded to the nearest whole number.", "evidence": "'r' is the tag used on this site for the R programming language for statistical computing.", "SQL": "SELECT ROUND(AVG(u.Reputation)) AS avg_reputation FROM users AS u WHERE u.Id IN (SELECT p.OwnerUserId FROM posts AS p WHERE p.Score < 20 AND p.Tags LIKE CONCAT('%', '<', 'r', '>', '%'))", "difficulty": "challenging"}
{"question_id": 132, "db_id": "codebase_community", "question": "I'm putting together the yearly activity report with a Germany-focused breakdown of who did the editing, covering posts created in calendar year 2012. For the 2012 posts whose last editor is a user based in Germany, I need the total score; and for all other posts created in 2012, I need their total score as well. Also, how many Germany-based users were the last editor of at least one 2012 post, and what their combined reputation is, as shown on their profiles. A user based in Germany is one whose profile location is in Germany.", "evidence": "A post's last editor is the user who made its most recent edit.", "SQL": "WITH posts_2012 AS (SELECT Id, Score, LastEditorUserId AS EditorId FROM posts WHERE CreaionDate >= '2012-01-01' AND CreaionDate < '2013-01-01'), german_editors AS (SELECT DISTINCT u.Id, u.Reputation FROM posts_2012 AS p JOIN users AS u ON u.Id = p.EditorId WHERE u.Location LIKE '%Germany%') SELECT (SELECT SUM(p.Score) FROM posts_2012 AS p JOIN german_editors AS g ON g.Id = p.EditorId) AS german_edited_score, (SELECT SUM(Score) FROM posts_2012 WHERE EditorId IS NULL OR NOT EditorId IN (SELECT Id FROM german_editors)) AS remaining_score, (SELECT COUNT(*) FROM german_editors) AS editor_count, (SELECT SUM(Reputation) FROM german_editors) AS editor_reputation", "difficulty": "challenging"}
{"question_id": 133, "db_id": "codebase_community", "question": "I'm reviewing R-language activity on the site. I'd like to gauge the standing of the community members behind the highly-rated R posts: what is the combined reputation of the users who own a post with a score of exactly 10 that carries the R programming language tag? Please return just that single number. Note that by R I mean the R programming language tag specifically, not any other tag or value that just happens to contain the letter r.", "evidence": "", "SQL": "SELECT SUM(u.Reputation) AS combined_reputation FROM users AS u WHERE u.Id IN (SELECT p.OwnerUserId FROM posts AS p WHERE p.Score = 10 AND p.Tags LIKE CONCAT('%', '<', 'R', '>', '%'))", "difficulty": "challenging"}
{"question_id": 134, "db_id": "codebase_community", "question": "I'd like to gauge the standing of the community members behind the R posts on one day. Could you tell me the combined reputation of the users who own the posts tagged R that were last active on 2014-08-27? I just need that one number, covering the whole calendar day 2014-08-27.", "evidence": "R: the R language for statistical computing.", "SQL": "SELECT SUM(Reputation) AS combined_reputation FROM users WHERE Id IN (SELECT OwnerUserId FROM posts WHERE Tags LIKE CONCAT('%', '<', 'R', '>', '%') AND LasActivityDate LIKE '2014-08-27%')", "difficulty": "challenging"}
{"question_id": 135, "db_id": "codebase_community", "question": "What is the total score of the questions tagged 'r' that link to the question titled \"A Probability distribution value exceeding 1 is OK?\"? I only need the total score of those linking questions.", "evidence": "'r' here means the R programming language for statistical computing, not the letter on its own.", "SQL": "WITH target AS (SELECT Id FROM posts WHERE Title = 'A Probability distribution value exceeding 1 is OK?'), linkers AS (SELECT DISTINCT pl.PostId AS pid FROM postLinks AS pl INNER JOIN target AS tg ON pl.RelatedPostId = tg.Id) SELECT SUM(p.Score) AS total_score FROM linkers AS l INNER JOIN posts AS p ON p.Id = l.pid WHERE EXISTS(SELECT 1 FROM tags AS t WHERE t.TagName = 'r' AND p.Tags LIKE CONCAT('%', '<', t.TagName, '>', '%'))", "difficulty": "challenging"}
{"question_id": 136, "db_id": "codebase_community", "question": "I'm profiling users by where they say they live. Among the users located in Germany, who has the second most badges of all time? By second most I mean the highest badge total strictly below the top holder's total. If several users tie at that total, include all of them. Please give me each such user's display name and their badge total, ordered by display name.", "evidence": "Badges: the badges a user has obtained, one badge award per record.", "SQL": "WITH per_user AS (SELECT u.Id, u.DisplayName, COUNT(b.Id) AS badge_count FROM users AS u LEFT JOIN badges AS b ON b.UserId = u.Id WHERE u.Location LIKE '%Germany%' GROUP BY u.Id, u.DisplayName) SELECT DisplayName, badge_count FROM per_user WHERE badge_count = (SELECT MAX(badge_count) FROM per_user AS p2 WHERE p2.badge_count < (SELECT MAX(badge_count) FROM per_user)) ORDER BY DisplayName", "difficulty": "challenging"}
{"question_id": 137, "db_id": "codebase_community", "question": "I'm planning regional outreach and want to know which California-based account draws the most profile attention. Among users whose stated location shows they are based in California, give me the user id, display name, profile view count, and reputation of the user or users with the most profile views. If several such users tie for the most profile views, list every one of them with those same four values.", "evidence": "CA is the two-letter state code for California.", "SQL": "WITH ca AS (SELECT Id, DisplayName, Views, Reputation FROM users WHERE LOCATE(CONCAT(',', 'CA', ','), CONCAT(',', REPLACE(UPPER(TRIM(Location)), ' ', ''), ',')) > 0 OR LOCATE(CONCAT(',', UPPER('California'), ','), CONCAT(',', REPLACE(UPPER(TRIM(Location)), ' ', ''), ',')) > 0) SELECT Id, DisplayName, Views, Reputation FROM ca WHERE Views = (SELECT MAX(Views) FROM ca)", "difficulty": "challenging"}
{"question_id": 138, "db_id": "codebase_community", "question": "We're profiling our most respected members by where they live, focusing on York, England (the English city itself; a location listed as just \"York\" counts). Who is the most influential user based there – the one with the highest reputation – and what is their age? If several users tie for the highest reputation, give me the age of each of them. Please return only the age, exactly as it stands for each user, even when an age isn't reported.", "evidence": "", "SQL": "SELECT Age FROM users WHERE LOCATE(CONCAT(',', 'York', ','), CONCAT(',', Location, ',')) > 0 AND Reputation = (SELECT MAX(Reputation) FROM users WHERE LOCATE(CONCAT(',', 'York', ','), CONCAT(',', Location, ',')) > 0)", "difficulty": "challenging"}
{"question_id": 139, "db_id": "codebase_community", "question": "I'm preparing a report on international participation. How many users located in India had earned a Yearling badge before 2014? 'Before 2014' should mean before 1 January 2014. I just need the single count, nothing else.", "evidence": "'Yearling' is a badge a member earns for a year of activity on the site.", "SQL": "SELECT COUNT(DISTINCT T1.UserId) AS user_count FROM badges AS T1 INNER JOIN users AS T2 ON T1.UserId = T2.Id WHERE T2.Location LIKE '%India%' AND T1.Name = 'Yearling' AND T1.Date < '2014-01-01'", "difficulty": "challenging"}
{"question_id": 140, "db_id": "codebase_community", "question": "I'm putting together a summary of how active badge-holders present themselves on the site. How many different display names appear among the adult users who obtained the Supporter badge? By adult I mean age 19 to 65 inclusive, and please cover all time. I just need that one number.", "evidence": "NaN stands for a user who never set a display name.", "SQL": "SELECT COUNT(DISTINCT BINARY (CASE WHEN u.DisplayName IS NULL OR u.DisplayName = 'NaN' THEN NULL ELSE u.DisplayName END)) AS different_display_names FROM users AS u INNER JOIN badges AS b ON u.Id = b.UserId WHERE b.Name = 'Supporter' AND u.Age BETWEEN 19 AND 65", "difficulty": "challenging"}
{"question_id": 141, "db_id": "codebase_community", "question": "Among all posts whose title contains the phrase 'principal component scores', which one has the most related posts linked to it? For each such post, give me the post title and the number of related posts. If several posts tie for the most, list every one of them with their counts. The count should cover related posts across the site's entire history.", "evidence": "A related post is another post that the community's link records connect to a given post.", "SQL": "WITH counts AS (SELECT p.Id AS post_id, p.Title AS title, COUNT(DISTINCT pl.RelatedPostId) AS related_posts FROM posts AS p JOIN postLinks AS pl ON pl.PostId = p.Id WHERE p.Title LIKE '%principal component scores%' GROUP BY p.Id, p.Title) SELECT title, related_posts FROM counts WHERE related_posts = (SELECT MAX(related_posts) FROM counts) ORDER BY title", "difficulty": "challenging"}
{"question_id": 142, "db_id": "codebase_community", "question": "I'm auditing accounts on the stats forum. What is the id of the youngest user account whose display name is Michael? If two or more such accounts tie as the youngest, give me the smallest id.", "evidence": "", "SQL": "SELECT Id FROM users WHERE DisplayName = 'Michael' AND Age = (SELECT MIN(Age) FROM users WHERE DisplayName = 'Michael') ORDER BY Id LIMIT 1", "difficulty": "challenging"}
{"question_id": 143, "db_id": "codebase_community", "question": "I'm trying to gauge how many users the bounty feature drew back when it first ran. How many users offered a bounty of 30 or more on some post between 1 January 2010 (inclusive) and 1 January 2011 (exclusive), going by the date the bounty was recorded? By the user who offered a bounty, I mean the post's owner - the owner account where one is recorded, otherwise the owner name on the post. I just need that one count.", "evidence": "A bounty is a reputation reward a user attaches to a post, recorded as an amount.", "SQL": "SELECT COUNT(DISTINCT COALESCE(CAST(p.OwnerUserId AS CHAR), p.OwnerDisplayName)) AS users FROM votes AS v JOIN posts AS p ON v.PostId = p.Id WHERE v.BountyAmount >= 30 AND v.CreationDate >= '2010-01-01' AND v.CreationDate < '2011-01-01'", "difficulty": "challenging"}
{"question_id": 144, "db_id": "codebase_community", "question": "What was the average reputation of users located in India who created a post in 2010? Please give me a single number rounded to two decimal places. Note: 'in 2010' means the calendar year 2010 based on the post's creation date, and any type of post counts. A user counts as located in India only if their location is actually India - a place that merely contains the word India (like the US state Indiana) doesn't count.", "evidence": "", "SQL": "SELECT ROUND(AVG(u.Reputation), 2) AS avg_reputation FROM users AS u WHERE (TRIM(u.Location) = 'India' OR (LOCATE(',', u.Location) > 0 AND TRIM(SUBSTRING(u.Location, LOCATE(',', u.Location) + 1)) = 'India')) AND u.Id IN (SELECT p.OwnerUserId FROM posts AS p WHERE p.CreaionDate >= '2010-01-01' AND p.CreaionDate < '2011-01-01')", "difficulty": "challenging"}
{"question_id": 145, "db_id": "codebase_community", "question": "I'm profiling our most active contributors of 2012. Among the users who created more than ten posts in 2012 (judged by each post's creation date), what is their average number of up-votes cast and their average age? Please give me a single row with both averages, each rounded to two decimal places.", "evidence": "Up-vote: a vote a user cast in favor of a post.", "SQL": "WITH active AS (SELECT OwnerUserId FROM posts WHERE CreaionDate >= '2012-01-01' AND CreaionDate < '2013-01-01' GROUP BY OwnerUserId HAVING COUNT(*) > 10) SELECT ROUND(AVG(u.UpVotes), 2) AS avg_upvotes, ROUND(AVG(u.Age), 2) AS avg_age FROM active AS a JOIN users AS u ON u.Id = a.OwnerUserId", "difficulty": "challenging"}
{"question_id": 146, "db_id": "codebase_community", "question": "For each month of 2010, how many posts that have no more than two answers received a link during that month? A month with none counts as zero. Give me the average across all twelve months of 2010, rounded to two decimals.", "evidence": "A link is a recorded connection that associates one post with another post of the site.", "SQL": "SELECT ROUND(CAST(SUM(month_cnt) AS FLOAT) / 12, 2) AS average FROM (SELECT DATE_FORMAT(T1.CreationDate, '%m') AS mon, COUNT(DISTINCT T1.PostId) AS month_cnt FROM postLinks AS T1 INNER JOIN posts AS T2 ON T1.PostId = T2.Id WHERE T2.AnswerCount <= 2 AND DATE_FORMAT(T1.CreationDate, '%Y') = '2010' GROUP BY mon) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 147, "db_id": "codebase_community", "question": "I'm reviewing our 2010 content. What percentage of posts created in 2010 that have a score above 5 were NOT made by high-reputation users? By high-reputation I mean a user with a reputation of at least 1000. Please give me just the single percentage value, rounded to two decimal places. Use the post's creation date to determine that it's from calendar year 2010.", "evidence": "high-reputation: reputation of at least 1000", "SQL": "SELECT ROUND(CAST(SUM(IF(T2.Reputation >= 1000, 0, 1)) AS FLOAT) * 100 / COUNT(T1.Id), 2) AS percentage FROM posts AS T1 LEFT JOIN users AS T2 ON T1.OwnerUserId = T2.Id WHERE T1.Score > 5 AND DATE_FORMAT(T1.CreaionDate, '%Y') = '2010'", "difficulty": "challenging"}
{"question_id": 148, "db_id": "codebase_community", "question": "I'm reviewing the history of the question 'Why square the difference instead of taking the absolute value in standard deviation?'. For that post, who left the most edit comments, and how many did they leave? Please give me each editor's display name along with their number of edit comments on that post. If several editors are tied for the most, list each of them with their count. Also, please count every revision as its own event, even when successive revisions carry the same note.", "evidence": "An edit comment is the note an editor records together with a revision of a post, not a comment posted under the post.", "SQL": "WITH target AS (SELECT Id FROM posts WHERE Title = 'Why square the difference instead of taking the absolute value in standard deviation?'), counts AS (SELECT u.DisplayName, COUNT(*) AS n FROM postHistory AS h JOIN users AS u ON u.Id = h.UserId WHERE h.PostId IN (SELECT Id FROM target) AND NOT h.Comment IS NULL AND TRIM(h.Comment) <> '' GROUP BY u.DisplayName) SELECT DisplayName, n FROM counts WHERE n = (SELECT MAX(n) FROM counts)", "difficulty": "challenging"}
{"question_id": 149, "db_id": "debit_card_specializing", "question": "For each of the SME, LAM, and KAM segments, identify the CZK customer with the lowest total recorded consumption in 2013, breaking a tie by smaller customer ID. What are the differences between those customers' 2013 totals in SME minus LAM, LAM minus KAM, and KAM minus SME order? Round each to two decimals.", "evidence": "", "SQL": "WITH annual AS (SELECT c.Segment, c.CustomerID, SUM(y.Consumption) AS total FROM customers AS c JOIN yearmonth AS y ON y.CustomerID = c.CustomerID WHERE c.Currency = 'CZK' AND y.Date BETWEEN '201301' AND '201312' AND NOT y.Consumption IS NULL AND c.Segment IN ('SME', 'LAM', 'KAM') GROUP BY c.Segment, c.CustomerID), ranked AS (SELECT Segment, total, ROW_NUMBER() OVER (PARTITION BY Segment ORDER BY total, CustomerID) AS rn FROM annual), chosen AS (SELECT MAX(CASE WHEN Segment = 'SME' THEN total END) AS sme, MAX(CASE WHEN Segment = 'LAM' THEN total END) AS lam, MAX(CASE WHEN Segment = 'KAM' THEN total END) AS kam FROM ranked WHERE rn = 1) SELECT ROUND(sme - lam, 2), ROUND(lam - kam, 2), ROUND(kam - sme, 2) FROM chosen", "difficulty": "challenging"}
{"question_id": 150, "db_id": "debit_card_specializing", "question": "Among EUR-paying customers in the SME, LAM, and KAM segments, which segments had the highest and lowest percentage increase in total consumption from 2012 to 2013? Return each extreme segment and its increase percentage, rounded to two decimal places; include ties.", "evidence": "", "SQL": "WITH annual AS (SELECT c.Segment, SUM(CASE WHEN SUBSTRING(y.Date, 1, 4) = '2012' THEN y.Consumption ELSE 0 END) AS total_2012, SUM(CASE WHEN SUBSTRING(y.Date, 1, 4) = '2013' THEN y.Consumption ELSE 0 END) AS total_2013 FROM customers AS c JOIN yearmonth AS y ON c.CustomerID = y.CustomerID WHERE c.Currency = 'EUR' AND c.Segment IN ('SME', 'LAM', 'KAM') AND SUBSTRING(y.Date, 1, 4) IN ('2012', '2013') GROUP BY c.Segment), rates AS (SELECT Segment, ROUND(100.0 * (total_2013 - total_2012) / NULLIF(total_2012, 0), 2) AS increase_pct FROM annual WHERE total_2012 > 0), ranked AS (SELECT Segment, increase_pct, RANK() OVER (ORDER BY increase_pct DESC) AS highest_rank, RANK() OVER (ORDER BY increase_pct ASC) AS lowest_rank FROM rates) SELECT Segment, increase_pct FROM ranked WHERE highest_rank = 1 OR lowest_rank = 1 ORDER BY increase_pct DESC, Segment", "difficulty": "challenging"}
{"question_id": 151, "db_id": "debit_card_specializing", "question": "For the customer who paid 634.8 on 2012-08-25, what is the relative change in annual consumption from 2012 to 2013, calculated as (2013 total - 2012 total) / 2012 total and rounded to four decimal places?", "evidence": "", "SQL": "SELECT ROUND(CAST(1.0 * (SUM(CASE WHEN SUBSTRING(ym.Date, 1, 4) = '2013' THEN ym.Consumption ELSE 0 END) - SUM(CASE WHEN SUBSTRING(ym.Date, 1, 4) = '2012' THEN ym.Consumption ELSE 0 END)) / NULLIF(SUM(CASE WHEN SUBSTRING(ym.Date, 1, 4) = '2012' THEN ym.Consumption ELSE 0 END), 0) AS DECIMAL(20, 8)), 4) FROM yearmonth AS ym WHERE ym.CustomerID = (SELECT t.CustomerID FROM transactions_1k AS t WHERE t.Date = '2012-08-25' AND CAST(t.Price AS DECIMAL(12, 2)) = 634.80)", "difficulty": "challenging"}
{"question_id": 152, "db_id": "debit_card_specializing", "question": "How many customers who pay in EUR and had gas consumption in 2012 also had gas consumption in 2013? I just need a single number: the count of such customers. By 2012 and 2013 I mean those calendar years, and gas consumption in any month of the year counts.", "evidence": "", "SQL": "SELECT COUNT(*) AS customers FROM (SELECT CustomerID FROM yearmonth WHERE SUBSTRING(Date, 1, 4) = '2012' AND CustomerID IN (SELECT CustomerID FROM customers WHERE Currency = 'EUR') INTERSECT SELECT CustomerID FROM yearmonth WHERE SUBSTRING(Date, 1, 4) = '2013') AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 153, "db_id": "debit_card_specializing", "question": "I'm reviewing our 2012 performance and want to see which client segments hold our small-scale customers. For each client segment, can you tell me how many customers had total consumption below 30,000 over the whole of 2012? Please count only customers who used their cards at some point during 2012, and treat 30,000 as a strict limit - someone at exactly 30,000 doesn't count. I just need the client segment and the number of such customers per segment.", "evidence": "Consumption means the amount spent through a customer's fuel cards.", "SQL": "WITH yearly AS (SELECT CustomerID, SUM(Consumption) AS total_consumption FROM yearmonth WHERE Date >= '201201' AND Date <= '201212' GROUP BY CustomerID HAVING SUM(Consumption) < 30000) SELECT c.Segment AS segment, COUNT(*) AS customers FROM yearly AS y INNER JOIN customers AS c ON c.CustomerID = y.CustomerID GROUP BY c.Segment ORDER BY c.Segment", "difficulty": "challenging"}
{"question_id": 154, "db_id": "debit_card_specializing", "question": "I'm reviewing 2013 uptake and want to know the genuinely active cardholder base in each client segment. For each client segment, how many of that segment's customers consumed any fuel at all during the calendar year 2013? I just need the client segment and the number of customers who consumed fuel in 2013, nothing else.", "evidence": "A customer's consumption for a month is the amount of fuel recorded against them for that month; by 'consumed any fuel in 2013' I mean they had fuel recorded against them in at least one month of 2013.", "SQL": "SELECT c.Segment AS segment, COUNT(DISTINCT y.CustomerID) AS customers_with_fuel_2013 FROM customers AS c INNER JOIN yearmonth AS y ON c.CustomerID = y.CustomerID WHERE y.Date BETWEEN '201301' AND '201312' AND y.Consumption > 0 GROUP BY c.Segment ORDER BY c.Segment", "difficulty": "challenging"}
{"question_id": 155, "db_id": "debit_card_specializing", "question": "I want to gauge how spread out our high-value fuelling activity in the Czech Republic was over the recorded window. How many whole minutes elapsed from the first to the last fuel transaction at gas stations in the Czech Republic with a price over 1000? Please round down to whole minutes.", "evidence": "Czech Republic means the gas station is in the CZE country.", "SQL": "SELECT (UNIX_TIMESTAMP(MAX(CONCAT(Date, ' ', Time))) - UNIX_TIMESTAMP(MIN(CONCAT(Date, ' ', Time)))) / (5 * 13 - 5) AS minutes FROM transactions_1k AS T1 INNER JOIN gasstations AS T2 ON T1.GasStationID = T2.GasStationID WHERE T2.Country = 'CZE' AND T1.Price > 1000", "difficulty": "challenging"}
{"question_id": 156, "db_id": "debit_card_specializing", "question": "I'm preparing a loyalty review of our steadily active customers in 2013. For each currency, I'd like to know how many customers bought fuel in every month from January through November 2013, with both January and November included. Please give me the currency and that customer count. If several currencies tie, list them all – no ranking needed.", "evidence": "Consumption means the total fuel a customer purchased in a month on their fuel card; a customer counts for a month if they had any consumption that month.", "SQL": "WITH RECURSIVE months(m) AS (SELECT '201301' UNION ALL SELECT CAST(CAST(m AS SIGNED) + 1 AS CHAR) FROM months WHERE m < '201311'), steady AS (SELECT CustomerID FROM yearmonth WHERE Date BETWEEN '201301' AND '201311' AND Consumption > 0 GROUP BY CustomerID HAVING COUNT(DISTINCT Date) = (SELECT COUNT(*) FROM months)) SELECT c.Currency, COUNT(*) AS customers FROM steady AS s JOIN customers AS c ON c.CustomerID = s.CustomerID GROUP BY c.Currency", "difficulty": "challenging"}
{"question_id": 157, "db_id": "debit_card_specializing", "question": "I'm putting together currency-specific pricing proposals and need a sense of typical quarterly fuel consumption. Among customers who have fuel consumption recorded in the second quarter of 2013 (April, May and June 2013), what is the average amount of fuel consumed over the whole quarter by an EUR-paying customer, and the same average for a CZK-paying customer? Please round both averages to two decimal places. By EUR-paying / CZK-paying I mean a customer whose account currency is EUR / CZK.", "evidence": "EUR-paying / CZK-paying: a customer whose account currency is EUR / CZK", "SQL": "WITH q2 AS (SELECT CustomerID, SUM(Consumption) AS total FROM yearmonth WHERE Date BETWEEN '201304' AND '201306' GROUP BY CustomerID) SELECT ROUND(AVG(CASE WHEN c.Currency = 'EUR' THEN q2.total END), 2) AS eur_avg_quarter, ROUND(AVG(CASE WHEN c.Currency = 'CZK' THEN q2.total END), 2) AS czk_avg_quarter FROM customers AS c JOIN q2 ON q2.CustomerID = c.CustomerID", "difficulty": "challenging"}
{"question_id": 158, "db_id": "debit_card_specializing", "question": "I want to see how much our busiest month grew from 2012 to 2013. What was the difference between our peak monthly total consumption in 2013 and our peak monthly total consumption in 2012, in consumption units, rounded to the nearest whole number? By total consumption in a calendar month I mean the consumption of the whole customer base that month, and the peak of a year is the calendar month with the highest total consumption in that year.", "evidence": "", "SQL": "SELECT ROUND((SELECT SUM(Consumption) FROM yearmonth WHERE SUBSTRING(Date, 1, 4) = '2013' GROUP BY SUBSTRING(Date, 5, 2) ORDER BY SUM(Consumption) DESC LIMIT 1) - (SELECT SUM(Consumption) FROM yearmonth WHERE SUBSTRING(Date, 1, 4) = '2012' GROUP BY SUBSTRING(Date, 5, 2) ORDER BY SUM(Consumption) DESC LIMIT 1), 0) AS difference", "difficulty": "challenging"}
{"question_id": 159, "db_id": "debit_card_specializing", "question": "I'm reviewing customer 15621's fuel spending on the fleet card in 2013. What was their average fuel consumption per month, counting only the months in which they actually purchased fuel? Give me the single average value rounded to two decimal places.", "evidence": "", "SQL": "SELECT ROUND(SUM(Consumption) / COUNT(*), 2) AS average_monthly_consumption FROM yearmonth WHERE CustomerID = 15621 AND Date BETWEEN '201301' AND '201312' AND Consumption > 0", "difficulty": "challenging"}
{"question_id": 160, "db_id": "debit_card_specializing", "question": "I want to compare how much a typical Czech-koruna-billed client spent versus a euro-billed client during 2012, to see whether the two currency segments behave differently. Please give me the difference between the average 2012 consumption of a CZK-paying customer and the average 2012 consumption of an EUR-paying customer, with the EUR average subtracted from the CZK average. Only include customers who had consumption in 2012 in each average, and the period is calendar year 2012. Just send me that one number, rounded to the nearest whole unit.", "evidence": "Consumption means the monthly consumption amount recorded per customer.", "SQL": "WITH per_customer AS (SELECT CustomerID, SUM(Consumption) AS tot_2012 FROM yearmonth WHERE SUBSTRING(Date, 1, 4) = '2012' GROUP BY CustomerID) SELECT ROUND(AVG(CASE WHEN c.Currency = 'CZK' THEN p.tot_2012 END) - AVG(CASE WHEN c.Currency = 'EUR' THEN p.tot_2012 END), 0) AS diff FROM customers AS c JOIN per_customer AS p ON c.CustomerID = p.CustomerID", "difficulty": "challenging"}
{"question_id": 161, "db_id": "debit_card_specializing", "question": "I'm sizing a premium offer for our heaviest corporate fuel buyers ahead of renewals. How many KAM-segment customers paying in CZK had total fuel consumption above 1 million (1,000,000) in calendar year 2013? I just need that number of customers.", "evidence": "KAM is one of our client segments.", "SQL": "SELECT COUNT(*) AS customer_count FROM (SELECT T2.CustomerID FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Currency = 'CZK' AND T1.Segment = 'KAM' AND T2.Date LIKE '2013%' GROUP BY T2.CustomerID HAVING SUM(T2.Consumption) > 1000000) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 162, "db_id": "debit_card_specializing", "question": "For my February 2013 activity report: how many SME customers actually purchased gas in February 2013? Please give me just a single whole number - the count of SME customers who consumed gas during the calendar month of February 2013 (Feb 1-28, 2013).", "evidence": "By \"gas\" I mean gasoline (motor fuel) purchases, not natural gas.", "SQL": "SELECT COUNT(DISTINCT T2.CustomerID) AS sme_gas_customers FROM customers AS T1 INNER JOIN yearmonth AS T2 ON T1.CustomerID = T2.CustomerID WHERE T1.Segment = 'SME' AND T2.Date = '201302' AND T2.Consumption > 0", "difficulty": "challenging"}
{"question_id": 163, "db_id": "european_football_2", "question": "Which away teams are tied for the most away wins in the Scottish Premier League 2009/2010 season?", "evidence": "", "SQL": "WITH wins AS (SELECT m.away_team_api_id, COUNT(*) AS n FROM `Match` AS m JOIN League AS l ON l.id = m.league_id WHERE l.name = 'Scotland Premier League' AND m.season = '2009/2010' AND m.away_team_goal > m.home_team_goal GROUP BY m.away_team_api_id) SELECT t.team_long_name FROM wins AS w JOIN Team AS t ON t.team_api_id = w.away_team_api_id WHERE w.n = (SELECT MAX(n) FROM wins) ORDER BY t.team_api_id", "difficulty": "challenging"}
{"question_id": 164, "db_id": "european_football_2", "question": "List the long name of teams with above-average build-up play passing in 2012.", "evidence": "", "SQL": "SELECT DISTINCT t4.team_long_name FROM Team_Attributes AS t3 INNER JOIN Team AS t4 ON t3.team_api_id = t4.team_api_id WHERE SUBSTRING(t3.`date`, 1, 4) = '2012' AND t3.buildUpPlayPassing > (SELECT CAST(SUM(t2.buildUpPlayPassing) AS FLOAT) / COUNT(t1.id) FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE DATE_FORMAT(t2.`date`, '%Y') = '2012')", "difficulty": "challenging"}
{"question_id": 165, "db_id": "european_football_2", "question": "List the ten players taller than 180 cm with the highest mean recorded heading accuracy, highest first. Break mean ties by player API ID.", "evidence": "", "SQL": "SELECT p.player_name FROM Player AS p JOIN Player_Attributes AS a ON a.player_api_id = p.player_api_id WHERE p.height > 180 GROUP BY p.player_api_id, p.player_name ORDER BY AVG(a.heading_accuracy) DESC, p.player_api_id LIMIT 10", "difficulty": "moderate"}
{"question_id": 166, "db_id": "european_football_2", "question": "List the name of leagues in which the average goals by the home team is higher than the away team in the 2009/2010 season.", "evidence": "", "SQL": "SELECT t1.name FROM League AS t1 INNER JOIN `Match` AS t2 ON t1.id = t2.league_id WHERE t2.season = '2009/2010' GROUP BY t1.name HAVING (CAST(SUM(t2.home_team_goal) AS FLOAT) / COUNT(DISTINCT t2.id)) - (CAST(SUM(t2.away_team_goal) AS FLOAT) / COUNT(DISTINCT t2.id)) > 0", "difficulty": "challenging"}
{"question_id": 167, "db_id": "european_football_2", "question": "Between the tallest and shortest players, who has the higher average finishing attribute across his recorded assessments? Give the player's name.", "evidence": "", "SQL": "SELECT p.player_name FROM Player AS p JOIN Player_Attributes AS a ON a.player_api_id = p.player_api_id WHERE p.height IN ((SELECT MAX(height) FROM Player), (SELECT MIN(height) FROM Player)) GROUP BY p.player_api_id, p.player_name ORDER BY AVG(a.finishing) DESC, p.player_api_id LIMIT 1", "difficulty": "challenging"}
{"question_id": 168, "db_id": "european_football_2", "question": "What is Abdou Diallo's mean recorded ball-control score minus Aaron Appindangoye's mean recorded ball-control score?", "evidence": "", "SQL": "SELECT CAST(SUM(CASE WHEN t1.player_name = 'Abdou Diallo' THEN t2.ball_control ELSE 0 END) AS FLOAT) / COUNT(CASE WHEN t1.player_name = 'Abdou Diallo' THEN t2.id ELSE NULL END) - CAST(SUM(CASE WHEN t1.player_name = 'Aaron Appindangoye' THEN t2.ball_control ELSE 0 END) AS FLOAT) / COUNT(CASE WHEN t1.player_name = 'Aaron Appindangoye' THEN t2.id ELSE NULL END) FROM Player AS t1 INNER JOIN Player_Attributes AS t2 ON t1.player_api_id = t2.player_api_id", "difficulty": "challenging"}
{"question_id": 169, "db_id": "european_football_2", "question": "By what percentage is Ariel Borysiuk's overall rating in his latest attribute record higher than Paulin Puel's latest overall rating? Round to two decimals.", "evidence": "", "SQL": "WITH latest AS (SELECT p.player_name, a.overall_rating, ROW_NUMBER() OVER (PARTITION BY p.player_api_id ORDER BY a.date DESC, a.id DESC) AS rn FROM Player AS p JOIN Player_Attributes AS a ON a.player_api_id = p.player_api_id WHERE p.player_name IN ('Ariel Borysiuk', 'Paulin Puel')) SELECT ROUND(100.0 * (MAX(CASE WHEN player_name = 'Ariel Borysiuk' THEN overall_rating END) - MAX(CASE WHEN player_name = 'Paulin Puel' THEN overall_rating END)) / NULLIF(MAX(CASE WHEN player_name = 'Paulin Puel' THEN overall_rating END), 0), 2) FROM latest WHERE rn = 1", "difficulty": "challenging"}
{"question_id": 170, "db_id": "european_football_2", "question": "On what date did Kevin Constant first record his highest crossing score?", "evidence": "", "SQL": "SELECT pa.date FROM Player_Attributes AS pa JOIN Player AS p ON p.player_fifa_api_id = pa.player_fifa_api_id WHERE p.player_name = 'Kevin Constant' AND NOT pa.crossing IS NULL ORDER BY pa.crossing DESC, pa.date ASC LIMIT 1", "difficulty": "moderate"}
{"question_id": 171, "db_id": "european_football_2", "question": "Among players shorter than 180 cm, what percentage have at least one recorded overall rating above 70? Round to two decimal places.", "evidence": "", "SQL": "SELECT ROUND(100.0 * COUNT(DISTINCT CASE WHEN a.overall_rating > 70 THEN p.player_api_id END) / NULLIF(COUNT(DISTINCT p.player_api_id), 0), 2) FROM Player AS p LEFT JOIN Player_Attributes AS a ON a.player_api_id = p.player_api_id WHERE p.height < 180", "difficulty": "moderate"}
{"question_id": 172, "db_id": "european_football_2", "question": "What is the average height, in centimetres, of the players taller than 180 cm who have appeared in the home team's number-3 lineup slot? This should cover the whole recorded match history with no season or date restriction. 'Taller than 180' means strictly taller than 180 cm. Please round the final average to two decimal places and return just that single value.", "evidence": "Number-3 lineup slot: each match records a home team's starting eleven as eleven ordered player slots; the number-3 slot is the home team's third slot.", "SQL": "SELECT ROUND(AVG(height), 2) AS avg_height FROM (SELECT p.height AS height FROM Player AS p JOIN `Match` AS m ON m.home_player_3 = p.player_api_id WHERE p.height > 180 GROUP BY p.player_api_id, p.height) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 173, "db_id": "european_football_2", "question": "I'm sizing up how defensive-minded the young generation is. Among players born after 1990 (i.e., born in 1991 or later) who have a defensive work rate rating, what share are rated high? A player counts as rated high if they've been rated high at any point in their career. Give me that share as a percentage rounded to two decimal places - nothing else.", "evidence": "Defensive work rate: a player's rating for defensive effort, on a low / medium / high scale.", "SQL": "SELECT ROUND(100.0 * (SELECT COUNT(DISTINCT pa.player_api_id) FROM Player AS p JOIN Player_Attributes AS pa ON pa.player_api_id = p.player_api_id WHERE CAST(DATE_FORMAT(p.birthday, '%Y') AS SIGNED) > 1990 AND pa.defensive_work_rate = 'high') / (SELECT COUNT(DISTINCT pa.player_api_id) FROM Player AS p JOIN Player_Attributes AS pa ON pa.player_api_id = p.player_api_id WHERE CAST(DATE_FORMAT(p.birthday, '%Y') AS SIGNED) > 1990 AND pa.defensive_work_rate IN ('low', 'medium', 'high')), 2) AS share_pct", "difficulty": "challenging"}
{"question_id": 174, "db_id": "european_football_2", "question": "I've shortlisted the players whose overall rating as of 31 December 2010 was above 80 - strictly above 80, that is. How many matches did these players play on average during the 2010/2011 season? Please give me just that single average, rounded to two decimals.", "evidence": "", "SQL": "WITH latest AS (SELECT player_api_id, MAX(date) AS md FROM Player_Attributes WHERE date <= '2010-12-31 00:00:00' GROUP BY player_api_id), shortlist AS (SELECT p.player_api_id FROM latest AS l JOIN Player_Attributes AS a ON a.player_api_id = l.player_api_id AND a.date = l.md JOIN Player AS p ON p.player_api_id = l.player_api_id WHERE a.overall_rating > 80 GROUP BY p.player_api_id), slots AS (SELECT id, home_player_1 AS pid FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_2 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_3 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_4 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_5 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_6 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_7 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_8 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_9 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_10 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, home_player_11 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_1 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_2 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_3 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_4 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_5 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_6 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_7 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_8 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_9 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_10 FROM `Match` WHERE season = '2010/2011' UNION ALL SELECT id, away_player_11 FROM `Match` WHERE season = '2010/2011'), apps AS (SELECT pid, COUNT(DISTINCT id) AS matches FROM slots WHERE NOT pid IS NULL GROUP BY pid) SELECT ROUND(AVG(COALESCE(x.matches, 0)), 2) AS average_matches FROM shortlist AS s LEFT JOIN apps AS x ON x.pid = s.player_api_id", "difficulty": "challenging"}
{"question_id": 175, "db_id": "european_football_2", "question": "What is the average height in centimeters of players whose current defensive work rate grade is not medium? Use each player's most recent rating record to determine their current grade, and round the result to two decimal places. I just need that single number.", "evidence": "Defensive work rate grades run low, medium and high.", "SQL": "WITH latest AS (SELECT player_api_id, defensive_work_rate, ROW_NUMBER() OVER (PARTITION BY player_api_id ORDER BY date DESC, id DESC) AS rn FROM Player_Attributes) SELECT ROUND(AVG(p.height), 2) AS average_height FROM latest AS l JOIN Player AS p ON p.player_api_id = l.player_api_id WHERE l.rn = 1 AND l.defensive_work_rate IN ('low', 'high')", "difficulty": "challenging"}
{"question_id": 176, "db_id": "european_football_2", "question": "I'm preparing a report on team playing styles. First, consider only teams whose chance creation passing class was Risky at any point in the recorded history. Among those, I want the short names that are carried by more than one club. For each such short name, please give me: the short name, the number of clubs that carry it, and the average chance creation passing risk of those clubs that was in force on 19 September 2014, rounded to one decimal place. Sort the results by that average, highest first; if two averages are the same, order them alphabetically by short name.", "evidence": "A team's chance creation passing class is 'Risky' when chanceCreationPassingClass = 'Risky'; its chance creation passing risk is the chanceCreationPassing value in force on the date in question.", "SQL": "WITH risky AS (SELECT DISTINCT team_api_id FROM Team_Attributes WHERE chanceCreationPassingClass = 'Risky'), cur AS (SELECT team_api_id, chanceCreationPassing FROM Team_Attributes AS ta WHERE ta.date = (SELECT MAX(date) FROM Team_Attributes AS x WHERE x.team_api_id = ta.team_api_id AND x.date <= '2014-09-19 00:00:00')) SELECT t.team_short_name AS team_short_name, COUNT(DISTINCT t.team_api_id) AS n_teams, ROUND(AVG(c.chanceCreationPassing), 1) AS avg_passing FROM Team AS t JOIN risky AS r ON r.team_api_id = t.team_api_id JOIN cur AS c ON c.team_api_id = t.team_api_id GROUP BY t.team_short_name HAVING COUNT(DISTINCT t.team_api_id) > 1 ORDER BY avg_passing DESC, t.team_short_name", "difficulty": "challenging"}
{"question_id": 177, "db_id": "european_football_2", "question": "I want to gauge how tall the current medium-defensive-work players from the 1990-1995 birth cohort are. Please find the average height, in centimetres, of players born from 1990 through 1995 inclusive whose defensive work rating is medium, and round the average to two decimals. A player's rating is the grade on their most recent record that carries a grade.", "evidence": "The defensive work rating grades are low, medium and high.", "SQL": "WITH latest_grade AS (SELECT player_api_id, defensive_work_rate, ROW_NUMBER() OVER (PARTITION BY player_api_id ORDER BY date DESC, id DESC) AS rn FROM Player_Attributes WHERE defensive_work_rate IN ('low', 'medium', 'high')) SELECT ROUND(AVG(p.height), 2) AS average_height FROM Player AS p JOIN latest_grade AS g ON g.player_api_id = p.player_api_id AND g.rn = 1 WHERE SUBSTRING(p.birthday, 1, 4) BETWEEN '1990' AND '1995' AND g.defensive_work_rate = 'medium'", "difficulty": "challenging"}
{"question_id": 178, "db_id": "european_football_2", "question": "What is the average weight of all left-footed players? Round the average to one decimal place.", "evidence": "Left-footed means the player's preferred foot when attacking is the left one.", "SQL": "SELECT ROUND(AVG(weight), 1) AS average_weight FROM Player WHERE player_api_id IN (SELECT player_api_id FROM Player_Attributes WHERE preferred_foot = 'left')", "difficulty": "challenging"}
{"question_id": 179, "db_id": "european_football_2", "question": "I'm putting together a participation report for the 2015/2016 season. For every player whose name starts with Adam and who weighs more than 170, I need the number of matches he played during that season. Please return, one row per qualifying player, the player's name and his number of matches played in the 2015/2016 season, and nothing else. The season I mean is the one labeled '2015/2016'.", "evidence": "Played a match means being named in that match's lineup, for either the home or the away team.", "SQL": "WITH apps AS (SELECT id AS mid, home_player_1 AS pid FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_2 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_3 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_4 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_5 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_6 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_7 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_8 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_9 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_10 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_11 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_1 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_2 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_3 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_4 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_5 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_6 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_7 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_8 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_9 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_10 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_11 FROM `Match` WHERE season = '2015/2016') SELECT p.player_name, COUNT(a.mid) AS matches_played FROM Player AS p LEFT JOIN apps AS a ON a.pid = p.player_api_id WHERE p.player_name LIKE 'Adam%' AND p.weight > 170 GROUP BY p.id, p.player_name ORDER BY p.player_name COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 180, "db_id": "european_football_2", "question": "What was the build-up play dribbling class for the team from England with short name POR on 10 September 2015? I just need that single class value for that team on that calendar day.", "evidence": "", "SQL": "SELECT t2.buildUpPlayDribblingClass FROM Team AS t1 INNER JOIN Team_Attributes AS t2 ON t1.team_api_id = t2.team_api_id WHERE t1.team_short_name = 'POR' AND t1.team_api_id IN (SELECT m.home_team_api_id FROM `Match` AS m INNER JOIN Country AS c ON c.id = m.country_id WHERE c.name = 'England' UNION SELECT m.away_team_api_id FROM `Match` AS m INNER JOIN Country AS c ON c.id = m.country_id WHERE c.name = 'England') AND t2.`date` >= '2015-09-10 00:00:00' AND t2.`date` < '2015-09-11 00:00:00'", "difficulty": "challenging"}
{"question_id": 181, "db_id": "european_football_2", "question": "I'm looking at whether a fast attacking build-up actually converts into big results. Which clubs, playing at home, have won a match by at least 3 goals while their build-up play speed was rated fast at the time? For each such club, give me the club name, short name, and how many of those home wins it has - one row per club. Please treat clubs as separate even if two clubs share the same short name, and if several clubs tie on the number of wins, list all of them. The speed rating that counts is the club's most recent rating dated on or before the match's own date.", "evidence": "A club wins by at least 3 goals when its goal count minus the opponent's goal count is 3 or more; 'fast' means the club's build-up play speed class at that time is Fast.", "SQL": "SELECT t.team_long_name AS club_name, t.team_short_name AS short_name, COUNT(*) AS home_wins FROM `Match` AS m JOIN Team AS t ON t.team_api_id = m.home_team_api_id WHERE m.home_team_goal - m.away_team_goal >= 3 AND (SELECT ta.buildUpPlaySpeedClass FROM Team_Attributes AS ta WHERE ta.team_api_id = m.home_team_api_id AND ta.date <= m.date ORDER BY ta.date DESC, ta.id DESC LIMIT 1) = 'Fast' GROUP BY t.team_api_id, t.team_long_name, t.team_short_name ORDER BY home_wins DESC, t.team_long_name COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 182, "db_id": "european_football_2", "question": "I'm writing a piece about players who've suffered heavy away defeats. For each season, I'd like to know how many different players were in the away team's lineup for a match that the away side lost by five or more goals. Please give me one row per season that had at least one such match, showing the season label (like 2012/2013) and the number of different players, ordered by season label.", "evidence": "", "SQL": "WITH away_lineup AS (SELECT season, away_player_1 AS pid FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_2 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_3 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_4 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_5 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_6 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_7 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_8 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_9 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_10 FROM `Match` WHERE home_team_goal - away_team_goal >= 5 UNION ALL SELECT season, away_player_11 FROM `Match` WHERE home_team_goal - away_team_goal >= 5) SELECT season, COUNT(DISTINCT pid) AS players FROM away_lineup WHERE NOT pid IS NULL GROUP BY season ORDER BY season", "difficulty": "challenging"}
{"question_id": 183, "db_id": "european_football_2", "question": "I want to find out which European league country had the largest group of exceptionally heavy players appear in its matches. For each country, I'm interested in players weighing 210 pounds or more who took part in matches played in that country's league - count players from both teams in each match. Please tell me which country had the most such players and how many there were. If several countries tie for the most, list them all, ordered alphabetically by country name. I just need the country name and the number of qualifying players - nothing more.", "evidence": "", "SQL": "WITH appearances AS (SELECT m.country_id, p.player_api_id FROM `Match` AS m JOIN Player AS p ON p.player_api_id IN (m.home_player_1, m.home_player_2, m.home_player_3, m.home_player_4, m.home_player_5, m.home_player_6, m.home_player_7, m.home_player_8, m.home_player_9, m.home_player_10, m.home_player_11, m.away_player_1, m.away_player_2, m.away_player_3, m.away_player_4, m.away_player_5, m.away_player_6, m.away_player_7, m.away_player_8, m.away_player_9, m.away_player_10, m.away_player_11) WHERE p.weight >= 210), counts AS (SELECT c.name AS country, COUNT(DISTINCT a.player_api_id) AS player_count FROM appearances AS a JOIN Country AS c ON c.id = a.country_id GROUP BY c.id, c.name) SELECT country, player_count FROM counts WHERE player_count = (SELECT MAX(player_count) FROM counts) ORDER BY country", "difficulty": "challenging"}
{"question_id": 184, "db_id": "european_football_2", "question": "I'm studying squad physical profiles in Serie A. For the 2008/2009 season and the 2015/2016 season of the Italian league, I'd like to know how many players appeared in matches that season (i.e. were listed in a match's lineup, including players who appeared in both seasons), and the average height of those players in centimeters, rounded to two decimals. One row per season with the season label, the count of players, and their average height.", "evidence": "A player appeared in a match if he is listed in that match's lineup (eleven home and eleven away players). Italian league = the league of the country Italy.", "SQL": "WITH italy AS (SELECT * FROM `Match` WHERE country_id = (SELECT id FROM Country WHERE name = 'Italy') AND season IN ('2008/2009', '2015/2016')), slots AS (SELECT id, season, home_player_1 AS pid FROM italy UNION ALL SELECT id, season, home_player_2 FROM italy UNION ALL SELECT id, season, home_player_3 FROM italy UNION ALL SELECT id, season, home_player_4 FROM italy UNION ALL SELECT id, season, home_player_5 FROM italy UNION ALL SELECT id, season, home_player_6 FROM italy UNION ALL SELECT id, season, home_player_7 FROM italy UNION ALL SELECT id, season, home_player_8 FROM italy UNION ALL SELECT id, season, home_player_9 FROM italy UNION ALL SELECT id, season, home_player_10 FROM italy UNION ALL SELECT id, season, home_player_11 FROM italy UNION ALL SELECT id, season, away_player_1 FROM italy UNION ALL SELECT id, season, away_player_2 FROM italy UNION ALL SELECT id, season, away_player_3 FROM italy UNION ALL SELECT id, season, away_player_4 FROM italy UNION ALL SELECT id, season, away_player_5 FROM italy UNION ALL SELECT id, season, away_player_6 FROM italy UNION ALL SELECT id, season, away_player_7 FROM italy UNION ALL SELECT id, season, away_player_8 FROM italy UNION ALL SELECT id, season, away_player_9 FROM italy UNION ALL SELECT id, season, away_player_10 FROM italy UNION ALL SELECT id, season, away_player_11 FROM italy), players AS (SELECT DISTINCT season, pid FROM slots WHERE NOT pid IS NULL) SELECT p.season, COUNT(*) AS n_players, ROUND(AVG(pl.height), 2) AS avg_height FROM players AS p JOIN Player AS pl ON pl.player_api_id = p.pid GROUP BY p.season ORDER BY p.season", "difficulty": "challenging"}
{"question_id": 185, "db_id": "european_football_2", "question": "I'm putting together a report on current player abilities. How many players are over 180 cm tall and have a volley score above 70 on their most recent rating record? Judge each player by their current rating only, not their career history. For each player, use the rating record with the latest date; if a player has several rating records on that same latest date, count them only based on the single record with the highest id on that date.", "evidence": "By volley I mean a player's ability to strike the ball while it is in the air, and a rating record is a dated assessment of a player's attributes.", "SQL": "WITH latest AS (SELECT player_api_id, volleys, ROW_NUMBER() OVER (PARTITION BY player_api_id ORDER BY date DESC, id DESC) AS rn FROM Player_Attributes) SELECT COUNT(DISTINCT t1.id) AS tall_volley_players FROM Player AS t1 INNER JOIN latest AS t2 ON t1.player_api_id = t2.player_api_id WHERE t1.height > 180 AND t2.rn = 1 AND t2.volleys > 70", "difficulty": "challenging"}
{"question_id": 186, "db_id": "european_football_2", "question": "I'm reviewing home-match outcomes by lineup slot and want one number: across the whole player population, what is the average of the total home-team goals scored in the matches where a player appeared as the home team's third listed player? In other words, for each player, take all matches where they were the home team's third listed player and add up the home team's goals in those matches; give me the average of those totals over all players, rounded to two decimal places.", "evidence": "The home team's third listed player means the player recorded third in the home team's lineup for a match.", "SQL": "SELECT ROUND(SUM(m.home_team_goal) * 1.0 / COUNT(DISTINCT p.player_api_id), 2) AS avg_home_goals_per_player FROM Player AS p LEFT JOIN `Match` AS m ON m.home_player_3 = p.player_api_id", "difficulty": "challenging"}
{"question_id": 187, "db_id": "european_football_2", "question": "I'm studying where small, low-weight players are concentrated across European leagues. Which country's league matches featured the fewest players weighing at most 160 pounds? If several countries tie for the fewest, give me every tied country's name. Include all seasons in the database, and count the players who took part in those matches.", "evidence": "Players are associated with a country through the matches they played in that country's league; all 22 players of a match, the 11 of the home team and the 11 of the away team, took part in it.", "SQL": "WITH appearances AS (SELECT country_id, home_player_1 AS player_api_id FROM `Match` UNION SELECT country_id, home_player_2 FROM `Match` UNION SELECT country_id, home_player_3 FROM `Match` UNION SELECT country_id, home_player_4 FROM `Match` UNION SELECT country_id, home_player_5 FROM `Match` UNION SELECT country_id, home_player_6 FROM `Match` UNION SELECT country_id, home_player_7 FROM `Match` UNION SELECT country_id, home_player_8 FROM `Match` UNION SELECT country_id, home_player_9 FROM `Match` UNION SELECT country_id, home_player_10 FROM `Match` UNION SELECT country_id, home_player_11 FROM `Match` UNION SELECT country_id, away_player_1 FROM `Match` UNION SELECT country_id, away_player_2 FROM `Match` UNION SELECT country_id, away_player_3 FROM `Match` UNION SELECT country_id, away_player_4 FROM `Match` UNION SELECT country_id, away_player_5 FROM `Match` UNION SELECT country_id, away_player_6 FROM `Match` UNION SELECT country_id, away_player_7 FROM `Match` UNION SELECT country_id, away_player_8 FROM `Match` UNION SELECT country_id, away_player_9 FROM `Match` UNION SELECT country_id, away_player_10 FROM `Match` UNION SELECT country_id, away_player_11 FROM `Match`), counts AS (SELECT T1.name AS name, COUNT(DISTINCT T3.player_api_id) AS n_players FROM Country AS T1 INNER JOIN appearances AS T2 ON T1.id = T2.country_id INNER JOIN Player AS T3 ON T3.player_api_id = T2.player_api_id WHERE T3.weight <= 160 GROUP BY T1.name) SELECT name FROM counts WHERE n_players = (SELECT MIN(n_players) FROM counts)", "difficulty": "challenging"}
{"question_id": 188, "db_id": "european_football_2", "question": "As of 1 January 2015, how many players preferred their left foot and had an attacking work rate below high (i.e. low or medium)? I just need the count of those players.", "evidence": "Attacking work rate is a rating on the scale low, medium, high; below high means low or medium. The player's preferred foot and work rate are the ones that held on 1 January 2015.", "SQL": "SELECT COUNT(DISTINCT pa.player_api_id) AS player_count FROM Player_Attributes AS pa JOIN (SELECT player_api_id, MAX(date) AS latest FROM Player_Attributes WHERE date <= '2015-01-01 00:00:00' GROUP BY player_api_id) AS t ON pa.player_api_id = t.player_api_id AND pa.date = t.latest WHERE pa.preferred_foot = 'left' AND pa.attacking_work_rate IN ('low', 'medium')", "difficulty": "challenging"}
{"question_id": 189, "db_id": "european_football_2", "question": "What percentage of left-footed players currently has a low attacking work rate? Use each player's most recent attribute record. Only count left-footed players whose current record includes an attacking work rate rating - those without one should be left out of the share. Give me a single percentage, rounded to one decimal place.", "evidence": "Attacking work rate: how much effort a player puts into attacking plays, rated low, medium or high.", "SQL": "WITH latest AS (SELECT player_api_id, MAX(date) AS d FROM Player_Attributes GROUP BY player_api_id) SELECT ROUND(100.0 * COUNT(DISTINCT CASE WHEN pa.attacking_work_rate = 'low' THEN pa.player_api_id END) / COUNT(DISTINCT CASE WHEN pa.attacking_work_rate IN ('low', 'medium', 'high') THEN pa.player_api_id END), 1) AS pct FROM Player_Attributes AS pa JOIN latest AS l ON pa.player_api_id = l.player_api_id AND pa.date = l.d WHERE pa.preferred_foot = 'left'", "difficulty": "challenging"}
{"question_id": 190, "db_id": "european_football_2", "question": "I want to see which of the young Aaron-named players actually got playing time in 2015/2016. For every player born after 1990 whose name begins with 'Aaron', can you give me his name and the number of matches he played in during the 2015/2016 season (the season labelled 2015/2016)? A player counts as having played in a match if he's recorded in either team's starting line-up for that match. One row per player, sorted alphabetically by player name.", "evidence": "", "SQL": "SELECT p.player_name, COUNT(DISTINCT m.match_id) AS matches FROM Player AS p LEFT JOIN (SELECT id AS match_id, home_player_1 AS pid FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_2 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_3 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_4 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_5 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_6 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_7 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_8 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_9 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_10 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, home_player_11 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_1 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_2 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_3 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_4 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_5 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_6 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_7 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_8 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_9 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_10 FROM `Match` WHERE season = '2015/2016' UNION ALL SELECT id, away_player_11 FROM `Match` WHERE season = '2015/2016') AS m ON m.pid = p.player_api_id WHERE CAST(SUBSTRING(p.birthday, 1, 4) AS SIGNED) > 1990 AND p.player_name LIKE 'Aaron%' GROUP BY p.id, p.player_name ORDER BY p.player_name", "difficulty": "challenging"}
{"question_id": 191, "db_id": "european_football_2", "question": "How many players had a jumping score of 80 or higher in the player fitness assessments made between 22 February 2007 and 30 August 2007, with both of those dates included in the period? For clarity, the jumping score is the player's jumping assessment on a 1-100 scale.", "evidence": "jumping score: the player's jumping assessment on a 1-100 scale", "SQL": "SELECT COUNT(DISTINCT player_api_id) AS player_count FROM Player_Attributes WHERE jumping >= 80 AND DATE(date) BETWEEN '2007-02-22' AND '2007-08-30'", "difficulty": "challenging"}
{"question_id": 192, "db_id": "european_football_2", "question": "What was KSV Cercle Brugge's build-up-play speed class at the time of their last match of the 2012/2013 season? The last match of the season is the latest-dated match the team played in that season, and the snapshot in effect at a moment is the latest one dated on or before that moment. I just want that single build-up-play speed class, nothing else.", "evidence": "Build-up-play speed class: a team's speed class for how quickly attacks are put together.", "SQL": "WITH last_match AS (SELECT MAX(m.date) AS match_day FROM `Match` AS m JOIN Team AS t ON t.team_api_id = m.home_team_api_id OR t.team_api_id = m.away_team_api_id WHERE t.team_long_name = 'KSV Cercle Brugge' AND m.season = '2012/2013'), effective AS (SELECT ta.buildUpPlaySpeedClass AS speed_class FROM Team_Attributes AS ta JOIN Team AS t2 ON t2.team_api_id = ta.team_api_id JOIN last_match AS lm ON ta.date <= lm.match_day WHERE t2.team_long_name = 'KSV Cercle Brugge' ORDER BY ta.date DESC LIMIT 1) SELECT speed_class FROM effective", "difficulty": "challenging"}
{"question_id": 193, "db_id": "european_football_2", "question": "I'm profiling how exceptional Landon Donovan was in the mid-2013 player ratings. By what percentage was his overall rating on 12 July 2013 higher than the average overall rating across all players on that same calendar date, considering every player with the overall rating they carried on that date (not only those updated that day), among players rated low, medium or high for defensive work rate? Return one value only: that percentage, rounded to two decimals (e.g. 12.34 meaning 12.34% higher).", "evidence": "Defensive work rate: a player's intensity of work in defense, rated low, medium or high. Overall rating: the overall score given to a player in the ratings.", "SQL": "WITH donovan AS (SELECT a.overall_rating AS r FROM Player AS p JOIN Player_Attributes AS a ON a.player_api_id = p.player_api_id WHERE p.player_name = 'Landon Donovan' AND a.date >= '2013-07-12' AND a.date < '2013-07-13'), inforce AS (SELECT a.player_api_id AS pid, a.overall_rating AS r, a.defensive_work_rate AS dwr FROM Player_Attributes AS a JOIN (SELECT player_api_id, MAX(date) AS md FROM Player_Attributes WHERE date < '2013-07-13' GROUP BY player_api_id) AS m ON a.player_api_id = m.player_api_id AND a.date = m.md) SELECT ROUND(100.0 * ((SELECT r FROM donovan) - AVG(r)) / AVG(r), 2) AS percentage FROM inforce WHERE dwr IN ('low', 'medium', 'high')", "difficulty": "challenging"}
{"question_id": 194, "db_id": "financial", "question": "Among female clients living in the district with the lowest average salary, give the account IDs of the oldest client and the difference between the highest and lowest district-average salaries.", "evidence": "", "SQL": "WITH oldest AS (SELECT c.client_id FROM client AS c JOIN district AS d ON d.district_id = c.district_id WHERE c.gender = 'F' AND d.A11 = (SELECT MIN(A11) FROM district) ORDER BY c.birth_date, c.client_id LIMIT 1) SELECT DISTINCT a.account_id, (SELECT MAX(A11) - MIN(A11) FROM district) FROM oldest AS o JOIN disp AS x ON x.client_id = o.client_id JOIN account AS a ON a.account_id = x.account_id ORDER BY a.account_id", "difficulty": "challenging"}
{"question_id": 195, "db_id": "financial", "question": "In which district did the female client born on 1976-01-29 open her account?", "evidence": "", "SQL": "SELECT DISTINCT d.A2 FROM client AS c JOIN disp AS x ON x.client_id = c.client_id JOIN account AS a ON a.account_id = x.account_id JOIN district AS d ON d.district_id = a.district_id WHERE c.gender = 'F' AND c.birth_date = '1976-01-29' ORDER BY d.A2", "difficulty": "simple"}
{"question_id": 196, "db_id": "financial", "question": "Among south Bohemia districts, in the one with the largest population, what percentage of resident clients are male? Round to two decimals.", "evidence": "", "SQL": "WITH chosen AS (SELECT district_id FROM district WHERE A3 = 'south Bohemia' ORDER BY CAST(A4 AS SIGNED) DESC, district_id LIMIT 1) SELECT ROUND(100.0 * SUM(CASE WHEN c.gender = 'M' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM client AS c JOIN chosen AS d ON d.district_id = c.district_id", "difficulty": "challenging"}
{"question_id": 197, "db_id": "financial", "question": "For the account associated with the loan dated 1993-07-05, what was the percentage increase in its recorded balance from 1993-03-22 to 1998-12-27?", "evidence": "", "SQL": "SELECT CAST((SUM(IF(T3.date = '1998-12-27', T3.balance, 0)) - SUM(IF(T3.date = '1993-03-22', T3.balance, 0))) AS FLOAT) * 100 / SUM(IF(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'", "difficulty": "challenging"}
{"question_id": 198, "db_id": "financial", "question": "For accounts opened from 1995 through 2000 in East Bohemia districts, list each account ID and its statement-issuance frequency.", "evidence": "", "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 DATE_FORMAT(T1.date, '%Y') BETWEEN '1995' AND '2000'", "difficulty": "moderate"}
{"question_id": 199, "db_id": "financial", "question": "For branch districts of accounts with loans still running in debt and recorded unemployment rates in both 1995 and 1996, list each district and the percentage change in its unemployment rate from 1995 to 1996, rounded to two decimal places.", "evidence": "Loan status 'D' denotes a running contract with the client in debt.", "SQL": "SELECT DISTINCT d.A2, ROUND(100.0 * (CAST(d.A13 AS DECIMAL(10, 2)) - CAST(d.A12 AS DECIMAL(10, 2))) / NULLIF(CAST(d.A12 AS DECIMAL(10, 2)), 0), 2) FROM loan AS l JOIN account AS a ON l.account_id = a.account_id JOIN district AS d ON a.district_id = d.district_id WHERE l.status = 'D' AND d.A12 <> 0 AND NOT d.A13 IS NULL ORDER BY d.A2", "difficulty": "challenging"}
{"question_id": 200, "db_id": "financial", "question": "For each account-disposition type other than OWNER found in districts with average salary above 8000 and at most 9000, give the type and the number of distinct associated accounts.", "evidence": "", "SQL": "SELECT d.type, COUNT(DISTINCT a.account_id) FROM district AS x JOIN account AS a ON a.district_id = x.district_id JOIN disp AS d ON d.account_id = a.account_id WHERE d.type <> 'OWNER' AND x.A11 > 8000 AND x.A11 <= 9000 GROUP BY d.type ORDER BY d.type", "difficulty": "challenging"}
{"question_id": 201, "db_id": "financial", "question": "For loans dated in 1996 and 1997 across accounts owned by male clients, what was the percentage growth in total loan amount from 1996 to 1997?", "evidence": "", "SQL": "SELECT CAST((SUM(CASE WHEN DATE_FORMAT(T1.date, '%Y') = '1997' THEN T1.amount ELSE 0 END) - SUM(CASE WHEN DATE_FORMAT(T1.date, '%Y') = '1996' THEN T1.amount ELSE 0 END)) AS FLOAT) * 100 / SUM(CASE WHEN DATE_FORMAT(T1.date, '%Y') = '1996' THEN T1.amount ELSE 0 END) FROM loan AS T1 INNER JOIN account AS T2 ON T1.account_id = T2.account_id INNER JOIN disp AS T3 ON T3.account_id = T2.account_id INNER JOIN client AS T4 ON T4.client_id = T3.client_id WHERE T4.gender = 'M' AND T3.type = 'OWNER'", "difficulty": "challenging"}
{"question_id": 202, "db_id": "financial", "question": "How often does account 3 receive statements, and what is the recorded payment-purpose code for its scheduled payments totaling 3,539?", "evidence": "", "SQL": "SELECT T1.frequency, T2.k_symbol FROM account AS T1 INNER JOIN (SELECT account_id, k_symbol, SUM(amount) AS total_amount FROM `order` GROUP BY account_id, k_symbol) AS T2 ON T1.account_id = T2.account_id WHERE T1.account_id = 3 AND T2.total_amount = 3539", "difficulty": "challenging"}
{"question_id": 203, "db_id": "financial", "question": "We're reviewing our first month of operations. Looking at the districts where we opened at least one account during that first month, which district had the largest population, and how many inhabitants does it have? If several districts tie for the largest population, list all of them with their populations.", "evidence": "The bank's first month of operation is the calendar month in which its earliest account was opened.", "SQL": "WITH first_month AS (SELECT DATE_FORMAT(MIN(date), '%Y-%m') AS ym FROM account), first_month_districts AS (SELECT DISTINCT district_id FROM account WHERE DATE_FORMAT(date, '%Y-%m') = (SELECT ym FROM first_month)), cohort AS (SELECT d.A2 AS district_name, CAST(d.A4 AS SIGNED) AS inhabitants FROM district AS d JOIN first_month_districts AS f ON d.district_id = f.district_id) SELECT district_name, inhabitants FROM cohort WHERE inhabitants = (SELECT MAX(inhabitants) FROM cohort)", "difficulty": "challenging"}
{"question_id": 204, "db_id": "financial", "question": "As part of a data-quality review for a segment report, I need to know how much of the recorded transaction activity for one of our segments has no payment purpose noted. How many transactions are there, over the whole recorded history, on the accounts held by male customers born between 1974 and 1976 (birth years 1974, 1975 and 1976), for which no payment purpose is noted? Please give me just that single number.", "evidence": "Payment purpose: the stated reason or note recorded for a transaction.", "SQL": "SELECT COUNT(*) AS txn_count FROM trans AS t WHERE (t.k_symbol IS NULL OR TRIM(t.k_symbol) = '') AND t.account_id IN (SELECT d.account_id FROM disp AS d INNER JOIN client AS c ON d.client_id = c.client_id WHERE c.gender = 'M' AND DATE_FORMAT(c.birth_date, '%Y') BETWEEN '1974' AND '1976')", "difficulty": "challenging"}
{"question_id": 205, "db_id": "financial", "question": "Among the bank's five most populous districts (the five with the largest numbers of inhabitants), which carries the heaviest active-lending burden relative to the account base it serves? For each of those five districts, please give me the district name and the average active loan per account, rounded to the nearest whole koruna. An active loan is a running loan contract with status 'C' (repaid OK so far) or status 'D' (client in debt). The average should be taken over every account held in the district, not just accounts with loans, and accounts and their loans count toward the district of the branch that holds the account, not the client's district. If several districts tie for the highest average, list them all.", "evidence": "", "SQL": "WITH populous AS (SELECT district_id FROM district ORDER BY CAST(A4 AS SIGNED) DESC LIMIT 5), per_district AS (SELECT d.A2 AS district_name, SUM(CASE WHEN l.status IN ('C', 'D') THEN l.amount ELSE 0 END) * 1.0 / COUNT(a.account_id) AS raw_avg FROM district AS d JOIN account AS a ON a.district_id = d.district_id LEFT JOIN loan AS l ON l.account_id = a.account_id WHERE d.district_id IN (SELECT district_id FROM populous) GROUP BY d.district_id, d.A2) SELECT district_name, ROUND(raw_avg, 0) AS avg_active_loan_per_account FROM per_district ORDER BY raw_avg DESC, district_name", "difficulty": "challenging"}
{"question_id": 206, "db_id": "financial", "question": "For our 1995 year-end loan review: which of the bank's regions has the largest total approved amount among loans that were still being repaid on 31 December 1995, and what is that total? Only count loans approved on or before that day whose repayment term still covers that day; loans approved after it don't count yet. A loan's term includes both its approval day and its last day. If several regions tie for the largest total, list every tied region with the total. Just give me the region name and the single total figure.", "evidence": "A loan is repaid over a term that starts on its approval day and lasts the number of months recorded for the loan; the loan is being repaid on every day of its term. Status 'C' means a running contract, OK so far; status 'D' means a running contract, client in debt. The regions are the bank's district regions.", "SQL": "WITH ends AS (SELECT d.A3 AS region, l.amount, DATE(CONCAT(CAST(CAST(SUBSTRING(l.date, 1, 4) AS SIGNED) + (CAST(SUBSTRING(l.date, 6, 2) AS SIGNED) - 1 + l.duration) DIV 12 AS CHAR), '-', SUBSTRING(CONCAT('0', (CAST(SUBSTRING(l.date, 6, 2) AS SIGNED) - 1 + l.duration) % 12 + 1), -2), '-', SUBSTRING(l.date, 9, 2))) AS end_date FROM loan AS l JOIN account AS a ON l.account_id = a.account_id JOIN district AS d ON a.district_id = d.district_id WHERE l.date <= '1995-12-31'), totals AS (SELECT region, SUM(amount) AS total_amount, RANK() OVER (ORDER BY SUM(amount) DESC) AS rnk FROM ends WHERE end_date >= '1995-12-31' GROUP BY region) SELECT region, total_amount FROM totals WHERE rnk = 1", "difficulty": "challenging"}
{"question_id": 207, "db_id": "financial", "question": "I'd like to know how many customer accounts based in North Bohemia as of the end of 1995 have had at least one transaction with partner bank AB at some point in their history. Please give me just that count as a single integer.", "evidence": "'End of 1995' means the state on 31 December 1995, and the AB transaction may date from any time, before or after that date; 'AB' is the code identifying the partner bank of the transaction.", "SQL": "SELECT COUNT(DISTINCT a.account_id) AS qualifying_accounts FROM district AS d JOIN account AS a ON d.district_id = a.district_id JOIN trans AS t ON a.account_id = t.account_id WHERE d.A3 = 'north Bohemia' AND a.date <= '1995-12-31' AND t.bank = 'AB'", "difficulty": "challenging"}
{"question_id": 208, "db_id": "financial", "question": "I'm profiling our East Bohemia branch districts that serve younger clients for a youth-product campaign. A district counts as serving a client when the client holds an account at a branch located in that district - it's the branch location that matters, not the client's home district. For the East Bohemia districts that serve at least one client born in the 1980s (birth years 1980 through 1989), please give me: the average of those districts' average salaries, rounded to two decimal places, and the number of such districts.", "evidence": "East Bohemia refers to the districts in the East Bohemia region of the Czech Republic.", "SQL": "SELECT ROUND(AVG(x.A11), 2) AS avg_salary, COUNT(*) AS district_count FROM (SELECT DISTINCT T1.district_id, T1.A11 FROM district AS T1 INNER JOIN account AS T2 ON T1.district_id = T2.district_id INNER JOIN disp AS T3 ON T2.account_id = T3.account_id INNER JOIN client AS T4 ON T3.client_id = T4.client_id WHERE T1.A3 = 'east Bohemia' AND DATE_FORMAT(T4.birth_date, '%Y') BETWEEN '1980' AND '1989') AS x", "difficulty": "challenging"}
{"question_id": 209, "db_id": "financial", "question": "I'm planning a card-offer mailing and want to gauge how affluent the home districts of certain clients are. Please give me one number: the average, over the districts where these clients live, of each district's average salary, rounded to two decimal places. The clients are account owners in central Bohemia who hold no credit card for their account. Two things to keep in mind: a client's district is the one recorded with the client, not the district of the account's branch; and a client counts as holding a card for an account if a card is linked to any disposition of that account, not just their own.", "evidence": "OWNER is the disposition type marking an account's owner; DISPONENT marks other account users.", "SQL": "WITH qualified AS (SELECT DISTINCT c.district_id FROM disp AS d JOIN client AS c ON c.client_id = d.client_id JOIN district AS dist ON c.district_id = dist.district_id WHERE d.type = 'OWNER' AND dist.A3 = 'central Bohemia' AND NOT EXISTS(SELECT 1 FROM card AS ca JOIN disp AS cd ON ca.disp_id = cd.disp_id WHERE cd.account_id = d.account_id)) SELECT ROUND(AVG(A11), 2) AS average_salary FROM district WHERE district_id IN (SELECT district_id FROM qualified)", "difficulty": "challenging"}
{"question_id": 210, "db_id": "financial", "question": "I'm preparing for a client review and want to gauge how indebted our older customers' accounts are, including accounts that never took any loans. Could you give me the average number of loans per account among accounts whose owner was born before 1950? By 'born before 1950' I mean a birth date earlier than 1 January 1950, and all loans should count regardless of when they were approved. Please give me the average rounded to two decimal places, and nothing else.", "evidence": "The owner of an account is the client with the OWNER disposition; a DISPONENT is a co-holder who does not own it. A loan is a credit granted on the account, recorded with the date it was approved.", "SQL": "WITH owner AS (SELECT T2.account_id, T1.birth_date FROM client AS T1 INNER JOIN disp AS T2 ON T1.client_id = T2.client_id WHERE T2.type = 'OWNER') SELECT ROUND(CAST(COUNT(T3.loan_id) AS FLOAT) / COUNT(DISTINCT T4.account_id), 2) AS average_loans_per_account FROM owner AS T4 LEFT JOIN loan AS T3 ON T4.account_id = T3.account_id WHERE T4.birth_date < '1950-01-01'", "difficulty": "challenging"}
{"question_id": 211, "db_id": "financial", "question": "I'm putting together a periodic report on large payments made by a specific customer cohort, split by what the payment was for. Among payments over $4000 (strictly more than $4000) made from the accounts of male customers born between 1974 and 1976, I need two figures: how many were household payments, and how many were made for a purpose other than household payment. A few rules to keep in mind: born between 1974 and 1976 means the birth year is 1974, 1975 or 1976; a customer's accounts are the ones they hold a disposition on; payments are the individual transactions executed on the account, not standing payment orders; a payment counts as other-purpose only if it has a recorded purpose different from household payment, and a payment with no purpose recorded counts in neither bucket.", "evidence": "SIPO stands for household payment.", "SQL": "SELECT COUNT(DISTINCT CASE WHEN t.k_symbol = 'SIPO' THEN t.trans_id END) AS household_payments, COUNT(DISTINCT CASE WHEN NOT t.k_symbol IS NULL AND TRIM(t.k_symbol) <> '' AND t.k_symbol <> 'SIPO' THEN t.trans_id END) AS other_purpose_payments FROM trans AS t JOIN disp AS d ON d.account_id = t.account_id JOIN client AS c ON c.client_id = d.client_id WHERE c.gender = 'M' AND CAST(DATE_FORMAT(c.birth_date, '%Y') AS SIGNED) BETWEEN 1974 AND 1976 AND t.amount > 4000", "difficulty": "challenging"}
{"question_id": 212, "db_id": "financial", "question": "I want to find out whether our borrowing households from larger population centres transact differently from local ones. For every account at the Prachatice branch that has taken at least one loan, please give me: the account number, the account opening date, the total amount ever borrowed, how many outside bank counterparties the account has transacted with over its entire history, the owner's home district, the population of that district, and a rank of these borrowing households by home-district population from largest to smallest. Note that a counterparty means a particular bank account at another institution, identified by that account number, not by the bank code, and only transfers to or from another bank count — handling cash at our own branch does not involve a counterparty. A household's home district is the district its owner client is registered in, which is not necessarily Prachatice. For the ranking: largest population first, ties share the same rank and the next rank after a tie is skipped, and among households whose home districts have the same population, list the smaller account number first.", "evidence": "An outside bank counterparty is a bank account at another institution that money was sent to or received from on a transfer transaction. District population is the number of inhabitants of the district.", "SQL": "WITH borrowers AS (SELECT a.account_id, a.date AS opening_date, (SELECT SUM(l.amount) FROM loan AS l WHERE l.account_id = a.account_id) AS total_borrowed FROM account AS a WHERE a.district_id = (SELECT district_id FROM district WHERE A2 = 'Prachatice') AND a.account_id IN (SELECT account_id FROM loan)), owners AS (SELECT d.account_id, c.district_id AS home_district_id FROM disp AS d JOIN client AS c ON c.client_id = d.client_id WHERE d.type = 'OWNER'), counterparties AS (SELECT account_id, COUNT(DISTINCT account) AS cnt FROM trans WHERE account > 0 GROUP BY account_id) SELECT bo.account_id, bo.opening_date, bo.total_borrowed, COALESCE(cp.cnt, 0) AS counterparty_count, hd.A2 AS home_district, CAST(hd.A4 AS SIGNED) AS home_population, RANK() OVER (ORDER BY CAST(hd.A4 AS SIGNED) DESC) AS population_rank FROM borrowers AS bo LEFT JOIN counterparties AS cp ON cp.account_id = bo.account_id LEFT JOIN owners AS o ON o.account_id = bo.account_id LEFT JOIN district AS hd ON hd.district_id = o.home_district_id ORDER BY population_rank ASC, bo.account_id ASC", "difficulty": "challenging"}
{"question_id": 213, "db_id": "financial", "question": "I'm profiling our gold-card customers for a regional campaign, split by gender. For women first, then men, look at gold-card holders whose card's account has an average balance over 1,000. Among the branch districts holding those accounts, keep only the districts with over 100,000 inhabitants. For each gender, tell me: the number of those districts; which of them has the most inhabitants, with its inhabitants figure - if two districts tie, list both, one row per district; the average salary across those districts, rounded to two decimals; and the average ratio of urban inhabitants across those districts, rounded to two decimals. Nothing else. Please note: 'over' means strictly greater than, and an account's average balance is the mean of its balances after each transaction.", "evidence": "A gold card is a card of type 'gold', and its holder is the client linked to its account as type 'OWNER'. The district of an account is the district of the branch that holds it; a district's inhabitants, salary and urban-inhabitant ratio are the district's own figures.", "SQL": "WITH gold_holder AS (SELECT d.account_id, cl.gender FROM card AS c JOIN disp AS d ON c.disp_id = d.disp_id JOIN client AS cl ON d.client_id = cl.client_id WHERE c.type = 'gold' AND d.type = 'OWNER'), acct_bal AS (SELECT account_id, AVG(balance) AS avg_balance FROM trans GROUP BY account_id), holder_district AS (SELECT DISTINCT gh.gender, a.district_id FROM gold_holder AS gh JOIN account AS a ON gh.account_id = a.account_id JOIN acct_bal AS ab ON ab.account_id = a.account_id AND ab.avg_balance > 1000), big AS (SELECT hd.gender, di.A2 AS name, CAST(di.A4 AS SIGNED) AS inhabitants, di.A11 AS salary, di.A10 AS urban FROM holder_district AS hd JOIN district AS di ON hd.district_id = di.district_id WHERE CAST(di.A4 AS SIGNED) > 100000), ranked AS (SELECT gender, name, inhabitants, COUNT(*) OVER (PARTITION BY gender) AS district_count, ROUND(AVG(salary) OVER (PARTITION BY gender), 2) AS avg_district_salary, ROUND(AVG(urban) OVER (PARTITION BY gender), 2) AS avg_urban_ratio, RANK() OVER (PARTITION BY gender ORDER BY inhabitants DESC) AS rnk FROM big) SELECT gender, district_count, name AS largest_district_name, inhabitants AS largest_district_inhabitants, avg_district_salary, avg_urban_ratio FROM ranked WHERE rnk = 1 ORDER BY CASE gender WHEN 'F' THEN 1 ELSE 2 END, name", "difficulty": "challenging"}
{"question_id": 214, "db_id": "financial", "question": "I'm preparing a partner-bank negotiation and want to focus on our big-city clients. Please tell me, for 1998 (1 January through 31 December 1998), where the money went from gold credit card clients' accounts held at branches in large districts. Specifically: for accounts whose owner has a gold credit card, and whose branch is located in a district with at least 250,000 inhabitants, look at their outgoing payments (debit transactions, type VYDAJ). I need a ranking of the recipient bank and counter-account pairs by the total amount paid. If two pairs tie for the largest total, list both. For each pair, give me: the recipient bank code, the recipient counter-account number, the number of outgoing payments, and the total amount paid.", "evidence": "Gold credit card means card type 'gold'; account owner means disposition type 'OWNER'; the counter-account is the partner account at another bank to which a payment is sent; the district is the one where the account's branch is located.", "SQL": "WITH gold_accounts AS (SELECT d.account_id FROM card AS c JOIN disp AS d ON c.disp_id = d.disp_id WHERE c.type = 'gold' AND d.type = 'OWNER'), outgoing AS (SELECT t.bank AS bank, t.account AS account, COUNT(*) AS n_payments, SUM(t.amount) AS total_amount FROM trans AS t JOIN account AS a ON a.account_id = t.account_id JOIN district AS di ON di.district_id = a.district_id WHERE t.account_id IN (SELECT account_id FROM gold_accounts) AND t.type = 'VYDAJ' AND t.date >= '1998-01-01' AND t.date <= '1998-12-31' AND t.account > 0 AND CAST(di.A4 AS SIGNED) >= 250000 GROUP BY t.bank, t.account) SELECT bank, account, n_payments, total_amount FROM outgoing WHERE total_amount = (SELECT MAX(total_amount) FROM outgoing) ORDER BY bank, account", "difficulty": "challenging"}
{"question_id": 215, "db_id": "financial", "question": "I'm reviewing what the money leaving our Pisek district branch's accounts is actually used for. What percentage of the total amount of outgoing payments that state a payment purpose went to household bill payments (SIPO)? Please give me a single percentage value, rounded to two decimals. Note this should be based only on payments that state a purpose, not all outgoing payments, and should consider the full transaction history.", "evidence": "VYDAJ marks a transaction where money leaves the account. SIPO is the code for household bill payments. A payment states its purpose through its transaction characterization.", "SQL": "SELECT ROUND(SUM(CASE WHEN t.k_symbol = 'SIPO' THEN t.amount ELSE 0 END) * 100.0 / SUM(t.amount), 2) AS sipo_percentage_of_purposed_outgoing_payments FROM trans AS t JOIN account AS a ON t.account_id = a.account_id JOIN district AS d ON a.district_id = d.district_id WHERE d.A2 = 'Pisek' AND t.type = 'VYDAJ' AND NOT t.k_symbol IS NULL AND TRIM(t.k_symbol) <> ''", "difficulty": "challenging"}
{"question_id": 216, "db_id": "financial", "question": "I'm planning a regional campaign for female customers who hold a credit card and a loan, and I need a demographic profile per region. For each region, please give me: the region, the average district salary of the districts where these female clients live, and the average 1996 district unemployment rate of those same districts – both averages rounded to 2 decimal places. I also want the name of the most populous district among those districts in each region, so I know where to focus local advertising. A few rules: count only female clients who own the account (disposition type OWNER) and who have at least one credit card and at least one loan on that account. 'Most populous' means the district with the largest number of inhabitants; if two tie, take the one whose name comes first alphabetically. One row per region, and include every region that has at least one such client – nothing else.", "evidence": "Disposition type OWNER means the client owns the account. Unemployment rate in 1996 is the district's unemployment rate for 1996; average salary is the district's average salary.", "SQL": "WITH cohort AS (SELECT DISTINCT c.district_id FROM client AS c JOIN disp AS d ON d.client_id = c.client_id AND d.type = 'OWNER' WHERE c.gender = 'F' AND d.disp_id IN (SELECT disp_id FROM card) AND d.account_id IN (SELECT account_id FROM loan)) SELECT di.A3 AS region, ROUND(AVG(di.A11), 2) AS average_district_salary, ROUND(AVG(di.A13), 2) AS average_unemployment_rate_1996, (SELECT di2.A2 FROM district AS di2 WHERE di2.district_id IN (SELECT district_id FROM cohort) AND di2.A3 = di.A3 ORDER BY CAST(di2.A4 AS SIGNED) DESC, di2.A2 LIMIT 1) AS most_populous_district FROM district AS di WHERE di.district_id IN (SELECT district_id FROM cohort) GROUP BY di.A3 ORDER BY di.A3", "difficulty": "challenging"}
{"question_id": 217, "db_id": "financial", "question": "I'm reviewing our presence in central Bohemia. Please tell me: the names of the three most populous districts of central Bohemia (largest by inhabitants), the number of crimes committed in 1996 in each of them, the average 1996 crime count across those three districts, the average 1996 crime count across all districts in the country, and the difference between the three-district average and the overall average (three-district average minus overall average). Rank districts by inhabitants, breaking ties by district name alphabetically (ignoring accents). Round all averages and the difference to 2 decimal places. The overall average should cover every district in the country, whether or not it has any accounts.", "evidence": "Central Bohemia is the region of the Czech Republic surrounding Prague.", "SQL": "WITH ranked AS (SELECT d.A2 AS district_name, CAST(d.A4 AS SIGNED) AS inhabitants, d.A16 AS crimes_1996 FROM district AS d WHERE d.A3 = 'central Bohemia' ORDER BY CAST(d.A4 AS SIGNED) DESC, d.A2 LIMIT 3) SELECT r.district_name, r.crimes_1996, ROUND((SELECT AVG(crimes_1996) FROM ranked), 2) AS avg_crimes_top3_1996, ROUND((SELECT AVG(A16) FROM district), 2) AS avg_crimes_all_districts_1996, ROUND((SELECT AVG(crimes_1996) FROM ranked) - (SELECT AVG(A16) FROM district), 2) AS difference FROM ranked AS r ORDER BY r.inhabitants DESC, r.district_name", "difficulty": "challenging"}
{"question_id": 218, "db_id": "financial", "question": "For planning region-targeted card offers, I need to look at the smallest markets behind each credit card type. For each credit card type (gold, classic and junior), which home district of the clients holding that type has the fewest inhabitants, and how many inhabitants does that district have? Please include all three card types, and if several districts tie for the fewest inhabitants, list them all.", "evidence": "By \"home district\" I mean the district a client lives in, and a district's inhabitants are its number of inhabitants.", "SQL": "WITH holder_districts AS (SELECT DISTINCT cd.type AS card_type, cl.district_id FROM card AS cd JOIN disp AS dp ON dp.disp_id = cd.disp_id JOIN client AS cl ON cl.client_id = dp.client_id), ranked AS (SELECT hd.card_type, ds.A2 AS district_name, CAST(ds.A4 AS SIGNED) AS inhabitants, RANK() OVER (PARTITION BY hd.card_type ORDER BY CAST(ds.A4 AS SIGNED)) AS rnk FROM holder_districts AS hd JOIN district AS ds ON ds.district_id = hd.district_id) SELECT card_type, district_name, inhabitants FROM ranked WHERE rnk = 1 ORDER BY card_type", "difficulty": "challenging"}
{"question_id": 219, "db_id": "financial", "question": "I'm reviewing how our branches performed in 1996, and I'd like a picture of the money standing in accounts opened during that year, across the region that Litomerice belongs to (the region as given in the district table's region field).\n\nFor each district in that region where at least one account was opened in 1996 (openings counted by account creation date within the calendar year 1996), please give me:\n- the district name,\n- the number of accounts opened in 1996,\n- the average end-of-1996 balance of those accounts,\nwith rows ordered by district name.\n\nAlso give me:\n- the region-wide average end-of-1996 balance, taken across all those accounts (not as the mean of the district averages),\n- the district with the highest average end-of-1996 balance; if two districts tie, name the one that comes first alphabetically.\n\nBy end-of-1996 balance I mean the balance after the account's last transaction dated on or before 1996-12-31; transactions dated 1997 or later don't count, and if several transactions fall on that last date, the one with the highest transaction id is the one that matters. Please round all averages to two decimals.", "evidence": "Balance means the balance after a transaction.", "SQL": "WITH region AS (SELECT A3 AS r FROM district WHERE A2 = 'Litomerice'), op AS (SELECT a.account_id, a.district_id FROM account AS a JOIN district AS d ON d.district_id = a.district_id WHERE d.A3 = (SELECT r FROM region) AND a.date >= '1996-01-01' AND a.date < '1997-01-01'), lastd AS (SELECT t.account_id, MAX(t.date) AS md FROM trans AS t WHERE t.date <= '1996-12-31' AND t.account_id IN (SELECT account_id FROM op) GROUP BY t.account_id), lastt AS (SELECT l.account_id, MAX(t.trans_id) AS mt FROM lastd AS l JOIN trans AS t ON t.account_id = l.account_id AND t.date = l.md GROUP BY l.account_id), eb AS (SELECT x.account_id, tr.balance AS bal FROM lastt AS x JOIN trans AS tr ON tr.trans_id = x.mt), rd AS (SELECT d.A2 AS district_name, COUNT(*) AS accounts_opened_in_1996, AVG(e.bal) AS raw_avg FROM op AS o JOIN district AS d ON d.district_id = o.district_id JOIN eb AS e ON e.account_id = o.account_id GROUP BY d.district_id, d.A2) SELECT rd.district_name, rd.accounts_opened_in_1996, ROUND(rd.raw_avg, 2) AS average_end_of_1996_balance, (SELECT ROUND(AVG(bal), 2) FROM eb) AS region_average_end_of_1996_balance, (SELECT district_name FROM rd ORDER BY raw_avg DESC, district_name ASC LIMIT 1) AS district_with_highest_average_end_of_1996_balance FROM rd ORDER BY rd.district_name", "difficulty": "challenging"}
{"question_id": 220, "db_id": "financial", "question": "I want to check whether our biggest short-term loans cluster in populous branch districts and how well-off those areas are. Looking at 24-month loans on accounts with weekly statement issuance, take the ten largest loans ranked by approved amount from highest to lowest — if two loans have the same amount, the one with the smaller loan id ranks first, and ranking continues consecutively after a tie. The district of a loan is the district where the branch managing the loan account is located. Among the districts those ten loans come from, I need: the district with the most inhabitants (if two districts tie on inhabitants, the one with the smaller district id counts as more populous), that district's number of inhabitants, and the average salary across those districts rounded to two decimals.", "evidence": "Weekly statement issuance means account issuance frequency 'POPLATEK TYDNE'. A district's inhabitants are its number of inhabitants, and its average salary is its average yearly salary.", "SQL": "WITH ranked AS (SELECT l.loan_id, a.district_id, ROW_NUMBER() OVER (ORDER BY l.amount DESC, l.loan_id ASC) AS rn FROM loan AS l JOIN account AS a ON a.account_id = l.account_id WHERE l.duration = 24 AND a.frequency = 'POPLATEK TYDNE'), top10 AS (SELECT * FROM ranked WHERE rn <= 10), districts AS (SELECT d.district_id, d.A2 AS district_name, CAST(d.A4 AS SIGNED) AS inhabitants, d.A11 AS avg_salary FROM district AS d JOIN (SELECT DISTINCT district_id FROM top10) AS t ON t.district_id = d.district_id) SELECT (SELECT district_name FROM districts ORDER BY inhabitants DESC, district_id ASC LIMIT 1) AS most_populous_district, (SELECT inhabitants FROM districts ORDER BY inhabitants DESC, district_id ASC LIMIT 1) AS inhabitants, (SELECT ROUND(AVG(avg_salary), 2) FROM districts) AS avg_district_salary", "difficulty": "challenging"}
{"question_id": 221, "db_id": "financial", "question": "For every district with at least 100,000 inhabitants that has withdrawal transactions, can you show me the district name, region, population, total amount withdrawn in the district, withdrawals per inhabitant (rounded to 2 decimals), the district's rank by withdrawals per inhabitant (highest first), and the average standing-order debit per account held in the district (rounded to 2 decimals)? I want to compare withdrawal pressure and the standing-order burden side by side across our major districts. Please rank all qualifying districts, not just the top few, using competition ranking so tied districts share a rank and the next rank is skipped (e.g. 1, 1, 3). The whole transaction history on record is in scope. For the average standing-order debit per account, every account held in the district counts, including ones with no standing orders – those simply bring no debits.", "evidence": "Withdrawal transactions are those recorded with type = 'VYDAJ'; a standing order is a recurring payment order that debits the account.", "SQL": "WITH wd AS (SELECT a.district_id, SUM(t.amount) AS total FROM trans AS t JOIN account AS a ON t.account_id = a.account_id WHERE t.type = 'VYDAJ' GROUP BY a.district_id), acct AS (SELECT district_id, COUNT(*) AS n_accounts FROM account GROUP BY district_id), so AS (SELECT a.district_id, SUM(o.amount) AS so_total FROM account AS a LEFT JOIN `order` AS o ON o.account_id = a.account_id GROUP BY a.district_id) SELECT d.A2 AS district_name, d.A3 AS region, CAST(d.A4 AS SIGNED) AS population, wd.total AS total_withdrawn, ROUND(wd.total / CAST(d.A4 AS FLOAT), 2) AS withdrawals_per_inhabitant, RANK() OVER (ORDER BY wd.total / CAST(d.A4 AS FLOAT) DESC) AS per_inhabitant_rank, ROUND(so.so_total * 1.0 / acct.n_accounts, 2) AS avg_standing_order_debit_per_account FROM district AS d JOIN wd ON wd.district_id = d.district_id JOIN acct ON acct.district_id = d.district_id JOIN so ON so.district_id = d.district_id WHERE CAST(d.A4 AS SIGNED) >= 100000 ORDER BY per_inhabitant_rank, district_name", "difficulty": "challenging"}
{"question_id": 222, "db_id": "financial", "question": "I'm preparing a client review for client 3541. For each account this client can access, I need one row with: the account id, the date the account was opened, its frequency, the name and region of the district where the account is held, whether that district is the client's home district (Yes/No), that district's average salary, the loan repayment status (none if there's no loan), the loan amount (0 if no loan), the number of transactions over the account's whole recorded history, total income, total expense, net balance, the number of clients whose home district lies in that region, the name of the most populous district in that region, that district's number of inhabitants, and the account district's population rank within its region. Order the rows by number of transactions, most first, with ties broken by ascending account id. The client's home district is the district recorded for the client, and population means number of inhabitants. For ranks, the most populous district is rank 1; districts with equal population share a rank and the next rank skips.", "evidence": "PRIJEM = incoming transaction; VYDAJ = outgoing transaction; net balance = total income - total expense", "SQL": "WITH acct AS (SELECT d.account_id, a.date AS opened, a.frequency AS freq, a.district_id AS branch_district, c.district_id AS home_district FROM client AS c JOIN disp AS d ON d.client_id = c.client_id JOIN account AS a ON a.account_id = d.account_id WHERE c.client_id = 3541), stats AS (SELECT ac.account_id, ac.opened, ac.freq, ac.branch_district, ac.home_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 FROM acct AS ac LEFT JOIN trans AS t ON t.account_id = ac.account_id GROUP BY ac.account_id, ac.opened, ac.freq, ac.branch_district, ac.home_district), ranked AS (SELECT district_id, A3 AS region, A2 AS district_name, CAST(A4 AS SIGNED) AS inhabitants, RANK() OVER (PARTITION BY A3 ORDER BY CAST(A4 AS SIGNED) DESC) AS pop_rank FROM district) SELECT s.account_id, s.opened AS opening_date, s.freq AS frequency, bd.A2 AS district_where_held, bd.A3 AS region, CASE WHEN bd.district_id = s.home_district THEN 'Yes' ELSE 'No' END AS is_client_home_district, bd.A11 AS district_avg_salary, COALESCE(l.status, 'none') AS loan_status, COALESCE(l.amount, 0) AS loan_amount, s.transaction_count, s.total_income, s.total_expense, s.total_income - s.total_expense AS net_balance, (SELECT COUNT(DISTINCT c2.client_id) FROM client AS c2 JOIN district AS d2 ON d2.district_id = c2.district_id WHERE d2.A3 = bd.A3) AS clients_home_district_in_region, mp.district_name AS most_populous_district, mp.inhabitants AS most_populous_inhabitants, rk.pop_rank AS population_rank_in_region FROM stats AS s JOIN district AS bd ON bd.district_id = s.branch_district JOIN ranked AS rk ON rk.district_id = bd.district_id JOIN ranked AS mp ON mp.region = bd.A3 AND mp.pop_rank = 1 LEFT JOIN loan AS l ON l.account_id = s.account_id ORDER BY s.transaction_count DESC, s.account_id ASC", "difficulty": "challenging"}
{"question_id": 223, "db_id": "financial", "question": "I'm doing a lending review by account-opening year for my region. For accounts opened in the central Bohemia region from 1 January 1996 onward, broken down by the calendar year of the account creation date (as a text string like '1996', not an integer), I need: the number of accounts opened that year in the region, the total amount lent on those accounts, and the average across the districts of the amount lent per account opened in that district, rounded to two decimals. An account with no loan counts as having lent nothing.", "evidence": "Central Bohemia is the region value recorded for districts in the region data; the amount lent on an account is the total of the loans granted on that account.", "SQL": "WITH cba AS (SELECT a.account_id, a.district_id, DATE_FORMAT(a.date, '%Y') AS y FROM account AS a INNER JOIN district AS d ON a.district_id = d.district_id WHERE d.A3 = 'central Bohemia' AND a.date >= '1996-01-01'), branch AS (SELECT cba.y, cba.district_id, SUM(COALESCE(l.amount, 0)) * 1.0 / COUNT(DISTINCT cba.account_id) AS lent_per_account FROM cba LEFT JOIN loan AS l ON l.account_id = cba.account_id GROUP BY cba.y, cba.district_id) SELECT yt.y AS opening_year, yt.accounts_opened, yl.total_lent, ROUND(b.avg_lent, 2) AS avg_amount_lent_per_account FROM (SELECT y, COUNT(DISTINCT account_id) AS accounts_opened FROM cba GROUP BY y) AS yt INNER JOIN (SELECT y, SUM(l.amount) AS total_lent FROM cba LEFT JOIN loan AS l ON l.account_id = cba.account_id GROUP BY y) AS yl ON yl.y = yt.y INNER JOIN (SELECT y, AVG(lent_per_account) AS avg_lent FROM branch GROUP BY y) AS b ON b.y = yt.y ORDER BY yt.y", "difficulty": "challenging"}
{"question_id": 224, "db_id": "financial", "question": "For a regional risk review, I need to look at our largest 24-month loans. Please find the ten loans with the largest approved amount among loans with a 24-month duration on accounts that have weekly statement issuance. For each of these ten loans, give me: the district of the branch servicing the account, the approved amount, the approval date, and the account balance at the end of the day the loan was approved. Two rules: if two loans have the same approved amount, the one approved earlier counts as larger; and if several transactions share that last day, the one with the higher transaction id counts as the later one. List the results from the largest approved amount down.", "evidence": "Weekly statement issuance means statement frequency is 'POPLATEK TYDNE'; loan duration is stated in months.", "SQL": "WITH top_loans AS (SELECT l.loan_id, l.account_id, l.amount, l.date AS loan_date, d.A2 AS district_name FROM loan AS l JOIN account AS a ON a.account_id = l.account_id JOIN district AS d ON d.district_id = a.district_id WHERE l.duration = 24 AND a.frequency = 'POPLATEK TYDNE' ORDER BY l.amount DESC, l.date ASC, l.loan_id ASC LIMIT 10) SELECT district_name, amount AS approved_amount, loan_date AS approval_date, (SELECT t.balance FROM trans AS t WHERE t.account_id = top_loans.account_id AND t.date <= top_loans.loan_date ORDER BY t.date DESC, t.trans_id DESC LIMIT 1) AS balance_at_approval FROM top_loans ORDER BY approved_amount DESC", "difficulty": "challenging"}
{"question_id": 225, "db_id": "financial", "question": "I'm putting together a review of our first credit card wave and need a profile of every client who was issued a credit card in 1994 (issue date falling in calendar year 1994). For each such client, please include: client id, gender, birth date, card type, age at card issue (the card's issue year minus the client's birth year), number of loans on their account, total amount borrowed, borrower classification, district name, district average salary, and their age rank within gender. Use these classifications: Young borrower if there's at least one loan on the account and age at card issue is under 30; Mature borrower if there's at least one loan and age at card issue is 30 or more; otherwise Non-borrower. The age rank within gender should be a standard competition rank - equal ages share a rank and the next rank is skipped (e.g. 1, 1, 3). Order the rows by client id.", "evidence": "", "SQL": "WITH cohort AS (SELECT c.client_id, c.gender, c.birth_date, cd.type AS card_type, (CAST(DATE_FORMAT(cd.issued, '%Y') AS SIGNED) - CAST(DATE_FORMAT(c.birth_date, '%Y') AS SIGNED)) AS age_at_issue, d.account_id, di.A2 AS district_name, di.A11 AS district_avg_salary FROM card AS cd JOIN disp AS d ON cd.disp_id = d.disp_id JOIN client AS c ON d.client_id = c.client_id JOIN district AS di ON c.district_id = di.district_id WHERE DATE_FORMAT(cd.issued, '%Y') = '1994') SELECT co.client_id, co.gender, co.birth_date, co.card_type, co.age_at_issue, COUNT(l.loan_id) AS loan_count, COALESCE(SUM(l.amount), 0) AS total_borrowed, CASE WHEN COUNT(l.loan_id) > 0 AND co.age_at_issue < 30 THEN 'Young borrower' WHEN COUNT(l.loan_id) > 0 THEN 'Mature borrower' ELSE 'Non-borrower' END AS borrower_category, co.district_name, co.district_avg_salary, RANK() OVER (PARTITION BY co.gender ORDER BY co.age_at_issue) AS age_rank_within_gender FROM cohort AS co LEFT JOIN loan AS l ON co.account_id = l.account_id GROUP BY co.client_id, co.gender, co.birth_date, co.card_type, co.age_at_issue, co.district_name, co.district_avg_salary ORDER BY co.client_id", "difficulty": "challenging"}
{"question_id": 226, "db_id": "financial", "question": "I'm reviewing branches in the north Moravia region ahead of a client meeting. For each branch there, how many transactions dated on or before 14 October 1998 have no characterization recorded? A branch is the district the account belongs to, and the count should cover all of the branch's accounts' transactions. Please list only the top three branches by this count, with the branch name and its count, ranked first to third. If any branches tie on the count, order them alphabetically by branch name and keep three rows after that ordering.", "evidence": "A transaction with no characterization recorded means the bank did not tag it with any characterization.", "SQL": "WITH branch_counts AS (SELECT d.A2 AS branch_name, COUNT(*) AS unstated_transactions FROM trans AS t JOIN account AS a ON t.account_id = a.account_id JOIN district AS d ON a.district_id = d.district_id WHERE d.A3 = 'north Moravia' AND t.date <= '1998-10-14' AND (t.k_symbol IS NULL OR TRIM(t.k_symbol) = '') GROUP BY d.A2) SELECT branch_name, unstated_transactions FROM branch_counts ORDER BY unstated_transactions DESC, branch_name ASC LIMIT 3", "difficulty": "challenging"}
{"question_id": 227, "db_id": "financial", "question": "The loan of 98832 approved on January 3rd, 1996 has one applicant account. For that account, list every counterparty it had paid before January 3rd, 1996. A counterparty means a specific account number at a specific bank, so give me one row per bank code and account number combination. For each counterparty I need the bank code, the account number, the number of outgoing payments made to them, and the total amount paid to them. Count only outgoing payments (VYDAJ, i.e. debits) made before January 3rd, 1996, and sort the counterparties by total amount paid, largest first.", "evidence": "VYDAJ denotes an outgoing payment (debit); PRIJEM denotes an incoming payment (credit).", "SQL": "SELECT t.bank AS bank_code, t.account AS counterparty_account, COUNT(*) AS payment_count, SUM(t.amount) AS total_paid FROM trans AS t WHERE t.account_id = (SELECT l.account_id FROM loan AS l WHERE l.date = '1996-01-03' AND l.amount = 98832) AND t.type = 'VYDAJ' AND t.date < '1996-01-03' AND t.account > 0 GROUP BY t.bank, t.account ORDER BY total_paid DESC", "difficulty": "challenging"}
{"question_id": 228, "db_id": "financial", "question": "For the year-end review of my branch at location 1: how many accounts that were on the branch's books as of 31 December 1995 hold an active loan contract? I want a single integer, nothing else. An account counts only if it belonged to the branch on that date, and only contracts that are still active by their repayment status count - statuses A and B are finished contracts and shouldn't be included.", "evidence": "Loan status C means an active contract in good standing; loan status D means an active contract with the client in debt. Both are active contracts.", "SQL": "SELECT COUNT(DISTINCT a.account_id) AS account_count FROM account AS a JOIN loan AS l ON l.account_id = a.account_id WHERE a.district_id = 1 AND a.date <= '1995-12-31' AND l.status IN ('C', 'D')", "difficulty": "challenging"}
{"question_id": 229, "db_id": "financial", "question": "I'm closing the 1998 books for client 2823's account and need to reconcile the interest. What was the net interest on that account for calendar year 1998 (1 January through 31 December 1998) – interest credited minus penalty interest charged, with penalty interest entering as negative – as a single exact amount in CZK, not rounded? Please include everything credited or charged over the year; the client's account is one account, regardless of the disposition it carries.", "evidence": "'UROK' is the bank's code for interest credited to an account; penalty (sanction) interest charged to an account uses the bank's sanction-interest code, which is built on the same interest code.", "SQL": "SELECT SUM(CASE WHEN t.k_symbol = 'UROK' THEN t.amount ELSE -t.amount END) AS net_interest FROM trans AS t WHERE t.date BETWEEN '1998-01-01' AND '1998-12-31' AND t.k_symbol LIKE '%UROK%' AND EXISTS(SELECT 1 FROM disp AS d WHERE d.account_id = t.account_id AND d.client_id = 2823)", "difficulty": "challenging"}
{"question_id": 230, "db_id": "financial", "question": "I need to profile our three largest loans held by female clients. Please report for each of these loans: the client id, loan amount, duration in months, total payments, interest paid, loan status, the district and region of the branch where the loan's account is held, the account's transaction count and total deposits, an income category, the number of loans the bank has granted in that region, the average of the average salaries of that region's districts, and the client's completed age on 2026-10-09. A few notes: the three largest loans are the three highest approved loan amounts, and if amounts tie, include all tied loans. Total payments is the monthly payment times the duration, and interest paid is total payments minus the approved amount; round money figures to two decimals. The income category is High Income if total deposits exceed twice the loan amount, Medium Income if they exceed the loan amount, and Low Income otherwise. Loans in a region counts every loan the bank has granted in that region for all clients, not only female clients. The region's average salary is the average of the average salaries of the districts in that region, rounded to two decimals. For the age, use the completed age on 2026-10-09, subtracting one if the birthday hasn't occurred by that date.", "evidence": "Female means client gender = 'F'. Deposits are transactions recorded as PRIJEM (credits to the account). District average salary is the district's average salary figure.", "SQL": "WITH female_loans AS (SELECT c.client_id, c.birth_date, d.account_id, l.loan_id, l.amount, l.duration, l.payments, l.status, a.district_id, RANK() OVER (ORDER BY l.amount DESC) AS rnk FROM client AS c JOIN disp AS d ON c.client_id = d.client_id AND d.type = 'OWNER' JOIN loan AS l ON d.account_id = l.account_id JOIN account AS a ON l.account_id = a.account_id WHERE c.gender = 'F'), region_loans AS (SELECT da.A3 AS region, COUNT(*) AS loans_in_region FROM loan AS l JOIN account AS a ON l.account_id = a.account_id JOIN district AS da ON a.district_id = da.district_id GROUP BY da.A3), region_salary AS (SELECT A3 AS region, ROUND(AVG(A11), 2) AS avg_district_salary FROM district GROUP BY A3), acct_trans AS (SELECT account_id, COUNT(*) AS transaction_count, SUM(CASE WHEN type = 'PRIJEM' THEN amount ELSE 0 END) AS total_credits FROM trans GROUP BY account_id) SELECT fl.client_id, fl.amount AS loan_amount, fl.duration AS loan_duration_months, ROUND(fl.payments * fl.duration, 2) AS total_payments, ROUND(fl.payments * fl.duration - fl.amount, 2) AS interest_paid, fl.status AS loan_status, di.A2 AS branch_district, di.A3 AS region, at.transaction_count, at.total_credits AS total_deposits, CASE WHEN at.total_credits > fl.amount * 2 THEN 'High Income' WHEN at.total_credits > fl.amount THEN 'Medium Income' ELSE 'Low Income' END AS income_category, rl.loans_in_region, rs.avg_district_salary AS region_avg_district_salary, DATE_FORMAT('2026-10-09', '%Y') - DATE_FORMAT(fl.birth_date, '%Y') - CASE WHEN DATE_FORMAT('2026-10-09', '%m-%d') < DATE_FORMAT(fl.birth_date, '%m-%d') THEN 1 ELSE 0 END AS client_age FROM female_loans AS fl JOIN district AS di ON fl.district_id = di.district_id JOIN region_loans AS rl ON di.A3 = rl.region JOIN region_salary AS rs ON di.A3 = rs.region LEFT JOIN acct_trans AS at ON fl.account_id = at.account_id WHERE fl.rnk <= 3 ORDER BY fl.amount DESC", "difficulty": "challenging"}
{"question_id": 231, "db_id": "financial", "question": "I need to find out where our pre-1997 long-term mortgage exposure is concentrated geographically. Long-term means a loan duration of more than 24 months, and \"opened before 1997\" should exclude anything opened during 1997. Please tell me: for each region, which districts have at least one such account, and give me the region whose qualifying districts have the largest combined number of inhabitants. Along with the region's name, I want the number of those districts in it, their combined population, and the total number of those accounts in the region. If two regions tie on combined population, pick the one whose name comes first alphabetically.", "evidence": "", "SQL": "WITH cohort AS (SELECT l.account_id, a.district_id FROM loan AS l JOIN account AS a ON l.account_id = a.account_id WHERE l.duration > 24 AND DATE_FORMAT(a.date, '%Y') < '1997'), region_districts AS (SELECT DISTINCT d.district_id, d.A3 AS region, CAST(d.A4 AS SIGNED) AS population FROM district AS d JOIN cohort AS c ON d.district_id = c.district_id) SELECT r.region, COUNT(*) AS num_districts, SUM(r.population) AS total_population, (SELECT COUNT(*) FROM cohort AS c JOIN region_districts AS x ON c.district_id = x.district_id WHERE x.region = r.region) AS num_accounts FROM region_districts AS r GROUP BY r.region ORDER BY total_population DESC, r.region ASC LIMIT 1", "difficulty": "challenging"}
{"question_id": 232, "db_id": "financial", "question": "I'm putting together a market-coverage report on how our 1997 rollout of monthly-statement accounts reached large urban districts. For districts with at least 100,000 inhabitants that had at least one monthly-statement account opened during calendar year 1997, please give me: the total number of monthly-statement accounts opened in those districts during 1997, how many districts are involved, and the average salary across these qualifying districts rounded to two decimals.", "evidence": "Monthly statement issuance means the account's statement frequency is 'POPLATEK MESICNE'.", "SQL": "WITH qualifying_districts AS (SELECT d.district_id, d.A11 FROM district AS d WHERE CAST(d.A4 AS SIGNED) >= 100000 AND EXISTS(SELECT 1 FROM account AS a WHERE a.district_id = d.district_id AND a.frequency = 'POPLATEK MESICNE' AND a.date BETWEEN '1997-01-01' AND '1997-12-31')) SELECT (SELECT COUNT(*) FROM account AS a JOIN qualifying_districts AS q ON a.district_id = q.district_id WHERE a.frequency = 'POPLATEK MESICNE' AND a.date BETWEEN '1997-01-01' AND '1997-12-31') AS monthly_accounts_opened_1997, (SELECT COUNT(*) FROM qualifying_districts) AS district_count, (SELECT ROUND(AVG(A11), 2) FROM qualifying_districts) AS avg_district_salary", "difficulty": "challenging"}
{"question_id": 233, "db_id": "financial", "question": "I'd like to review the breadth of each gold-card account's external payment network. For every account that has a gold credit card, could you list: the account id, the district name and region of the branch, the total amount received, the total amount withdrawn, the number of loans taken, and the number of accounts at other banks that money was transferred to or received from? Then rank the accounts by that number of external counterparties. A few things to keep in mind: if accounts tie on the number, they share a rank and the next rank is not skipped; accounts with no external counterparty transfers should still be included and count as zero; and the totals and counts should cover the full recorded period.", "evidence": "An external counterparty account is an account at another bank that money was transferred to or received from. Amount received refers to credit transactions, which carry transaction type PRIJEM. Amount withdrawn refers to debit transactions, which carry transaction type VYDAJ.", "SQL": "WITH gold_accounts AS (SELECT d.account_id FROM disp AS d JOIN card AS c ON c.disp_id = d.disp_id WHERE c.type = 'gold' GROUP BY d.account_id), trans_stats AS (SELECT account_id, SUM(CASE WHEN type = 'PRIJEM' THEN amount ELSE 0 END) AS total_received, SUM(CASE WHEN type = 'VYDAJ' THEN amount ELSE 0 END) AS total_withdrawn, COUNT(DISTINCT CASE WHEN NOT bank IS NULL THEN account END) AS external_counterparty_accounts FROM trans GROUP BY account_id), loan_stats AS (SELECT account_id, COUNT(loan_id) AS loan_count FROM loan GROUP BY account_id) SELECT g.account_id, di.A2 AS district, di.A3 AS region, COALESCE(t.total_received, 0) AS total_received, COALESCE(t.total_withdrawn, 0) AS total_withdrawn, COALESCE(l.loan_count, 0) AS loan_count, COALESCE(t.external_counterparty_accounts, 0) AS external_counterparty_accounts, DENSE_RANK() OVER (ORDER BY COALESCE(t.external_counterparty_accounts, 0) DESC) AS counterparty_rank FROM gold_accounts AS g JOIN account AS a ON a.account_id = g.account_id JOIN district AS di ON di.district_id = a.district_id LEFT JOIN trans_stats AS t ON t.account_id = g.account_id LEFT JOIN loan_stats AS l ON l.account_id = g.account_id ORDER BY counterparty_rank, g.account_id", "difficulty": "challenging"}
{"question_id": 234, "db_id": "financial", "question": "I'm preparing our branch's annual customer review. For every account held at the Tabor branch as of 31 December 1996, I need a one-row profile per account, ordered among tied ranks by ascending account id, showing: the account id; the date the account was opened; the owner's gender and their age at 31 December 1996 in whole completed years; the number of credit cards issued to the account by 31 December 1996 (0 if none); the number of loans approved to the account by 31 December 1996 (0 if none); a loan standing label; the number of transactions on the account during 1997; the total money into the account during 1997; the total money out of the account during 1997; the peak balance reached on the account during 1997 (0 if none); and the account's rank by 1997 peak balance, highest first, with ties sharing a rank and the next rank skipped (e.g. 1, 1, 3). All 'as of' figures are taken at 31 December 1996; activity figures cover the calendar year 1997. A card or loan counts as held if it was issued or approved on or before 31 December 1996. The loan standing label is: 'no loan' if the account had no loans approved by 31 December 1996; otherwise 'defaulted' if any of its loans has repayment status B; otherwise 'repaying' if any has status C or D; otherwise 'paid off'. Money in is the sum of credit transaction amounts; money out is the sum of debit and cash-withdrawal transaction amounts. The account owner is the person with the 'OWNER' disposition on the account; other dispositions are just additional users. Nothing beyond these fields, please.", "evidence": "Loan repayment status codes: A means the contract finished and was paid off, B means the loan was not repaid (default), C means the loan is running and being repaid, D means the loan is running and the client is in debt on it. Transaction types: a credit transaction brings money into the account, a debit transaction takes money out, and a cash withdrawal takes money out in cash.", "SQL": "WITH cohort AS (SELECT a.account_id, a.date AS open_date FROM account AS a JOIN district AS d ON d.district_id = a.district_id WHERE d.A2 = 'Tabor' AND a.date <= '1996-12-31'), own AS (SELECT co.account_id, co.open_date, c.gender, c.birth_date FROM cohort AS co JOIN disp AS dp ON dp.account_id = co.account_id AND dp.type = 'OWNER' JOIN client AS c ON c.client_id = dp.client_id), cards96 AS (SELECT dp.account_id, COUNT(cd.card_id) AS n_cards FROM disp AS dp JOIN card AS cd ON cd.disp_id = dp.disp_id WHERE cd.issued <= '1996-12-31' GROUP BY dp.account_id), loans96 AS (SELECT l.account_id, COUNT(*) AS n_loans, SUM(CASE WHEN l.status = 'B' THEN 1 ELSE 0 END) AS n_bad, SUM(CASE WHEN l.status IN ('C', 'D') THEN 1 ELSE 0 END) AS n_run FROM loan AS l WHERE l.date <= '1996-12-31' GROUP BY l.account_id), t1997 AS (SELECT t.account_id, COUNT(*) AS n_trans, SUM(CASE WHEN t.type = 'PRIJEM' THEN t.amount ELSE 0 END) AS money_in, SUM(CASE WHEN t.type <> 'PRIJEM' THEN t.amount ELSE 0 END) AS money_out, MAX(t.balance) AS max_bal FROM trans AS t WHERE t.date BETWEEN '1997-01-01' AND '1997-12-31' GROUP BY t.account_id) SELECT o.account_id, o.open_date AS date_opened, o.gender AS owner_gender, 1996 - CAST(DATE_FORMAT(o.birth_date, '%Y') AS SIGNED) AS owner_age_at_end_1996, COALESCE(c.n_cards, 0) AS cards_by_end_1996, COALESCE(l.n_loans, 0) AS loans_by_end_1996, CASE WHEN COALESCE(l.n_loans, 0) = 0 THEN 'no loan' WHEN l.n_bad > 0 THEN 'defaulted' WHEN l.n_run > 0 THEN 'repaying' ELSE 'paid off' END AS loan_standing, COALESCE(t.n_trans, 0) AS trans_1997_count, COALESCE(t.money_in, 0) AS money_in_1997, COALESCE(t.money_out, 0) AS money_out_1997, COALESCE(t.max_bal, 0) AS max_balance_1997, RANK() OVER (ORDER BY COALESCE(t.max_bal, 0) DESC) AS balance_rank FROM own AS o LEFT JOIN cards96 AS c ON c.account_id = o.account_id LEFT JOIN loans96 AS l ON l.account_id = o.account_id LEFT JOIN t1997 AS t ON t.account_id = o.account_id ORDER BY balance_rank, o.account_id", "difficulty": "challenging"}
{"question_id": 235, "db_id": "financial", "question": "I'd like a district-by-district picture of where our classic-card-holding account owners send money outside the bank. For every district, give me: the district name, the number of clients who own an account and hold a classic credit card, the number of external accounts at other banks those clients paid through outgoing payments, and the total amount of those outgoing payments. A district means the district of the branch where the owned account is held — not the client's home district — and each client and every outgoing payment from the account they own counts toward that account's branch district. Include every district, even ones with no such clients or no such outgoing payments (show zeros). Use the whole recorded payment history. Order by total amount paid from highest to lowest, and alphabetically by district name when totals tie. Don't round the totals.", "evidence": "An account owner is the client recorded as 'OWNER' on the account. An outgoing payment is a transaction recorded with type 'VYDAJ' (money paid out of the account). An external account is an account held at another bank to which the account holder sends money; the receiving bank together with the receiving account number identifies it.", "SQL": "WITH holders AS (SELECT dp.client_id, dp.account_id, a.district_id FROM card AS c JOIN disp AS dp ON dp.disp_id = c.disp_id AND dp.type = 'OWNER' JOIN account AS a ON a.account_id = dp.account_id WHERE c.type = 'classic') SELECT d.A2 AS district, COUNT(DISTINCT h.client_id) AS classic_card_holders, COUNT(DISTINCT t.account) AS external_accounts_paid, COALESCE(SUM(t.amount), 0) AS total_amount_paid FROM district AS d LEFT JOIN holders AS h ON h.district_id = d.district_id LEFT JOIN trans AS t ON t.account_id = h.account_id AND t.type = 'VYDAJ' AND t.account > 0 GROUP BY d.district_id, d.A2 ORDER BY total_amount_paid DESC, district ASC", "difficulty": "challenging"}
{"question_id": 236, "db_id": "financial", "question": "I'm planning services for our older female customers. For the clients who are female and were born before 1930, please look at the branches that hold their accounts, and then the districts those branches are located in. What is the average salary of those districts? Round the result to 2 decimal places. Note: born before 1930 means calendar birth dates before 1 January 1930.", "evidence": "Average salary refers to the district attribute describing average salary.", "SQL": "SELECT ROUND(AVG(d.A11), 2) AS average_salary FROM district AS d WHERE d.district_id IN (SELECT a.district_id FROM account AS a JOIN disp AS x ON x.account_id = a.account_id JOIN client AS c ON c.client_id = x.client_id WHERE c.gender = 'F' AND c.birth_date < '1930-01-01')", "difficulty": "challenging"}
{"question_id": 237, "db_id": "financial", "question": "I'm preparing a campaign for senior female clients and want a sense of the economic profile of their home districts. Could you tell me the average of the average salaries of the districts where our female clients born before 1950 live? Please give me just that single figure, rounded to two decimal places.", "evidence": "Average salary means the average yearly salary recorded for a district, in CZK.", "SQL": "SELECT ROUND(AVG(T1.A11), 2) AS average_salary FROM district AS T1 WHERE T1.district_id IN (SELECT T2.district_id FROM client AS T2 WHERE T2.gender = 'F' AND DATE_FORMAT(T2.birth_date, '%Y') < '1950')", "difficulty": "challenging"}
{"question_id": 238, "db_id": "financial", "question": "I want to know whether our small, healthy loans are concentrated in richer or poorer districts before we decide where to grow the small-loan business. Please give me one number: the average district salary, rounded to two decimals, across the districts where the accounts holding these loans are located. The cohort is loans with an approved amount below 100,000 that are still running without issues.", "evidence": "Loan status C means the contract is running with no problems so far. District average salary is the average salary recorded for a district.", "SQL": "SELECT ROUND(AVG(d.A11), 2) AS average_district_salary FROM district AS d WHERE d.district_id IN (SELECT a.district_id FROM account AS a WHERE a.account_id IN (SELECT l.account_id FROM loan AS l WHERE l.amount < 100000 AND l.status = 'C'))", "difficulty": "challenging"}
{"question_id": 239, "db_id": "financial", "question": "I'm studying how client age relates to branch location. For each of two client cohorts, I want the cohort label and the average salary across the districts where the branches holding that cohort's accounts are located, rounded to the nearest whole number. A client's cohort is based on birth date: born 1980 or later is the young cohort, born 1919 or earlier is the old cohort. Note the district of an account is the district of its branch, not the client's home district. Give me one row per cohort, young cohort first. Nothing else.", "evidence": "", "SQL": "WITH cohort_districts AS (SELECT a.district_id, CASE WHEN c.birth_date >= '1980-01-01' THEN 'young' ELSE 'old' END AS cohort FROM client AS c JOIN disp AS d ON d.client_id = c.client_id JOIN account AS a ON a.account_id = d.account_id WHERE c.birth_date >= '1980-01-01' OR c.birth_date <= '1919-12-31' GROUP BY a.district_id, CASE WHEN c.birth_date >= '1980-01-01' THEN 'young' ELSE 'old' END) SELECT cohort, CAST(ROUND(AVG(x.A11)) AS SIGNED) AS avg_salary FROM cohort_districts AS cd JOIN district AS x ON x.district_id = cd.district_id GROUP BY cohort ORDER BY CASE cohort WHEN 'young' THEN 1 ELSE 2 END", "difficulty": "challenging"}
{"question_id": 240, "db_id": "formula_1", "question": "By what percentage was Paul di Resta's fastest-lap speed in race 853 higher than in race 854? Use the speed in race 854 as the baseline and round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * (MAX(CASE WHEN r.raceId = 853 THEN CAST(r.fastestLapSpeed AS DECIMAL(12, 4)) END) - MAX(CASE WHEN r.raceId = 854 THEN CAST(r.fastestLapSpeed AS DECIMAL(12, 4)) END)) / NULLIF(MAX(CASE WHEN r.raceId = 854 THEN CAST(r.fastestLapSpeed AS DECIMAL(12, 4)) END), 0), 2) FROM drivers AS d JOIN results AS r ON r.driverId = d.driverId WHERE d.forename = 'Paul' AND d.surname = 'di Resta' AND r.raceId IN (853, 854)", "difficulty": "challenging"}
{"question_id": 241, "db_id": "formula_1", "question": "What percentage of Lewis Hamilton's recorded race entries from 2010 onward were not victories? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN x.positionOrder <> 1 THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM results AS x JOIN drivers AS d ON d.driverId = x.driverId JOIN races AS r ON r.raceId = x.raceId WHERE d.forename = 'Lewis' AND d.surname = 'Hamilton' AND r.year >= 2010", "difficulty": "challenging"}
{"question_id": 242, "db_id": "formula_1", "question": "Which driver won the most recorded races? Give their first name, last name, nationality, and highest recorded driver-standings points total.", "evidence": "", "SQL": "WITH wins AS (SELECT driverId, COUNT(*) AS win_count FROM results WHERE positionOrder = 1 GROUP BY driverId), winner AS (SELECT driverId FROM wins ORDER BY win_count DESC, driverId LIMIT 1) SELECT d.forename, d.surname, d.nationality, (SELECT MAX(s.points) FROM driverStandings AS s WHERE s.driverId = d.driverId) FROM winner AS w JOIN drivers AS d ON d.driverId = w.driverId", "difficulty": "moderate"}
{"question_id": 243, "db_id": "formula_1", "question": "In the 1988 Australian Grand Prix, by what percentage was the winner's elapsed time shorter than the last full-distance finisher's? Use the last finisher's time as denominator and round to two decimals.", "evidence": "", "SQL": "WITH finished AS (SELECT x.positionOrder, x.milliseconds FROM results AS x JOIN races AS r ON r.raceId = x.raceId JOIN status AS s ON s.statusId = x.statusId WHERE r.name = 'Australian Grand Prix' AND r.year = 1988 AND s.status = 'Finished' AND NOT x.milliseconds IS NULL), extremes AS (SELECT MIN(CASE WHEN positionOrder = 1 THEN milliseconds END) AS winner_ms, MAX(CASE WHEN positionOrder = (SELECT MAX(positionOrder) FROM finished) THEN milliseconds END) AS last_ms FROM finished) SELECT ROUND(100.0 * (last_ms - winner_ms) / NULLIF(last_ms, 0), 2) FROM extremes", "difficulty": "challenging"}
{"question_id": 244, "db_id": "formula_1", "question": "What percentage of Japanese-driver race entries from 2007 through 2009 matched their race winner's recorded lap count? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN x.laps = (SELECT y.laps FROM results AS y WHERE y.raceId = x.raceId AND y.positionOrder = 1 ORDER BY y.resultId LIMIT 1) THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM results AS x JOIN races AS r ON r.raceId = x.raceId JOIN drivers AS d ON d.driverId = x.driverId WHERE d.nationality = 'Japanese' AND r.year BETWEEN 2007 AND 2009", "difficulty": "challenging"}
{"question_id": 245, "db_id": "formula_1", "question": "For each year before 1975 with recorded winner times, what was the mean race winner elapsed time in seconds? Round the exact mean to two decimal places; if it is exactly halfway, round away from zero. Order by year.", "evidence": "", "SQL": "SELECT r.year, FLOOR((SUM(x.milliseconds) + 5 * COUNT(*)) / (10 * COUNT(*))) / 100.0 FROM results AS x JOIN races AS r ON r.raceId = x.raceId WHERE r.year < 1975 AND x.positionOrder = 1 AND NOT x.milliseconds IS NULL GROUP BY r.year ORDER BY r.year", "difficulty": "challenging"}
{"question_id": 246, "db_id": "formula_1", "question": "From 2000 through 2005, what percentage of race results were by drivers born before 1985 who completed more than 50 laps?", "evidence": "", "SQL": "SELECT CAST(SUM(IF(DATE_FORMAT(T3.dob, '%Y') < '1985' AND T1.laps > 50, 1, 0)) AS FLOAT) * 100 / COUNT(*) FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN drivers AS T3 ON T1.driverId = T3.driverId WHERE T2.year BETWEEN 2000 AND 2005", "difficulty": "challenging"}
{"question_id": 247, "db_id": "formula_1", "question": "Which constructor scored most points from Monaco Grand Prix between 1980 and 2010? List the score, name and nationality of this team.", "evidence": "", "SQL": "SELECT SUM(T1.points), T2.name, T2.nationality FROM constructorResults AS T1 INNER JOIN constructors AS T2 ON T1.constructorId = T2.constructorId INNER JOIN races AS T3 ON T3.raceId = T1.raceId WHERE T3.name = 'Monaco Grand Prix' AND T3.year BETWEEN 1980 AND 2010 GROUP BY T2.name, T2.nationality ORDER BY SUM(T1.points) DESC LIMIT 1", "difficulty": "challenging"}
{"question_id": 248, "db_id": "formula_1", "question": "Who recorded the fastest Q3 qualifying time at Marina Bay Street Circuit in 2008? Give the driver's first and last name.", "evidence": "", "SQL": "SELECT T2.forename, T2.surname FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS T3 ON T1.raceId = T3.raceId WHERE NOT q3 IS NULL AND T3.year = 2008 AND T3.circuitId IN (SELECT circuitId FROM circuits WHERE name = 'Marina Bay Street Circuit') ORDER BY CAST(SUBSTRING(q3, 1, LOCATE(':', q3) - 1) AS SIGNED) * 60 + CAST(SUBSTRING(q3, LOCATE(':', q3) + 1, LOCATE('.', q3) - LOCATE(':', q3) - 1) AS FLOAT) + CAST(SUBSTRING(q3, LOCATE('.', q3) + 1) AS FLOAT) / 1000 ASC LIMIT 1", "difficulty": "challenging"}
{"question_id": 249, "db_id": "formula_1", "question": "Which 20 drivers recorded the shortest single lap times in Formula 1 races? Give their full names, shortest lap first.", "evidence": "", "SQL": "WITH per_driver AS (SELECT driverId, MIN(milliseconds) AS fastest_ms FROM lapTimes WHERE milliseconds > 0 GROUP BY driverId) SELECT CONCAT(d.forename, ' ', d.surname) AS full_name FROM per_driver AS p JOIN drivers AS d ON d.driverId = p.driverId ORDER BY p.fastest_ms, d.driverId LIMIT 20", "difficulty": "challenging"}
{"question_id": 250, "db_id": "formula_1", "question": "For each Formula 1 circuit in Italy with recorded laps, give the circuit name and its fastest recorded lap time in minutes:seconds.milliseconds format.", "evidence": "", "SQL": "WITH ranked_laps AS (SELECT c.circuitId, c.name AS circuit_name, l.time AS lap_record, ROW_NUMBER() OVER (PARTITION BY c.circuitId ORDER BY l.milliseconds, l.raceId, l.driverId, l.lap) AS rn FROM lapTimes AS l JOIN races AS r ON r.raceId = l.raceId JOIN circuits AS c ON c.circuitId = r.circuitId WHERE c.country = 'Italy' AND l.milliseconds > 0) SELECT circuit_name, lap_record FROM ranked_laps WHERE rn = 1 ORDER BY circuit_name, circuitId", "difficulty": "challenging"}
{"question_id": 251, "db_id": "formula_1", "question": "I'm comparing pit stop activity at the newer Grand Prix weekends. Among the 2017 races that were not hosted in 2000, what was the average number of pit stops per race? Please take the average of all of those races and round it to two decimal places.", "evidence": "Hosted in 2000 means the race was on the 2000 race calendar.", "SQL": "WITH cohort AS (SELECT raceId FROM races WHERE year = 2017 AND NOT name IN (SELECT name FROM races WHERE year = 2000)) SELECT ROUND(1.0 * (SELECT COUNT(*) FROM pitStops WHERE raceId IN (SELECT raceId FROM cohort)) / (SELECT COUNT(*) FROM cohort), 2) AS avg_pit_stops_per_race", "difficulty": "challenging"}
{"question_id": 252, "db_id": "formula_1", "question": "I'm writing a retrospective on German F1 drivers born between 1971 and 1985, and I'd like to quantify how often each of them reached the final part of qualifying. For every German driver born in 1971 through 1985 inclusive, over their entire career (every race on record), please give me their forename, surname, Wikipedia page link, date of birth, and the number of Q3 times they set. Sort the list from most Q3 times to fewest, and where two drivers have the same number, put the older one (by date of birth) first.", "evidence": "Q3 is the third and final part of the qualifying session that sets the starting grid; a driver's Q3 time is the lap time recorded for them in that part.", "SQL": "SELECT d.forename, d.surname, d.url, d.dob, COUNT(NULLIF(q.q3, '')) AS q3_times FROM drivers AS d LEFT JOIN qualifying AS q ON q.driverId = d.driverId WHERE d.nationality = 'German' AND DATE_FORMAT(d.dob, '%Y') BETWEEN '1971' AND '1985' GROUP BY d.driverId ORDER BY q3_times DESC, d.dob ASC", "difficulty": "challenging"}
{"question_id": 253, "db_id": "formula_1", "question": "I'm writing a retrospective on the 1995 Japanese Grand Prix and want to highlight how far off the pace the slowest qualifier was. Could you tell me who set the slowest time in the first qualifying session (Q1) of that race? For that driver (or drivers, if two share the same slowest time, please list them all), I'd like their short reference name, nationality, birthday, and their Q1 time. To be clear, I mean the race named 'Japanese Grand Prix' in the 1995 season. Nothing else needed.", "evidence": "By 'reference name' I mean the short driver code like 'hamilton'; by 'Q1' I mean the first of the three qualifying sessions; by 'birthday' I mean the driver's date of birth.", "SQL": "WITH t AS (SELECT d.driverRef AS driverRef, d.nationality AS nationality, d.dob AS dob, q.q1 AS q1 FROM qualifying AS q INNER JOIN races AS r ON q.raceId = r.raceId INNER JOIN drivers AS d ON q.driverId = d.driverId WHERE r.name = 'Japanese Grand Prix' AND r.year = 1995 AND NOT q.q1 IS NULL AND q.q1 <> '') SELECT a.driverRef, a.nationality, a.dob, a.q1 FROM t AS a WHERE NOT EXISTS(SELECT 1 FROM t AS b WHERE CAST(b.q1 AS FLOAT) > CAST(a.q1 AS FLOAT) OR (CAST(b.q1 AS FLOAT) = CAST(a.q1 AS FLOAT) AND b.q1 > a.q1))", "difficulty": "challenging"}
{"question_id": 254, "db_id": "formula_1", "question": "For qualifying at the 1995 Japanese Grand Prix, I need the nationality of the driver who set the slowest time in Q1. If two drivers tie for the slowest Q1 time, give me each of their nationalities. I only want the nationality value(s), nothing else.", "evidence": "", "SQL": "WITH t AS (SELECT d.nationality, RANK() OVER (ORDER BY CAST(REPLACE(SUBSTRING(q.q1, 1, LOCATE(':', q.q1)), ':', '') AS SIGNED) DESC, CAST(SUBSTRING(q.q1, LOCATE(':', q.q1) + 1) AS SIGNED) DESC) AS rnk FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId JOIN races AS r ON r.raceId = q.raceId WHERE r.year = 1995 AND r.name = 'Japanese Grand Prix' AND NOT q.q1 IS NULL AND q.q1 <> '') SELECT nationality FROM t WHERE rnk = 1", "difficulty": "challenging"}
{"question_id": 255, "db_id": "formula_1", "question": "Who set the fastest time in Q1 at the 1995 Japanese Grand Prix, and what was that time? Please give me the driver's forename and surname, and the Q1 time. By '1995 Japanese Grand Prix' I mean the race of the 1995 season named 'Japanese Grand Prix'. If two drivers tied for the fastest Q1 time, list them all.", "evidence": "Q1: the time a driver set in the first qualifying session.", "SQL": "SELECT d.forename, d.surname, q.q1 FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId JOIN races AS r ON r.raceId = q.raceId WHERE r.year = 1995 AND r.name = 'Japanese Grand Prix' AND NOT q.q1 IS NULL ORDER BY CAST(SUBSTRING(q.q1, 1, LOCATE(':', q.q1) - 1) AS SIGNED) ASC, CAST(SUBSTRING(q.q1, LOCATE(':', q.q1) + 1) AS FLOAT) ASC LIMIT 1", "difficulty": "challenging"}
{"question_id": 256, "db_id": "formula_1", "question": "For the 2010 Formula 1 season, how many drivers did Lucas di Grassi qualify ahead of? I want a single number: the count of drivers he out-qualified over the whole season. By 'qualify ahead of' I mean recording a better qualifying position than that driver in the same race, with a lower position number being better. The 2010 season means the races held in the year 2010.", "evidence": "qualifying position: the starting slot a driver earns in the qualifying session before a race", "SQL": "SELECT COUNT(DISTINCT T2.driverId) AS drivers_qualified_ahead_of FROM qualifying AS T1 JOIN qualifying AS T2 ON T2.raceId = T1.raceId AND T2.position > T1.position JOIN drivers AS D ON D.driverId = T1.driverId JOIN races AS R ON R.raceId = T1.raceId WHERE D.forename = 'Lucas' AND D.surname = 'di Grassi' AND R.year = 2010", "difficulty": "challenging"}
{"question_id": 257, "db_id": "formula_1", "question": "I'm writing a recap of the 2017 Italian Grand Prix and want to credit the country of the quickest driver in the second qualifying session. Can you give me the nationality of the driver who set the fastest Q2 lap time in qualifying for the 2017 edition of the Italian Grand Prix? If two or more drivers tied for the fastest Q2 lap time, give me the nationality of each of them. I just need that nationality (or nationalities, in case of a tie), and nothing else.", "evidence": "Q2: the second of the knockout qualifying sessions of a Grand Prix weekend.", "SQL": "SELECT T2.nationality FROM qualifying AS T1 INNER JOIN races AS T3 ON T3.raceId = T1.raceId INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T3.name = 'Italian Grand Prix' AND T3.year = 2017 AND NOT T1.q2 IS NULL AND T1.q2 <> '' AND T1.q2 = (SELECT MIN(q2) FROM qualifying WHERE raceId = T1.raceId AND NOT q2 IS NULL AND q2 <> '')", "difficulty": "challenging"}
{"question_id": 258, "db_id": "formula_1", "question": "I'm writing an article about the Italian Grand Prix and want to know which first names recur among the drivers who finished second in that race. For every forename carried by two or more runners-up of the Italian Grand Prix across all its editions in the data, please give me one row with the forename and the number of runners-up who carried it. Order the rows from the most runners-up to the fewest, and alphabetically by forename when two forenames are tied. Leave out any forename held by only one runner-up.", "evidence": "A runner-up is the driver who finished second in an edition of the Italian Grand Prix.", "SQL": "SELECT d.forename AS forename, COUNT(DISTINCT d.driverId) AS runner_ups FROM races AS r INNER JOIN results AS x ON x.raceId = r.raceId INNER JOIN drivers AS d ON d.driverId = x.driverId WHERE r.name = 'Italian Grand Prix' AND x.position = 2 GROUP BY d.forename HAVING COUNT(DISTINCT d.driverId) > 1 ORDER BY runner_ups DESC, d.forename", "difficulty": "challenging"}
{"question_id": 259, "db_id": "formula_1", "question": "Who won the 2017 Azerbaijan Grand Prix? I'd like the winner's forename and surname, the local clock time (hours:minutes:seconds.milliseconds) at the circuit at which he crossed the finish line, and the url of his information page, so I can compare the moment the race ended with the TV coverage.", "evidence": "A driver's race time is the duration from the start of the race to the moment he crosses the finish line.", "SQL": "SELECT d.forename, d.surname, CONCAT(TIME_FORMAT(ADDTIME(r.time, CONCAT('0', res.time)), '%H:%i:%s'), '.', SUBSTRING(res.time, -3)) AS finish_time, d.url FROM races AS r JOIN results AS res ON res.raceId = r.raceId JOIN drivers AS d ON d.driverId = res.driverId WHERE r.year = 2017 AND r.name = 'Azerbaijan Grand Prix' AND res.positionOrder = 1", "difficulty": "challenging"}
{"question_id": 260, "db_id": "formula_1", "question": "For the 2017 Italian Grand Prix, I'd like to identify the drivers who completed the second qualifying session (Q2) but were knocked out and did not reach Q3. Please list every such driver - no ranking, cutoff or tie-break, just all of them - showing each driver's reference name, nationality and birthday, and nothing else.", "evidence": "Formula 1 qualifying is run in three timed sessions, Q1, Q2 and Q3; completing a session means the driver recorded a lap time in that session, and only drivers who complete a session move on to the next. The reference name is the driver's short identifier.", "SQL": "SELECT T2.driverRef, T2.nationality, T2.dob FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId INNER JOIN races AS R ON T1.raceId = R.raceId WHERE R.year = 2017 AND R.name = 'Italian Grand Prix' AND NOT T1.q2 IS NULL AND T1.q2 <> '' AND (T1.q3 IS NULL OR T1.q3 = '')", "difficulty": "challenging"}
{"question_id": 261, "db_id": "formula_1", "question": "For the 2017 Italian Grand Prix qualifying, what is the nationality of the driver with the second fastest Q2 time? Only drivers who took part in Q2 count, and by second fastest I mean the second smallest Q2 time. If several drivers share that time, list each of their nationalities.", "evidence": "Q2 is the second qualifying session of a Grand Prix weekend, after Q1.", "SQL": "WITH q2times AS (SELECT d.nationality, q.q2 FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId JOIN races AS r ON r.raceId = q.raceId WHERE r.name = 'Italian Grand Prix' AND r.year = 2017 AND NOT q.q2 IS NULL AND q.q2 <> '') SELECT DISTINCT T.nationality FROM q2times AS T WHERE T.q2 = (SELECT MIN(q2) FROM q2times WHERE q2 > (SELECT MIN(q2) FROM q2times))", "difficulty": "challenging"}
{"question_id": 262, "db_id": "formula_1", "question": "For qualifying at the 2017 Italian Grand Prix, how many drivers set a time in the second qualifying session (Q2) faster than 1:40.000? I just need the count of drivers as a single number.", "evidence": "", "SQL": "SELECT COUNT(DISTINCT q.driverId) AS driver_count FROM qualifying AS q JOIN races AS r ON r.raceId = q.raceId WHERE r.year = 2017 AND r.name = 'Italian Grand Prix' AND NOT q.q2 IS NULL AND q.q2 <> '' AND q.q2 < '1:40.000'", "difficulty": "challenging"}
{"question_id": 263, "db_id": "formula_1", "question": "I'm reviewing the longest service pauses in races across the sport's whole history. Which racetrack saw the longest single pit stop ever? Please give me the racetrack name, location, country, the season year of that race, and the pit stop length. Consider all seasons in the data, and if several pit stops tie for the longest, give me one row for each of them.", "evidence": "pit stop: a recorded pit-stop entry in a race; pit stop length: how long that pit stop lasted", "SQL": "SELECT c.name AS racetrack, c.location, c.country, r.year AS season_year, ps.duration AS pit_stop_length FROM pitStops AS ps JOIN races AS r ON r.raceId = ps.raceId JOIN circuits AS c ON c.circuitId = r.circuitId WHERE ps.milliseconds = (SELECT MAX(milliseconds) FROM pitStops) ORDER BY c.name", "difficulty": "challenging"}
{"question_id": 264, "db_id": "formula_1", "question": "I'm researching the generation of drivers born in the 1980s and want to know how much final-session qualifying that generation actually did as a whole cohort. How many Q3 lap times did a driver born between 1981 and 1991 set on average? Count every driver born in that period in the average, including any who never set a Q3 lap time. Please give me the average rounded to two decimal places.", "evidence": "Q3: the third and final qualifying session of a race weekend, whose times decide the top starting grid positions.", "SQL": "SELECT ROUND(COUNT(q.q3 > '' OR NULL) * 1.0 / COUNT(DISTINCT d.driverId), 2) AS avg_q3_times_per_driver FROM drivers AS d LEFT JOIN qualifying AS q ON q.driverId = d.driverId WHERE DATE_FORMAT(d.dob, '%Y') BETWEEN '1981' AND '1991'", "difficulty": "challenging"}
{"question_id": 265, "db_id": "formula_1", "question": "I'm profiling drivers whose first name alone doesn't identify them. Across all races in the dataset throughout Formula 1 history, how many qualifying 1 times slower than two minutes were set by drivers who share their first name with at least one other driver and who have no code? I want just that single count.", "evidence": "A driver's code is their three-letter abbreviation (e.g. 'HAM'); having no code means no such abbreviation is on record for them. The qualifying 1 time is the time a driver set in the first qualifying session of a race, one per race they took part in.", "SQL": "SELECT COUNT(*) AS n FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId WHERE d.code IS NULL AND EXISTS(SELECT 1 FROM drivers AS o WHERE BINARY o.forename = BINARY d.forename AND o.driverId <> d.driverId) AND NOT q.q1 IS NULL AND (CAST(SUBSTRING(q.q1, 1, LOCATE(':', q.q1) - 1) AS FLOAT) > 2 OR (CAST(SUBSTRING(q.q1, 1, LOCATE(':', q.q1) - 1) AS FLOAT) = 2 AND CAST(SUBSTRING(q.q1, LOCATE(':', q.q1) + 1) AS FLOAT) > 0))", "difficulty": "challenging"}
{"question_id": 266, "db_id": "formula_1", "question": "I'm checking how much of the championship points for drivers named Robert came from races covered by the lap-by-lap timing archive. For every driver whose forename is Robert, I need their reference name and the total points they scored in races where lap-by-lap timing data exists for that driver in that race. The totals should cover all seasons and races on record.", "evidence": "The reference name is the driver's short identifier, and points are championship points recorded for that driver's race result.", "SQL": "SELECT d.driverRef AS reference_name, COALESCE(SUM(r.points), 0) AS total_points FROM drivers AS d LEFT JOIN results AS r ON r.driverId = d.driverId AND EXISTS(SELECT 1 FROM lapTimes AS l WHERE l.raceId = r.raceId AND l.driverId = d.driverId) WHERE d.forename = 'Robert' GROUP BY d.driverId, d.driverRef ORDER BY total_points DESC, reference_name", "difficulty": "challenging"}
{"question_id": 267, "db_id": "formula_1", "question": "For every edition of the French Grand Prix from the 1990 season through the most recent edition, I'd like to know which drivers set a fastest lap of the race slower than 90 seconds. For each such driver, give me the date of the edition, the driver's forename and surname, and their fastest lap time of that race in m:ss.mmm form. If several drivers in an edition clear that 90-second mark, list one row per driver. If an edition has no driver over 90 seconds, still show the edition with its date, but no driver or lap time. Please order the rows from the earliest edition date to the latest, and within an edition by driver surname alphabetically - if two drivers share the same fastest-lap time, order them by forename alphabetically.", "evidence": "A driver's fastest lap in an edition means the shortest time they took to complete any single lap of that race, measured from the start of that lap; the 90-second threshold applies to that fastest lap, not to an average.", "SQL": "WITH editions AS (SELECT raceId, date FROM races WHERE name = 'French Grand Prix' AND year >= 1990), best AS (SELECT raceId, driverId, MIN(milliseconds) AS best FROM lapTimes GROUP BY raceId, driverId) SELECT e.date, d.forename, d.surname, lt.time FROM editions AS e LEFT JOIN best AS b ON b.raceId = e.raceId AND b.best > 90 * 1000 LEFT JOIN lapTimes AS lt ON lt.raceId = b.raceId AND lt.driverId = b.driverId AND lt.milliseconds = b.best LEFT JOIN drivers AS d ON d.driverId = b.driverId ORDER BY e.date, d.surname, d.forename", "difficulty": "challenging"}
{"question_id": 268, "db_id": "formula_1", "question": "I'm putting together a trivia fact about Italian drivers in Formula 1. Who holds the fastest lap time set in Q3 - the third and final part of qualifying - by an Italian driver, across the sport's entire history? Please give me the driver's forename, surname, and the fastest Q3 lap time exactly as it appears in the data. Only consider drivers who have a Q3 lap time recorded for some race, and if several Italian drivers share the exact same fastest Q3 time, list all of them.", "evidence": "Q3 is the third and final part of qualifying.", "SQL": "SELECT d.forename, d.surname, q.q3 AS q3_time FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId WHERE d.nationality = 'Italian' AND q.q3 <> '' AND q.q3 = (SELECT MIN(q2.q3) FROM qualifying AS q2 JOIN drivers AS d2 ON d2.driverId = q2.driverId WHERE d2.nationality = 'Italian' AND q2.q3 > '')", "difficulty": "challenging"}
{"question_id": 269, "db_id": "formula_1", "question": "I'm writing a piece on the new generation of British Formula 1 talent. Among British F1 drivers born after 1980, who set the fastest Q3 qualifying time, what was that time, and at which race and in which year was it set? Please give me the driver's full name, the race name, the race year, and the Q3 time. By 'born after 1980' I mean the year of birth is later than 1980. If two qualifying results tie for the fastest Q3 time, I'd like a row for each.", "evidence": "Q3 is the final part of the qualifying session that decides the front of the starting grid.", "SQL": "WITH cohort AS (SELECT q.driverId, q.raceId, q.q3 FROM drivers AS d JOIN qualifying AS q ON d.driverId = q.driverId WHERE d.nationality = 'British' AND CAST(DATE_FORMAT(d.dob, '%Y') AS SIGNED) > 1980 AND NOT q.q3 IS NULL AND TRIM(q.q3) <> '') SELECT CONCAT(d.forename, ' ', d.surname) AS driver_name, r.name AS race_name, r.year AS race_year, c.q3 AS q3_time FROM cohort AS c JOIN drivers AS d ON d.driverId = c.driverId JOIN races AS r ON r.raceId = c.raceId WHERE c.q3 = (SELECT MIN(q3) FROM cohort)", "difficulty": "challenging"}
{"question_id": 270, "db_id": "formula_1", "question": "We're writing a piece on F1's younger generation and want a number for it: how many drivers born in 1976 or later (born from 1 January 1976 onwards) have ever set the second-fastest lap of a race at any point in the history covered by the data? I just need the single count of such drivers.", "evidence": "By second-fastest lap of a race I mean the driver's own fastest lap in that race was the second quickest among all drivers in that race.", "SQL": "SELECT COUNT(DISTINCT T1.driverId) AS driver_count FROM results AS T1 INNER JOIN drivers AS T2 ON T1.driverId = T2.driverId WHERE DATE_FORMAT(T2.dob, '%Y') >= '1976' AND T1.`rank` = 2", "difficulty": "challenging"}
{"question_id": 271, "db_id": "formula_1", "question": "Who set the fastest time in Q3 (the final qualifying session) at the 2017 Italian Grand Prix? Please give me the driver's reference name (the short identifier like 'hamilton') as the result. If two drivers set the same fastest Q3 time, give me both of their reference names.", "evidence": "Q3: the final qualifying session of a Grand Prix weekend", "SQL": "SELECT d.driverRef FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId JOIN races AS r ON r.raceId = q.raceId WHERE r.year = 2017 AND r.name = 'Italian Grand Prix' AND NOT q.q3 IS NULL AND q.q3 <> '' AND q.q3 = (SELECT MIN(q3) FROM qualifying WHERE raceId = q.raceId AND NOT q3 IS NULL AND q3 <> '')", "difficulty": "challenging"}
{"question_id": 272, "db_id": "formula_1", "question": "Can you rank the Italian Formula 1 constructors by career points and give me the three highest-placed ones? For each, I'd like the constructor name, their career points, and their introduction website. Career points means the total of the points the constructor finished each season with (a season being one calendar year of racing). Constructors with no points still count, ranked with 0. If there are ties, they share a rank and the next rank is skipped (so 1, 1, 3), and I'd like every constructor within the top three ranks returned.", "evidence": "", "SQL": "WITH season AS (SELECT cs.constructorId, cs.points, ROW_NUMBER() OVER (PARTITION BY cs.constructorId, r.year ORDER BY cs.raceId DESC) AS rn FROM constructorStandings AS cs JOIN races AS r ON r.raceId = cs.raceId), career AS (SELECT constructorId, SUM(points) AS pts FROM season WHERE rn = 1 GROUP BY constructorId), ranked AS (SELECT c.name, COALESCE(cr.pts, 0) AS pts, c.url, RANK() OVER (ORDER BY COALESCE(cr.pts, 0) DESC) AS rnk FROM constructors AS c LEFT JOIN career AS cr ON cr.constructorId = c.constructorId WHERE c.nationality = 'Italian') SELECT name, pts, url FROM ranked WHERE rnk <= 3 ORDER BY rnk, pts DESC, name", "difficulty": "challenging"}
{"question_id": 273, "db_id": "formula_1", "question": "I'm writing a piece about how the same common forenames recur across Formula 1 history. Could you tell me how many different drivers named Peter have ever won a Formula 1 race, and the same for drivers named John? Please give me one count per forename, so I can compare the two — if they turn out to be equal, just report both counts side by side. Nothing else needed.", "evidence": "A race win means the driver finished first in that race.", "SQL": "SELECT T1.forename, COUNT(DISTINCT T1.driverId) AS winner_drivers FROM drivers AS T1 INNER JOIN results AS T2 ON T2.driverId = T1.driverId WHERE T2.positionOrder = 1 AND T1.forename IN ('John', 'Peter') GROUP BY T1.forename ORDER BY T1.forename", "difficulty": "challenging"}
{"question_id": 274, "db_id": "formula_1", "question": "I'm working on a story about qualifying records. Across all races, which driver set the fastest time in Q3 (the final part of qualifying)? I'd like the nationality of that driver - and if more than one driver shares the fastest Q3 time, please give me every such driver's nationality. I don't need anything else, just the nationality or nationalities.", "evidence": "Q3: the third and final part of the qualifying session.", "SQL": "SELECT DISTINCT d.nationality FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId WHERE TRIM(q.q3) = (SELECT MIN(q3) FROM qualifying WHERE NOT q3 IS NULL AND TRIM(q3) <> '')", "difficulty": "challenging"}
{"question_id": 275, "db_id": "formula_1", "question": "I'm putting together a historical note on constructor nationalities in Formula 1. For each constructor nationality, how many constructors from that nationality have recorded the fastest lap of a race? Please include every nationality in the result, with a count of 0 for nationalities where no constructor has done so. Count a constructor only when it is officially credited with the quickest single lap time in a race's recorded result - don't compute lap times yourself.", "evidence": "Fastest lap: the constructor officially credited with the quickest single lap time in a race's recorded result.", "SQL": "SELECT c.nationality, COUNT(DISTINCT CASE WHEN r.`rank` = 1 THEN c.constructorId END) AS num_constructors FROM constructors AS c LEFT JOIN results AS r ON c.constructorId = r.constructorId GROUP BY c.nationality ORDER BY num_constructors DESC, c.nationality", "difficulty": "challenging"}
{"question_id": 276, "db_id": "formula_1", "question": "I'm studying how pit stop activity changed across the refuelling-rule change for Australia's F1 drivers. For each season from 2002 through 2013, can you give me the total number of pit stops made at the races of that season where, after the race, at least one Australian driver was placed better than 20th in the driver standings? I'd like the season year and the total pit stop count for each season. The pit stop total should cover every driver who pitted at those races, not just the Australian drivers.", "evidence": "Better than 20th in the driver standings means a position of 1 through 19 after that race. A pit stop is any recorded pit stop made by any driver at the race.", "SQL": "WITH oz_races AS (SELECT DISTINCT r.raceId, r.year FROM races AS r INNER JOIN driverStandings AS ds ON ds.raceId = r.raceId INNER JOIN drivers AS d ON d.driverId = ds.driverId WHERE d.nationality = 'Australian' AND ds.position <= 19 AND r.year BETWEEN 2002 AND 2013) SELECT oz.year AS season, COUNT(ps.stop) AS pit_stops FROM oz_races AS oz LEFT JOIN pitStops AS ps ON ps.raceId = oz.raceId GROUP BY oz.year ORDER BY oz.year", "difficulty": "challenging"}
{"question_id": 277, "db_id": "formula_1", "question": "For the 1995 season (races held in the calendar year 1995), how many drivers set a Q1 lap time of more than two minutes - i.e., strictly longer than 2:00.000? I just need the number of drivers.", "evidence": "Q1: the first of the qualifying sessions; a Q1 time is the lap time a driver set in that session.", "SQL": "SELECT COUNT(DISTINCT T1.driverId) FROM qualifying AS T1 INNER JOIN races AS T2 ON T2.raceId = T1.raceId WHERE T2.year = 1995 AND (CHAR_LENGTH(T1.q1) > CHAR_LENGTH('2:00.000') OR T1.q1 > '2:00.000')", "difficulty": "challenging"}
{"question_id": 278, "db_id": "formula_1", "question": "For my monthly recap I need the fastest pit stop made during any F1 race held in September 2016. Please tell me the driver's full name, the pit stop time, the name of the race where it happened, the circuit name, and the circuit location. If two or more pit stops share the fastest time, list each of them with its own driver, race, circuit name and circuit location.", "evidence": "By pit stop time I mean the elapsed time of a pit stop, from the car arriving at its pit to rejoining the race.", "SQL": "WITH scope AS (SELECT ps.driverId, ps.duration, ps.milliseconds, r.raceId FROM pitStops AS ps JOIN races AS r ON r.raceId = ps.raceId WHERE r.date >= '2016-09-01' AND r.date < '2016-10-01') SELECT CONCAT(d.forename, ' ', d.surname) AS driver_name, s.duration AS pit_stop_time, r.name AS race_name, c.name AS circuit_name, c.location AS circuit_location FROM scope AS s JOIN drivers AS d ON d.driverId = s.driverId JOIN races AS r ON r.raceId = s.raceId JOIN circuits AS c ON c.circuitId = r.circuitId WHERE s.milliseconds = (SELECT MIN(milliseconds) FROM scope)", "difficulty": "challenging"}
{"question_id": 279, "db_id": "formula_1", "question": "I'm profiling the oldest driver ever to win a Formula 1 race. Please identify the winning driver with the earliest date of birth - if two winning drivers share that birth date, use the one whose full name (forename then surname) comes first alphabetically. For that driver, return his full name (forename then surname), his nationality, the name and date of the first race he won (the earliest date; if two of his wins share that date, the one whose race name comes first alphabetically), and the total number of races he started over his entire career. A win means finishing in position 1 in a race. The career covers every race in the database, from 1950 through 2017. Return a single row.", "evidence": "Grand Prix: any race event in the database, whatever its name is; some race names do not contain the words 'Grand Prix'.", "SQL": "WITH winner AS (SELECT d.driverId, d.forename, d.surname, d.nationality FROM drivers AS d WHERE EXISTS(SELECT 1 FROM results AS res WHERE res.driverId = d.driverId AND res.position = 1) ORDER BY d.dob ASC, d.forename ASC, d.surname ASC LIMIT 1) SELECT CONCAT(w.forename, ' ', w.surname) AS full_name, w.nationality, (SELECT r.name FROM results AS res JOIN races AS r ON r.raceId = res.raceId WHERE res.driverId = w.driverId AND res.position = 1 ORDER BY r.date ASC, r.name ASC LIMIT 1) AS first_win_race, (SELECT r.date FROM results AS res JOIN races AS r ON r.raceId = res.raceId WHERE res.driverId = w.driverId AND res.position = 1 ORDER BY r.date ASC, r.name ASC LIMIT 1) AS first_win_date, (SELECT COUNT(DISTINCT res.raceId) FROM results AS res WHERE res.driverId = w.driverId) AS races_started FROM winner AS w", "difficulty": "challenging"}
{"question_id": 280, "db_id": "formula_1", "question": "Across the history of the Canadian Grand Prix, how many runnings of the race have had at least one car retire with an accident? Please note that a crash in which the driver was killed is recorded as its own status and should not count as an accident here. I just need the single number of runnings, nothing else.", "evidence": "accident: a car's race ends because of a crash", "SQL": "SELECT COUNT(DISTINCT T1.raceId) FROM results AS T1 INNER JOIN races AS T2 ON T1.raceId = T2.raceId INNER JOIN status AS T3 ON T1.statusId = T3.statusId WHERE T3.status = 'Accident' AND T2.name = 'Canadian Grand Prix'", "difficulty": "challenging"}
{"question_id": 281, "db_id": "formula_1", "question": "For the 2017 Italian Grand Prix, which driver set the second-fastest time in the second qualifying session (Q2), and which constructor did he drive for that weekend? By second-fastest I mean the driver whose Q2 time comes next after the quickest one, counting every driver who took part in that session. If two drivers tie on Q2 time, the one who started the race higher up the grid counts as the faster of the two. Please give me the driver's forename, the driver's surname, and the constructor name.", "evidence": "Q2: the second of the weekend's qualifying sessions; its times are measured to the thousandth of a second.", "SQL": "WITH t AS (SELECT d.driverId, d.forename, d.surname, co.name AS constructor, q.q2, q.position, CAST(SUBSTRING(q.q2, 1, LOCATE(':', q.q2) - 1) AS SIGNED) AS mins, CAST(SUBSTRING(q.q2, LOCATE(':', q.q2) + 1) AS FLOAT) AS secs FROM qualifying AS q JOIN races AS r ON r.raceId = q.raceId JOIN drivers AS d ON d.driverId = q.driverId JOIN constructors AS co ON co.constructorId = q.constructorId WHERE r.year = 2017 AND r.name = 'Italian Grand Prix' AND NOT q.q2 IS NULL AND q.q2 <> '') SELECT forename, surname, constructor FROM t ORDER BY mins ASC, secs ASC, position ASC, driverId ASC LIMIT 1 OFFSET 1", "difficulty": "challenging"}
{"question_id": 282, "db_id": "formula_1", "question": "I'm writing a season review piece and need the outright quickest Q2 time of the 2017 Formula One season – the fastest single Q2 time set at any race that year. Please give me the surname of the driver who set it and the name of the race where it was set. If two drivers share that fastest Q2 time, list every one of them along with the race names.", "evidence": "Q2: the second of the three qualifying sessions of a Grand Prix weekend.", "SQL": "WITH t AS (SELECT d.surname AS surname, r.name AS race_name, q.driverId AS driverId, q.q2 AS q2 FROM qualifying AS q JOIN drivers AS d ON d.driverId = q.driverId JOIN races AS r ON r.raceId = q.raceId WHERE r.year = 2017 AND q.q2 LIKE '%:%.%'), m AS (SELECT MIN(q2) AS q2 FROM t) SELECT t.surname, t.race_name FROM t JOIN m ON m.q2 = t.q2 ORDER BY t.driverId ASC", "difficulty": "challenging"}
{"question_id": 283, "db_id": "formula_1", "question": "I'm writing a race report and need to name the pole-sitter by their permanent race number. Who set the fastest Q3 qualifying time at the 2017 Italian Grand Prix (the race named 'Italian Grand Prix' in the 2017 season)? Please give me just that driver's permanent number. If two or more drivers share that fastest time, give me the numbers of all of them and nothing else.", "evidence": "Q3 is the final part of qualifying, whose times decide the top starting positions; the fastest Q3 time earns pole position.", "SQL": "SELECT d.number FROM qualifying AS q JOIN races AS r ON r.raceId = q.raceId JOIN drivers AS d ON d.driverId = q.driverId WHERE r.name = 'Italian Grand Prix' AND r.year = 2017 AND NOT q.q3 IS NULL AND q.q3 <> '' AND q.q3 = (SELECT MIN(q2.q3) FROM qualifying AS q2 JOIN races AS r2 ON r2.raceId = q2.raceId WHERE r2.name = 'Italian Grand Prix' AND r2.year = 2017 AND NOT q2.q3 IS NULL AND q2.q3 <> '')", "difficulty": "challenging"}
{"question_id": 284, "db_id": "formula_1", "question": "For the 2017 Italian Grand Prix, who set the fastest lap time in Q3 (the final qualifying session), and what was that time? Give me the driver code along with the fastest Q3 time. If two or more drivers tie for the fastest Q3 time, list every tied driver.", "evidence": "Q3: the third and final qualifying session; a driver's Q3 time is the lap time that driver set in that session", "SQL": "SELECT T2.code, T1.q3 FROM qualifying AS T1 INNER JOIN drivers AS T2 ON T2.driverId = T1.driverId WHERE T1.raceId = (SELECT raceId FROM races WHERE year = 2017 AND name = 'Italian Grand Prix') AND T1.q3 <> '' AND T1.q3 = (SELECT MIN(q3) FROM qualifying WHERE raceId = (SELECT raceId FROM races WHERE year = 2017 AND name = 'Italian Grand Prix') AND q3 <> '')", "difficulty": "challenging"}
{"question_id": 285, "db_id": "formula_1", "question": "I'm writing a report on the 2017 Italian Grand Prix (the one held in the 2017 season). Could you tell me the nationality of the driver who set the fastest time in Q3, the final part of qualifying? If several drivers share the same fastest Q3 time, please give each of their nationalities.", "evidence": "Q3 is the third and final part of the qualifying session.", "SQL": "SELECT d.nationality FROM qualifying AS q JOIN races AS r ON r.raceId = q.raceId JOIN drivers AS d ON d.driverId = q.driverId WHERE r.year = 2017 AND r.name = 'Italian Grand Prix' AND NOT q.q3 IS NULL AND q.q3 <> '' AND q.q3 = (SELECT MIN(q2.q3) FROM qualifying AS q2 JOIN races AS r2 ON r2.raceId = q2.raceId WHERE r2.year = 2017 AND r2.name = 'Italian Grand Prix' AND NOT q2.q3 IS NULL AND q2.q3 <> '')", "difficulty": "challenging"}
{"question_id": 286, "db_id": "formula_1", "question": "Which Chinese Grand Prix edition from the 2000s (2000–2009 seasons) had the earliest scheduled local start time? Give me the season year of that edition and the runner-up's time gap to the winner (the runner-up being the driver classified second at the finish). If several editions share the earliest scheduled local start time, use the most recent one.", "evidence": "Scheduled local start time: the time of day the race was scheduled to start, local to the circuit.", "SQL": "SELECT r.year, res.time AS runner_up_gap FROM races AS r JOIN results AS res ON res.raceId = r.raceId WHERE r.name = 'Chinese Grand Prix' AND r.year BETWEEN 2000 AND 2009 AND res.positionOrder = 2 AND NOT r.time IS NULL AND r.time = (SELECT MIN(r2.time) FROM races AS r2 WHERE r2.name = 'Chinese Grand Prix' AND r2.year BETWEEN 2000 AND 2009 AND NOT r2.time IS NULL) ORDER BY r.year DESC LIMIT 1", "difficulty": "challenging"}
{"question_id": 287, "db_id": "formula_1", "question": "I'm writing a qualifying report. Can you give me the driver codes of all drivers who set a time in the third qualifying session at the 2017 Italian Grand Prix? One row per driver who set such a time, and please list the codes in alphabetical order. Nothing else needed.", "evidence": "The third qualifying session is the final segment of the race weekend's qualifying, in which only the fastest drivers take part.", "SQL": "SELECT d.code FROM qualifying AS q JOIN races AS r ON r.raceId = q.raceId JOIN drivers AS d ON d.driverId = q.driverId WHERE r.year = 2017 AND r.name = 'Italian Grand Prix' AND NOT q.q3 IS NULL AND q.q3 <> '' ORDER BY d.code", "difficulty": "challenging"}
{"question_id": 288, "db_id": "formula_1", "question": "I'm writing about how the Canadian Grand Prix moved to early-evening starts. Could you find the editions of the Canadian Grand Prix from 2007 through 2017 (both years included) that began at 17:00 local time or earlier - a race that began exactly at 17:00 counts. For each one, give me the race year, the winner's forename, the winner's surname, and the winner's finish time. The winner is the single driver classified first at the finish. Nothing else, please.", "evidence": "An edition is one running of the Canadian Grand Prix in a given year; local start time is the clock time of day, local to the circuit, at which the race began, on the 24-hour clock.", "SQL": "SELECT r.year, d.forename, d.surname, res.time AS finish_time FROM races AS r JOIN results AS res ON res.raceId = r.raceId AND res.positionOrder = 1 JOIN drivers AS d ON d.driverId = res.driverId WHERE r.name = 'Canadian Grand Prix' AND r.year BETWEEN 2007 AND 2017 AND TIME(r.time) <= TIME('17:00') ORDER BY r.year", "difficulty": "challenging"}
{"question_id": 289, "db_id": "formula_1", "question": "I'm writing a retrospective on the 2017 Italian Grand Prix at Monza. For the Q3 session of that race's qualifying, can you give me the permanent career race number and surname of every driver whose Q3 lap time was strictly faster than 1 minute 38.000 seconds? I want all drivers under that mark, not just the fastest, and no particular order. Note that by permanent career race number I mean the number a driver carries throughout his career, not a one-off entry number for that weekend.", "evidence": "Q3 is the third and final qualifying session; a driver only has a Q3 time if he actually took part in that session.", "SQL": "WITH mark(t) AS (SELECT CONCAT('1', ':', '38.000')) SELECT d.number, d.surname FROM qualifying AS q INNER JOIN races AS r ON r.raceId = q.raceId INNER JOIN drivers AS d ON d.driverId = q.driverId WHERE r.year = 2017 AND r.name = 'Italian Grand Prix' AND q.q3 LIKE '%:%' AND q.q3 < (SELECT t FROM mark) ORDER BY d.number", "difficulty": "challenging"}
{"question_id": 290, "db_id": "formula_1", "question": "Across all seasons in the database, which circuit's Grand Prix started earliest in the day, and which started latest? I'd like the circuit reference name of the earliest one, the circuit reference name of the latest one, and the gap between those two start times in seconds. Include every season, and if several circuits share the earliest start time, list them all - same for the latest.", "evidence": "By \"start time of the day\" I mean the local clock time at the venue at which the race started.", "SQL": "WITH per_circuit AS (SELECT c.circuitRef AS circuitRef, MIN(CAST(TIME_TO_SEC(r.time) AS SIGNED)) AS earliest_start_seconds, MAX(CAST(TIME_TO_SEC(r.time) AS SIGNED)) AS latest_start_seconds FROM races AS r JOIN circuits AS c ON c.circuitId = r.circuitId WHERE NOT r.time IS NULL GROUP BY c.circuitRef) SELECT GROUP_CONCAT(circuitRef SEPARATOR ', ') AS earliest_circuitRef, (SELECT GROUP_CONCAT(circuitRef SEPARATOR ', ') FROM per_circuit WHERE latest_start_seconds = (SELECT MAX(latest_start_seconds) FROM per_circuit)) AS latest_circuitRef, (SELECT MAX(latest_start_seconds) - MIN(earliest_start_seconds) FROM per_circuit) AS gap_seconds FROM per_circuit WHERE earliest_start_seconds = (SELECT MIN(earliest_start_seconds) FROM per_circuit)", "difficulty": "challenging"}
{"question_id": 291, "db_id": "formula_1", "question": "I'm looking into fastest race laps recorded by drivers born in the 1980s. Can you tell me which three drivers born between 1980 and 1990 reached the highest single fastest-lap speed at any point in their career? I'd like their first and last names, ranked from the highest career-high speed down, and if two drivers are tied on that speed, list the one born earlier first, and then the one whose last name comes first alphabetically. Please give me just the three names, nothing else.", "evidence": "Fastest lap speed: the average speed, in km/h, that a driver recorded on their single fastest lap of a race. A driver's career-high speed is based on that one lap, not an average across their laps.", "SQL": "SELECT d.forename, d.surname FROM drivers AS d JOIN results AS r ON r.driverId = d.driverId WHERE SUBSTRING(d.dob, 1, 4) BETWEEN '1980' AND '1990' AND NOT r.fastestLapSpeed IS NULL GROUP BY d.driverId, d.forename, d.surname, d.dob ORDER BY MAX(CAST(r.fastestLapSpeed AS FLOAT)) DESC, d.dob, d.surname LIMIT 3", "difficulty": "challenging"}
{"question_id": 292, "db_id": "formula_1", "question": "For the 2017 Italian Grand Prix, I need the list of drivers who were eliminated after the first qualifying session. Give me one row per eliminated driver with their reference name, ordered by their first-segment time from slowest to fastest. If two eliminated drivers have the same first-segment time, list the one with the lower driverId first.", "evidence": "Eliminated after the first qualifying session means the driver took part in qualifying but did not go out in the second qualifying session.", "SQL": "SELECT d.driverRef FROM qualifying AS q JOIN races AS r ON r.raceId = q.raceId JOIN drivers AS d ON d.driverId = q.driverId WHERE r.name = 'Italian Grand Prix' AND r.year = 2017 AND NOT q.q1 IS NULL AND (q.q2 IS NULL OR q.q2 = '') ORDER BY q.q1 DESC, d.driverId", "difficulty": "challenging"}
{"question_id": 293, "db_id": "formula_1", "question": "For my retrospective on the 1962 British Grand Prix – the race named 'British Grand Prix' in the 1962 season – how many drivers withdrew from that race? I just need a single whole number.", "evidence": "A driver who withdrew from a race is recorded with the status 'Withdrew'.", "SQL": "SELECT COUNT(DISTINCT x.driverId) AS num_withdrawn_drivers FROM results AS x JOIN races AS r ON r.raceId = x.raceId JOIN status AS s ON s.statusId = x.statusId WHERE r.name = 'British Grand Prix' AND r.year = 1962 AND s.status = 'Withdrew'", "difficulty": "challenging"}
{"question_id": 294, "db_id": "formula_1", "question": "For the 1957 British Grand Prix, what percentage of the drivers who took part in the race were classified finishers, rounded to two decimals? By classified finisher I mean a driver whose race record shows them finishing the race, whether on the lead lap or one or more laps behind the winner. I just need the one percentage figure.", "evidence": "classified finisher: a driver whose race record shows them finishing the race, whether on the lead lap or one or more laps behind the winner", "SQL": "SELECT ROUND(100.0 * COUNT(DISTINCT CASE WHEN NOT x.position IS NULL THEN x.driverId END) / COUNT(DISTINCT x.driverId), 2) AS finisher_percentage FROM races AS r JOIN results AS x ON x.raceId = r.raceId WHERE r.year = 1957 AND r.name = 'British Grand Prix'", "difficulty": "challenging"}
{"question_id": 295, "db_id": "student_club", "question": "What was Elijah Allen's mean total expense per event for expenses dated in September or October? Round to two decimals.", "evidence": "", "SQL": "WITH per_event AS (SELECT b.link_to_event, SUM(e.cost) AS event_spend FROM expense AS e JOIN member AS m ON m.member_id = e.link_to_member JOIN budget AS b ON b.budget_id = e.link_to_budget WHERE m.first_name = 'Elijah' AND m.last_name = 'Allen' AND SUBSTRING(e.expense_date, 6, 2) IN ('09', '10') AND NOT b.link_to_event IS NULL GROUP BY b.link_to_event) SELECT ROUND(AVG(event_spend), 2) FROM per_event", "difficulty": "challenging"}
{"question_id": 296, "db_id": "student_club", "question": "What is the total amount spent on Student Club events in 2019 minus the total spent on events in 2020?", "evidence": "", "SQL": "SELECT SUM(CASE WHEN SUBSTRING(T1.event_date, 1, 4) = '2019' THEN T2.spent ELSE 0 END) - SUM(CASE WHEN SUBSTRING(T1.event_date, 1, 4) = '2020' THEN T2.spent ELSE 0 END) AS num FROM event AS T1 INNER JOIN budget AS T2 ON T1.event_id = T2.link_to_event", "difficulty": "moderate"}
{"question_id": 297, "db_id": "student_club", "question": "What note was recorded for the fundraising proceeds received on September 14, 2019?", "evidence": "", "SQL": "SELECT notes FROM income WHERE source = 'Fundraising' AND date_received = '2019-09-14'", "difficulty": "simple"}
{"question_id": 298, "db_id": "student_club", "question": "What is the ratio of the Advertisement budget for the Yearly Kickoff meeting to that for the October Meeting?", "evidence": "", "SQL": "SELECT CAST(SUM(CASE WHEN T2.event_name = 'Yearly Kickoff' THEN T1.amount ELSE 0 END) AS FLOAT) / SUM(CASE WHEN T2.event_name = 'October Meeting' THEN T1.amount ELSE 0 END) FROM budget AS T1 INNER JOIN event AS T2 ON T1.link_to_event = T2.event_id WHERE T1.category = 'Advertisement' AND T2.type = 'Meeting'", "difficulty": "challenging"}
{"question_id": 299, "db_id": "student_club", "question": "Which closed events are tied for the highest ratio of total spending to total budget amount?", "evidence": "", "SQL": "WITH ratios AS (SELECT e.event_id, e.event_name, CAST(SUM(b.spent) AS DECIMAL(20, 4)) / NULLIF(SUM(b.amount), 0) AS ratio FROM event AS e JOIN budget AS b ON b.link_to_event = e.event_id WHERE e.status = 'Closed' GROUP BY e.event_id, e.event_name HAVING SUM(b.amount) > 0) SELECT event_name FROM ratios WHERE ratio = (SELECT MAX(ratio) FROM ratios)", "difficulty": "moderate"}
{"question_id": 300, "db_id": "student_club", "question": "List the name of students that have attended more than 7 events.", "evidence": "", "SQL": "SELECT T1.first_name, T1.last_name FROM member AS T1 INNER JOIN attendance AS T2 ON T1.member_id = T2.link_to_member GROUP BY T2.link_to_member, T1.first_name, T1.last_name HAVING COUNT(T2.link_to_event) > 7", "difficulty": "moderate"}
{"question_id": 301, "db_id": "student_club", "question": "Which members incurred at least one expense above the overall average expense cost? Give each member's first name, last name, and phone number as separate fields.", "evidence": "", "SQL": "SELECT DISTINCT T3.first_name, T3.last_name, T3.phone FROM expense AS T1 INNER JOIN budget AS T2 ON T1.link_to_budget = T2.budget_id INNER JOIN member AS T3 ON T3.member_id = T1.link_to_member WHERE T1.cost > (SELECT AVG(T1.cost) FROM expense AS T1 INNER JOIN budget AS T2 ON T1.link_to_budget = T2.budget_id INNER JOIN member AS T3 ON T3.member_id = T1.link_to_member)", "difficulty": "challenging"}
{"question_id": 302, "db_id": "student_club", "question": "I'm putting together a review of last fall's activities and want to see how the Women's Soccer game compared to a typical event that semester. Please give me one row with: the number of students who attended the Women's Soccer event, the average number of students who attended events held in fall 2019 rounded to one decimal place, and a verdict of 'more', 'fewer' or 'equal' comparing the Women's Soccer head count to that average. Fall 2019 means events from 1 September 2019 through 30 November 2019 inclusive, and every event that semester counts toward the average even if nobody attended it. The verdict should compare the Women's Soccer head count to the rounded average: above it is 'more', below is 'fewer', exactly equal is 'equal'.", "evidence": "Women's Soccer is an event name; attendance at an event is the number of members who attended it.", "SQL": "WITH fall_events AS (SELECT e.event_id, (SELECT COUNT(*) FROM attendance AS a WHERE a.link_to_event = e.event_id) AS attendees FROM event AS e WHERE e.event_date >= '2019-09-01' AND e.event_date < '2019-12-01'), agg AS (SELECT ROUND(AVG(attendees), 1) AS avg_att FROM fall_events), soccer AS (SELECT COUNT(*) AS head_count FROM attendance AS a JOIN event AS e ON e.event_id = a.link_to_event WHERE e.event_name = 'Women''s Soccer') SELECT s.head_count AS soccer_attendance, g.avg_att AS average_attendance, CASE WHEN s.head_count > g.avg_att THEN 'more' WHEN s.head_count < g.avg_att THEN 'fewer' ELSE 'equal' END AS verdict FROM soccer AS s CROSS JOIN agg AS g", "difficulty": "challenging"}
{"question_id": 303, "db_id": "student_club", "question": "I'm reviewing our roster against the catalog and want to see how much of the College of Humanities and Social Sciences' coverage our members actually hold, department by department. For each department in that college, give me: the department's name, the majors it offers, the majors held by at least one of our members, and the average members per major it offers, rounded to two decimals. Membership is as currently listed in the member records, and count a department as belonging to the college when any of its majors sits in the college.", "evidence": "College of Humanities and Social Sciences: one of the colleges that houses departments offering majors.", "SQL": "SELECT m.department, COUNT(DISTINCT m.major_id) AS majors_offered, COUNT(DISTINCT mem.link_to_major) AS majors_held, ROUND(1.0 * COUNT(DISTINCT mem.member_id) / COUNT(DISTINCT m.major_id), 2) AS avg_members_per_major FROM major AS m LEFT JOIN member AS mem ON mem.link_to_major = m.major_id WHERE m.college = 'College of Humanities and Social Sciences' GROUP BY m.department", "difficulty": "challenging"}
{"question_id": 304, "db_id": "student_club", "question": "I'm putting together our yearly report and need a breakdown of our 2019 events by event type. For each type of event we held in 2019, please give me: the event type, how many members attended that type's events during 2019, and the total amount budgeted for that type's events in dollars. A few notes: 2019 means the calendar year; the budgeted amount is the planned amount, not what was actually spent. If nothing was budgeted for a type's events, or no member attended them, just show zero. Please list one row per event type, in alphabetical order by event type.", "evidence": "", "SQL": "SELECT e.type AS event_type, (SELECT COUNT(DISTINCT a.link_to_member) FROM attendance AS a JOIN event AS e2 ON e2.event_id = a.link_to_event WHERE e2.type = e.type AND SUBSTRING(e2.event_date, 1, 4) = '2019') AS members_who_attended, CAST(COALESCE((SELECT SUM(b.amount) FROM budget AS b JOIN event AS e3 ON e3.event_id = b.link_to_event WHERE e3.type = e.type AND SUBSTRING(e3.event_date, 1, 4) = '2019'), 0) AS FLOAT) AS total_budgeted FROM event AS e WHERE SUBSTRING(e.event_date, 1, 4) = '2019' GROUP BY e.type ORDER BY e.type", "difficulty": "challenging"}
{"question_id": 305, "db_id": "student_club", "question": "I'm putting together a financial overview for the college that houses the Electrical and Computer Engineering Department. For each department of that college, can you tell me the total dues the club actually received from that department's enrolled members who took part in the club's events, in dollars? Please include every department of the college, showing zero if we received no such dues from it. Just the department name and the total dues per department.", "evidence": "'Dues' is the income source label for membership dues a member pays to the club; 'Member' is the club position of an enrolled member, as opposed to officer or inactive positions.", "SQL": "SELECT m.department, COALESCE(SUM(i.amount), 0) AS total_dues_received FROM major AS m LEFT JOIN member AS mb ON mb.link_to_major = m.major_id AND mb.position = 'Member' LEFT JOIN income AS i ON i.link_to_member = mb.member_id AND i.source = 'Dues' AND EXISTS(SELECT 1 FROM attendance AS a WHERE a.link_to_member = mb.member_id) WHERE m.college IN (SELECT college FROM major WHERE department = 'Electrical and Computer Engineering Department') GROUP BY m.department ORDER BY m.department", "difficulty": "challenging"}
{"question_id": 306, "db_id": "student_club", "question": "For the mid-year budget review: I need to see, for each member who had to spend more than fifty dollars on an expense, how much room was still left in the budget lines those purchases were charged against. Please give me, per member, their first name, last name, and the total amount left across those budget lines in dollars rounded to two decimals. Order the results from the largest total down to the smallest; if two members have the same total, list them alphabetically by last name and then first name. The totals should cover all expenses on record, and if a budget line ended up overdrawn, its negative remaining amount should count toward the total.", "evidence": "Spending more than fifty dollars on an expense means the expense's dollar cost is over 50. The amount left in a budget line is the amount budgeted for that line minus the amount spent against it.", "SQL": "SELECT m.first_name, m.last_name, ROUND(SUM(b.remaining), 2) AS remaining_total FROM member AS m JOIN (SELECT DISTINCT link_to_member, link_to_budget FROM expense WHERE cost > 50) AS e ON e.link_to_member = m.member_id JOIN budget AS b ON b.budget_id = e.link_to_budget GROUP BY m.member_id, m.first_name, m.last_name ORDER BY remaining_total DESC, m.last_name ASC, m.first_name ASC", "difficulty": "challenging"}
{"question_id": 307, "db_id": "student_club", "question": "I'm putting together our year-end budget summary. How much did we collect in membership dues, in total dollars, from the students who attended the Football game? Membership dues are the payments recorded under the source 'Dues'.", "evidence": "membership dues: payments recorded under the source 'Dues'", "SQL": "SELECT SUM(i.amount) AS total_dues FROM income AS i WHERE i.source = 'Dues' AND i.link_to_member IN (SELECT a.link_to_member FROM attendance AS a INNER JOIN event AS e ON a.link_to_event = e.event_id WHERE e.event_name = 'Football game')", "difficulty": "challenging"}
{"question_id": 308, "db_id": "student_club", "question": "How many majors offered by the college that offers Tyler Hewitt's major currently have no enrolled members in the club? Count every major that college offers, by major name.", "evidence": "Enrolled members are the people recorded in the club's membership list.", "SQL": "SELECT COUNT(*) AS num_majors_without_members FROM major AS m WHERE m.college = (SELECT T2.college FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T1.first_name = 'Tyler' AND T1.last_name = 'Hewitt') AND NOT EXISTS(SELECT 1 FROM member AS mm WHERE mm.link_to_major = m.major_id)", "difficulty": "challenging"}
{"question_id": 309, "db_id": "student_club", "question": "For our end-of-year report, I need one figure: the average number of members who attended each event that carried a budget line for advertising, covering every such event across the club's records regardless of when it took place. Please give it as a single number rounded to two decimal places.", "evidence": "A budget line for advertising means a budget entry whose category is advertising.", "SQL": "WITH att AS (SELECT link_to_event, COUNT(DISTINCT link_to_member) AS members FROM attendance GROUP BY link_to_event) SELECT ROUND(AVG(COALESCE(att.members, 0)), 2) AS average_attendance FROM event AS T1 INNER JOIN budget AS T2 ON T2.link_to_event = T1.event_id AND T2.category = 'Advertisement' LEFT JOIN att ON att.link_to_event = T1.event_id", "difficulty": "challenging"}
{"question_id": 310, "db_id": "student_club", "question": "For every budget review event the club has held, can you give me the event name, its location, and the number of members who attended? I need this for the year-end report.", "evidence": "'Budget' is the club's event type for its budget review events, such as the Fall Budget Review and the Spring Budget Review.", "SQL": "SELECT e.event_name, e.location, COUNT(a.link_to_member) AS attended FROM event AS e LEFT JOIN attendance AS a ON e.event_id = a.link_to_event WHERE e.type = 'Budget' GROUP BY e.event_id, e.event_name, e.location", "difficulty": "challenging"}
{"question_id": 311, "db_id": "student_club", "question": "I'm planning study-partner pairings around our biggest social-attendance event. Can you tell me which academic majors were most represented among the members who attended the football game? For each major, give me the major name and the number of attendees in that major. If several majors tie for the highest attendee count, list all of them, ordered alphabetically by major name.", "evidence": "Football game: the event named 'Football game'", "SQL": "WITH cnt AS (SELECT mj.major_name AS major_name, COUNT(DISTINCT m.member_id) AS attendees FROM event AS e JOIN attendance AS a ON a.link_to_event = e.event_id JOIN member AS m ON m.member_id = a.link_to_member JOIN major AS mj ON mj.major_id = m.link_to_major WHERE e.event_name = 'Football game' GROUP BY mj.major_id, mj.major_name) SELECT major_name, attendees FROM cnt WHERE attendees = (SELECT MAX(attendees) FROM cnt) ORDER BY major_name", "difficulty": "challenging"}
{"question_id": 312, "db_id": "student_club", "question": "I want to gauge how much of the university's range of academic programs our club is failing to reach. Out of every major offered by the university - including majors where we have no members - what percentage have no club member studying them? Please give me just that single percentage, between 0 and 100, rounded to two decimal places.", "evidence": "Major: an academic program offered by the university, as listed in the club's records of majors.", "SQL": "SELECT ROUND(CAST((SELECT COUNT(*) FROM major AS m WHERE NOT EXISTS(SELECT 1 FROM member AS mem WHERE mem.link_to_major = m.major_id)) AS FLOAT) * 100 / (SELECT COUNT(*) FROM major), 2) AS percentage", "difficulty": "challenging"}
{"question_id": 313, "db_id": "student_club", "question": "Our officer team wants to settle a debate about whether we pull more weight than the rest of the club, so we need the attendance numbers before the next meeting. Could you tell us two things: the average number of events attended per officer, and the average number of events attended per other student, each rounded to two decimal places? To be clear on who counts where: officers are the members holding the position of President, Vice President, Secretary, or Treasurer, and everyone else in the club counts as an other student. Each average should cover every member of its group, and include every event in the club's records - there's no date cutoff.", "evidence": "", "SQL": "WITH t AS (SELECT m.member_id, m.position, COUNT(a.link_to_event) AS cnt FROM member AS m LEFT JOIN attendance AS a ON a.link_to_member = m.member_id GROUP BY m.member_id, m.position) SELECT ROUND(AVG(CASE WHEN t.position IN ('President', 'Vice President', 'Secretary', 'Treasurer') THEN t.cnt END), 2) AS officer_avg, ROUND(AVG(CASE WHEN NOT t.position IN ('President', 'Vice President', 'Secretary', 'Treasurer') THEN t.cnt END), 2) AS other_students_avg FROM t", "difficulty": "challenging"}
{"question_id": 314, "db_id": "student_club", "question": "I'm finalizing the semester wrap-up report and need one number: how many different kinds of things the club bought for events that went over budget this semester. A few things to keep in mind: an event counts as over budget if, in at least one of its budgeted categories, we spent more than we budgeted for that category - the budgeted amount minus what was actually spent came out below zero. Also, a single purchase can cover several kinds of things at once, and the purchase description lists what it bought, so make sure each kind is counted. The answer should cover the whole semester shown in the records, and I just need the single integer count, nothing else.", "evidence": "went over budget: a budgeted category of the event ended with more spent than was budgeted for it, i.e. the amount budgeted minus the amount spent is below zero; kind of thing: a type of item bought, like water, pizza or posters", "SQL": "WITH RECURSIVE over_budget_events AS (SELECT DISTINCT link_to_event FROM budget WHERE amount - spent < 0), purchases AS (SELECT ex.expense_description AS d FROM expense AS ex JOIN budget AS b ON ex.link_to_budget = b.budget_id WHERE b.link_to_event IN (SELECT link_to_event FROM over_budget_events)), items(item, rest) AS (SELECT TRIM(SUBSTRING(CONCAT(d, ','), 1, LOCATE(',', CONCAT(d, ',')) - 1)), SUBSTRING(CONCAT(d, ','), LOCATE(',', CONCAT(d, ',')) + 1) FROM purchases UNION ALL SELECT TRIM(SUBSTRING(rest, 1, LOCATE(',', rest) - 1)), SUBSTRING(rest, LOCATE(',', rest) + 1) FROM items WHERE rest <> '') SELECT COUNT(DISTINCT LOWER(item)) AS kinds FROM items WHERE item <> ''", "difficulty": "challenging"}
{"question_id": 315, "db_id": "student_club", "question": "For every event in our records that had at least one attendee, I need the amount spent per attendee on bottled drinking water, in dollars and cents rounded to two decimals. Give me one row per event with the event name and that amount; if an attended event had no water purchases, show 0.00, and if two events share a name, list them separately. Include all events regardless of status, across the club's entire history. A purchase that included water along with other items counts fully toward water.", "evidence": "water: bottled drinking water bought for attendees", "SQL": "WITH water AS (SELECT b.link_to_event AS event_id, SUM(e.cost) AS total_cost FROM expense AS e JOIN budget AS b ON e.link_to_budget = b.budget_id WHERE e.expense_description LIKE '%water%' GROUP BY b.link_to_event), att AS (SELECT link_to_event AS event_id, COUNT(*) AS attendees FROM attendance GROUP BY link_to_event) SELECT ev.event_name, ROUND(COALESCE(w.total_cost, 0) / a.attendees, 2) AS water_cost_per_attendee FROM event AS ev JOIN att AS a ON a.event_id = ev.event_id LEFT JOIN water AS w ON w.event_id = ev.event_id GROUP BY ev.event_id, ev.event_name, a.attendees, w.total_cost ORDER BY ev.event_name", "difficulty": "challenging"}
{"question_id": 316, "db_id": "student_club", "question": "For my report on the club's academic makeup, could you tell me how many members on the club roster major in a department of the College of Humanities and Social Sciences, and how many members do not? The two counts together should cover every member on the roster, with each member counted in exactly one of the two groups. A member counts as majoring in the college only if the department offering their major belongs to the College of Humanities and Social Sciences.", "evidence": "The College of Humanities and Social Sciences is a college made up of certain departments; membership in the college is determined by which department offers a member's major.", "SQL": "WITH flag AS (SELECT m.member_id, CASE WHEN b.college = 'College of Humanities and Social Sciences' THEN 1 ELSE 0 END AS in_college FROM member AS m LEFT JOIN major AS b ON m.link_to_major = b.major_id) SELECT SUM(in_college) AS members_in_college, COUNT(*) - SUM(in_college) AS members_not_in_college FROM flag", "difficulty": "challenging"}
{"question_id": 317, "db_id": "student_club", "question": "For our snack budget planning: among the events that spent money on chips, which event has the highest budget amount? By budget amount I mean a single budget line, not a total across lines - compare events by their largest single budgeted line. If several events tie on that largest line, list all of their names. Please just give me the event name(s).", "evidence": "", "SQL": "WITH chip_events AS (SELECT DISTINCT b.link_to_event AS event_id FROM budget AS b INNER JOIN expense AS x ON x.link_to_budget = b.budget_id WHERE x.expense_description LIKE '%chips%') SELECT e.event_name FROM event AS e INNER JOIN budget AS b ON b.link_to_event = e.event_id WHERE e.event_id IN (SELECT event_id FROM chip_events) AND b.amount = (SELECT MAX(amount) FROM budget WHERE link_to_event IN (SELECT event_id FROM chip_events))", "difficulty": "challenging"}
{"question_id": 318, "db_id": "student_club", "question": "What is the date of the Vice President's most recent expense on record, and what is the total cost of all expenses incurred on that date? Consider all expenses on record with no earlier cut-off, and give the total exactly as it appears in the records, without rounding.", "evidence": "Vice President is a position of the Student Club.", "SQL": "SELECT e.expense_date, SUM(e.cost) AS total_cost FROM expense AS e JOIN member AS m ON m.member_id = e.link_to_member WHERE m.position = 'Vice President' AND e.expense_date = (SELECT MAX(e2.expense_date) FROM expense AS e2 JOIN member AS m2 ON m2.member_id = e2.link_to_member WHERE m2.position = 'Vice President') GROUP BY e.expense_date", "difficulty": "challenging"}
{"question_id": 319, "db_id": "student_club", "question": "I'm reviewing member engagement for our club's events in MU 215. Can you give me, for each event category of events held at MU 215, the number of club members who attended those events? Please count events regardless of their status (planning, open, or closed), and make sure every category that had events at MU 215 shows up, even if none of its events had any attendees.", "evidence": "MU 215: the room name as the event location.", "SQL": "SELECT e.type AS event_category, COUNT(DISTINCT a.link_to_member) AS attended_members FROM event AS e LEFT JOIN attendance AS a ON a.link_to_event = e.event_id WHERE e.location = 'MU 215' GROUP BY e.type", "difficulty": "challenging"}
{"question_id": 320, "db_id": "student_club", "question": "I'm putting together a recruitment report for the colleges and want to know which parts of the university our club's membership actually draws from. For every person on the roster-regardless of their position in the club-look at their major, and the college that houses the department offering that major. Which college or colleges do the most majors on our roster come from, and how many majors is that? If there's a tie at the top, give me every college tied at that count. Please list the colleges in alphabetical order by college name, and return just each college's name and its number of majors.", "evidence": "Major: a field of study offered by a department housed in a college.", "SQL": "WITH cnt AS (SELECT mj.college AS college, COUNT(DISTINCT mj.major_id) AS majors FROM member AS m JOIN major AS mj ON mj.major_id = m.link_to_major GROUP BY mj.college) SELECT college, majors FROM cnt WHERE majors = (SELECT MAX(majors) FROM cnt) ORDER BY college", "difficulty": "challenging"}
{"question_id": 321, "db_id": "student_club", "question": "I want to review what the money actually went on for the well-funded events, by venue. For events that had a budget line of more than forty dollars, how many different things were bought for them at each location? Please give me, for each location, the location of the event and the number of different things bought for such events at that location, and nothing else. Note that a budget line of more than forty dollars means a single budgeted amount strictly over 40 dollars, and all qualifying events held at a location should be pooled together.", "evidence": "", "SQL": "WITH RECURSIVE split(item, rest, loc) AS (SELECT CAST('' AS CHAR(2048)), CONCAT(x.expense_description, ','), e.location FROM expense AS x JOIN budget AS b ON b.budget_id = x.link_to_budget JOIN event AS e ON e.event_id = b.link_to_event WHERE b.amount > 40 UNION ALL SELECT TRIM(SUBSTRING(rest, 1, LOCATE(',', rest) - 1)), SUBSTRING(rest, LOCATE(',', rest) + 1), loc FROM split WHERE rest <> '') SELECT loc AS location, COUNT(DISTINCT item) AS things_bought FROM split WHERE item <> '' GROUP BY loc ORDER BY loc", "difficulty": "challenging"}
{"question_id": 322, "db_id": "student_club", "question": "I'm reconciling what we budgeted for September events against what we actually spent. Can you give me the total amount budgeted for the September 2019 events that served pizza? By September 2019 I mean events dated September 1 through September 30, 2019. An event counts as having served pizza if pizza was among the expenses booked to it. Please include every budget line for those events, whatever the category - not just the food lines. All I need back is the single dollar figure for that total.", "evidence": "A pizza expense means an expense whose description is Pizza.", "SQL": "WITH pizza_events AS (SELECT DISTINCT b.link_to_event AS event_id FROM expense AS e JOIN budget AS b ON e.link_to_budget = b.budget_id WHERE e.expense_description = 'Pizza'), sept_events AS (SELECT event_id FROM event WHERE event_date >= '2019-09-01' AND event_date < '2019-10-01') SELECT ROUND(SUM(b.amount), 2) AS total_budgeted FROM budget AS b JOIN sept_events AS s ON s.event_id = b.link_to_event WHERE b.link_to_event IN (SELECT event_id FROM pizza_events)", "difficulty": "challenging"}
{"question_id": 323, "db_id": "student_club", "question": "Hi - I need one overall figure for the budget next year: what's the average total amount we've actually spent per event, counting all budget categories, across every event we've ever recorded? Please give me the average in dollars, rounded to two decimal places, with no date restriction.", "evidence": "", "SQL": "WITH per_event AS (SELECT e.event_id, COALESCE(SUM(b.spent), 0) AS total_spent FROM event AS e LEFT JOIN budget AS b ON b.link_to_event = e.event_id GROUP BY e.event_id) SELECT ROUND(AVG(total_spent), 2) AS average_total_spent_per_event FROM per_event", "difficulty": "challenging"}
{"question_id": 324, "db_id": "student_club", "question": "Among our closed events that stayed within budget (total spending not exceeding total budget), which one had the most purchases? Please give me just that event's name. Consider every closed event that didn't go over budget, including events with no purchases at all. If two events tie for the most purchases, report only the one with the alphabetically first event ID.", "evidence": "A purchase is a single item recorded on an expense record; one expense record may list several items. Total budget is the sum of budgeted amounts across all budget lines of the event; total spending is the sum of spent amounts across all budget lines of the event.", "SQL": "WITH budget_totals AS (SELECT link_to_event, SUM(spent) AS total_spending, SUM(amount) AS total_budget FROM budget GROUP BY link_to_event), items AS (SELECT b.link_to_event, SUM(CHAR_LENGTH(x.expense_description) - CHAR_LENGTH(REPLACE(x.expense_description, ',', '')) + 1) AS purchases FROM expense AS x JOIN budget AS b ON b.budget_id = x.link_to_budget GROUP BY b.link_to_event) SELECT e.event_name FROM event AS e LEFT JOIN budget_totals AS bt ON bt.link_to_event = e.event_id LEFT JOIN items AS i ON i.link_to_event = e.event_id WHERE e.status = 'Closed' AND (bt.total_budget IS NULL OR bt.total_spending <= bt.total_budget) GROUP BY e.event_id, e.event_name ORDER BY COALESCE(MAX(i.purchases), 0) DESC, e.event_id LIMIT 1", "difficulty": "challenging"}
{"question_id": 325, "db_id": "student_club", "question": "For our year-end review, I want to know which event formats bring in the most people. Looking at our whole club year (every event from September 2019 through May 2020), which event type was attended by the most members, and how many members attended that type's events? If several event types tie for the most, list every one of them. Just give me the event type and the number of members for it - nothing else.", "evidence": "By \"attended\" I mean a member coming to an event; event type is the kind of event, e.g. Meeting, Social, Game, Election, Community Service.", "SQL": "WITH member_counts AS (SELECT e.type AS event_type, COUNT(DISTINCT a.link_to_member) AS members FROM event AS e LEFT JOIN attendance AS a ON a.link_to_event = e.event_id GROUP BY e.type) SELECT event_type, members FROM member_counts WHERE members = (SELECT MAX(members) FROM member_counts) ORDER BY event_type", "difficulty": "challenging"}
{"question_id": 326, "db_id": "student_club", "question": "I'm putting together next semester's purchasing plan and want to know which food and drink item the club buys most often. Among purchases made under the food budget only, which single item appears on the most purchase records, and how many purchase records mention it? If two items are tied, go with the one whose name comes first alphabetically. Please give me just the item's name and that record count.", "evidence": "A purchase record is an entry in the club's expense records for money spent on a purchase.", "SQL": "WITH RECURSIVE items(expense_id, item, rest) AS (SELECT e.expense_id, CAST('' AS CHAR(2048)), CONCAT(e.expense_description, ',') FROM expense AS e JOIN budget AS b ON e.link_to_budget = b.budget_id WHERE b.category = 'Food' UNION ALL SELECT expense_id, TRIM(SUBSTRING(rest, 1, LOCATE(',', rest) - 1)), SUBSTRING(rest, LOCATE(',', rest) + 1) FROM items WHERE rest <> '') SELECT item AS item_name, COUNT(DISTINCT expense_id) AS record_count FROM items WHERE item <> '' GROUP BY item ORDER BY record_count DESC, item LIMIT 1", "difficulty": "challenging"}
{"question_id": 327, "db_id": "student_club", "question": "I'm wrapping up the October Meeting and need the final numbers broken down by what we actually bought, not just by budget category. For every item bought with approved money for the October Meeting, can you give me: the item's name, the budget category of the purchase that included the item, and the total cost in dollars of the approved October Meeting purchases that included the item? Only expenses marked as approved count - an expense without an approval mark doesn't. If an item was included in approved purchases recorded under more than one budget category, give me one row per category. Costs should be plain sums in US dollars with no rounding, and please sort the list by category and then by item name.", "evidence": "An item is a single thing bought with club money, such as water, pizza or posters. A purchase is an expense recorded for the event.", "SQL": "WITH RECURSIVE split AS (SELECT link_to_budget AS bid, cost, CAST('' AS CHAR(2048)) AS item, CONCAT(expense_description, ',') AS rest FROM expense WHERE approved = 'true' UNION ALL SELECT bid, cost, TRIM(SUBSTRING(rest, 1, LOCATE(',', rest) - 1)), SUBSTRING(rest, LOCATE(',', rest) + 1) FROM split WHERE rest <> '') SELECT s.item AS item, b.category AS category, SUM(s.cost) AS total_cost FROM split AS s JOIN budget AS b ON s.bid = b.budget_id JOIN event AS e ON b.link_to_event = e.event_id WHERE s.item <> '' AND e.event_name = 'October Meeting' GROUP BY s.item, b.category ORDER BY b.category COLLATE utf8mb4_bin, s.item COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 328, "db_id": "student_club", "question": "For every event in the club's records, can you give me the event name, event date, total amount budgeted for the event, and the number of members who attended it? Please sort the list by event name, then by event date, both in ascending order.", "evidence": "", "SQL": "SELECT e.event_name, e.event_date, COALESCE(b.total_budgeted_amount, 0) AS total_budgeted_amount, COALESCE(a.attendee_count, 0) AS attendee_count FROM event AS e LEFT JOIN (SELECT link_to_event, SUM(amount) AS total_budgeted_amount FROM budget GROUP BY link_to_event) AS b ON b.link_to_event = e.event_id LEFT JOIN (SELECT link_to_event, COUNT(*) AS attendee_count FROM attendance GROUP BY link_to_event) AS a ON a.link_to_event = e.event_id ORDER BY e.event_name ASC, e.event_date ASC", "difficulty": "challenging"}
{"question_id": 329, "db_id": "student_club", "question": "I'm preparing the year-end audit of club spending. For each item Sacha Harrison bought with club money, I need the item name and how many times she bought it. Can you give me that list?", "evidence": "By \"item\" I mean an individual thing named in a record of what money was spent for.", "SQL": "WITH RECURSIVE split(rest, item) AS (SELECT CONCAT(expense_description, ','), CAST('' AS CHAR(2048)) FROM expense WHERE link_to_member = (SELECT member_id FROM member WHERE first_name = 'Sacha' AND last_name = 'Harrison') UNION ALL SELECT SUBSTRING(rest, LOCATE(',', rest) + 1), TRIM(SUBSTRING(rest, 1, LOCATE(',', rest) - 1)) FROM split WHERE rest <> '') SELECT item, COUNT(*) AS times FROM split WHERE item <> '' GROUP BY item ORDER BY item COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 330, "db_id": "student_club", "question": "I'm putting together the end-of-term spending review. Who bought the most different kinds of items in October or November 2019? Please give me that member's full name, how many different kinds of items they bought in those two months, and their total spending in dollars over the same period. If two members tie for the most kinds, list every tied member with their kind count and spending.", "evidence": "An item is one of the individual things a purchase covered, such as a pizza or a bottle of water.", "SQL": "WITH RECURSIVE split AS (SELECT link_to_member, expense_description AS rest FROM expense WHERE expense_date BETWEEN '2019-10-01' AND '2019-11-30' UNION ALL SELECT link_to_member, SUBSTRING(rest, LOCATE(',', CONCAT(rest, ',')) + 1) FROM split WHERE rest <> ''), items AS (SELECT link_to_member, TRIM(SUBSTRING(rest, 1, LOCATE(',', CONCAT(rest, ',')) - 1)) AS item FROM split WHERE rest <> ''), kinds AS (SELECT link_to_member, COUNT(DISTINCT item) AS kind_count FROM items GROUP BY link_to_member), spend AS (SELECT link_to_member, SUM(cost) AS total_spending FROM expense WHERE expense_date BETWEEN '2019-10-01' AND '2019-11-30' GROUP BY link_to_member) SELECT CONCAT(m.first_name, ' ', m.last_name) AS full_name, k.kind_count, s.total_spending FROM kinds AS k JOIN spend AS s ON s.link_to_member = k.link_to_member JOIN member AS m ON m.member_id = k.link_to_member WHERE k.kind_count = (SELECT MAX(kind_count) FROM kinds)", "difficulty": "challenging"}
{"question_id": 331, "db_id": "student_club", "question": "For our department report, I need to know how many different fields of study our club members from the Political Science Department represent. Only count members of the Political Science Department - members from other departments don't count. Just give me the number of different majors studied by those members.", "evidence": "A major is a field of study offered by a department.", "SQL": "SELECT COUNT(DISTINCT T2.major_id) AS different_majors FROM member AS T1 INNER JOIN major AS T2 ON T1.link_to_major = T2.major_id WHERE T2.department = 'Political Science Department'", "difficulty": "challenging"}
{"question_id": 332, "db_id": "superhero", "question": "Among Marvel Comics superheroes with a known eye colour, rank the eye colours by number of superheroes. Give each colour, its hero count, and its rank, most common first; break display-order ties alphabetically.", "evidence": "", "SQL": "WITH colour_counts AS (SELECT c.colour AS eye_colour, COUNT(*) AS hero_count FROM superhero AS s JOIN colour AS c ON c.id = s.eye_colour_id JOIN publisher AS p ON p.id = s.publisher_id WHERE p.publisher_name = 'Marvel Comics' AND c.colour <> 'No Colour' GROUP BY c.colour) SELECT eye_colour, hero_count, RANK() OVER (ORDER BY hero_count DESC) AS popularity_rank FROM colour_counts ORDER BY hero_count DESC, eye_colour", "difficulty": "moderate"}
{"question_id": 333, "db_id": "superhero", "question": "List the superheroes from Marvel Comics who have the super power of 'Super Strength'.", "evidence": "", "SQL": "SELECT superhero_name FROM superhero AS T1 WHERE EXISTS(SELECT 1 FROM hero_power AS T2 INNER JOIN superpower AS T3 ON T2.power_id = T3.id WHERE T3.power_name = 'Super Strength' AND T1.id = T2.hero_id) AND EXISTS(SELECT 1 FROM publisher AS T4 WHERE T4.publisher_name = 'Marvel Comics' AND T1.publisher_id = T4.id)", "difficulty": "challenging"}
{"question_id": 334, "db_id": "superhero", "question": "What percentage of all superheroes have Neutral alignment, and how many of those Neutral superheroes were published by Marvel Comics? Round the percentage to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN a.alignment = 'Neutral' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2), SUM(CASE WHEN a.alignment = 'Neutral' AND p.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) FROM superhero AS s LEFT JOIN alignment AS a ON a.id = s.alignment_id LEFT JOIN publisher AS p ON p.id = s.publisher_id", "difficulty": "challenging"}
{"question_id": 335, "db_id": "superhero", "question": "Between Marvel Comics and DC Comics, which publisher has more superheroes, and by how many?", "evidence": "", "SQL": "WITH counts AS (SELECT SUM(CASE WHEN p.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) AS marvel_count, SUM(CASE WHEN p.publisher_name = 'DC Comics' THEN 1 ELSE 0 END) AS dc_count FROM superhero AS s JOIN publisher AS p ON p.id = s.publisher_id) SELECT CASE WHEN marvel_count > dc_count THEN 'Marvel Comics' WHEN dc_count > marvel_count THEN 'DC Comics' ELSE 'Tie' END, ABS(marvel_count - dc_count) FROM counts", "difficulty": "challenging"}
{"question_id": 336, "db_id": "superhero", "question": "Among superheroes from 170 through 190 cm tall whose recorded eye-colour category is unknown, list their names.", "evidence": "", "SQL": "SELECT DISTINCT T1.superhero_name FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.eye_colour_id = T2.id WHERE T1.height_cm BETWEEN 170 AND 190 AND T2.colour = 'No Colour'", "difficulty": "moderate"}
{"question_id": 337, "db_id": "superhero", "question": "Among all superheroes with recorded height from 150 through 180 cm, what percentage were published by Marvel Comics? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN p.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM superhero AS s LEFT JOIN publisher AS p ON p.id = s.publisher_id WHERE s.height_cm BETWEEN 150 AND 180", "difficulty": "challenging"}
{"question_id": 338, "db_id": "superhero", "question": "What known full names belong to superheroes tied for the highest strength attribute value?", "evidence": "", "SQL": "SELECT DISTINCT s.full_name FROM superhero AS s JOIN hero_attribute AS ha ON ha.hero_id = s.id JOIN attribute AS a ON a.id = ha.attribute_id WHERE a.attribute_name = 'Strength' AND ha.attribute_value = (SELECT MAX(ha2.attribute_value) FROM hero_attribute AS ha2 JOIN attribute AS a2 ON a2.id = ha2.attribute_id WHERE a2.attribute_name = 'Strength') AND NOT s.full_name IS NULL AND s.full_name <> '-' ORDER BY s.full_name ASC", "difficulty": "moderate"}
{"question_id": 339, "db_id": "superhero", "question": "List superheroes whose known eye, hair and skin colours are all the same, along with any recorded publisher name.", "evidence": "", "SQL": "SELECT s.superhero_name, p.publisher_name FROM superhero AS s LEFT JOIN publisher AS p ON p.id = s.publisher_id JOIN colour AS c ON c.id = s.eye_colour_id WHERE s.eye_colour_id = s.hair_colour_id AND s.eye_colour_id = s.skin_colour_id AND c.colour <> 'No Colour'", "difficulty": "challenging"}
{"question_id": 340, "db_id": "superhero", "question": "Among all female superheroes, what percentage have blue skin? Round to two decimals.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN co.colour = 'Blue' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM superhero AS s JOIN gender AS g ON g.id = s.gender_id LEFT JOIN colour AS co ON co.id = s.skin_colour_id WHERE g.gender = 'Female'", "difficulty": "challenging"}
{"question_id": 341, "db_id": "superhero", "question": "Among all female superheroes, what percentage were published by Marvel Comics? Round to two decimal places.", "evidence": "", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN p.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM superhero AS s JOIN gender AS g ON s.gender_id = g.id LEFT JOIN publisher AS p ON s.publisher_id = p.id WHERE g.gender = 'Female'", "difficulty": "challenging"}
{"question_id": 342, "db_id": "superhero", "question": "Which publisher has more superheroes, DC Comics or Marvel Comics, and by how many? Return Tie if their counts are equal.", "evidence": "", "SQL": "WITH counts AS (SELECT SUM(CASE WHEN p.publisher_name = 'DC Comics' THEN 1 ELSE 0 END) AS dc, SUM(CASE WHEN p.publisher_name = 'Marvel Comics' THEN 1 ELSE 0 END) AS marvel FROM superhero AS s JOIN publisher AS p ON p.id = s.publisher_id) SELECT CASE WHEN dc > marvel THEN 'DC Comics' WHEN marvel > dc THEN 'Marvel Comics' ELSE 'Tie' END, ABS(dc - marvel) FROM counts", "difficulty": "challenging"}
{"question_id": 343, "db_id": "superhero", "question": "I'm comparing Marvel and DC rosters and want to quantify how tall Marvel's roster is for characters whose abilities DC cannot match. What is the average height, in centimetres, of Marvel Comics characters who have at least one power that no DC Comics character has? Only characters with a measured height count.", "evidence": "A \"power\" is any single ability listed for a character in the database.", "SQL": "SELECT AVG(CAST(s.height_cm AS DOUBLE)) AS average_height_cm FROM superhero AS s JOIN publisher AS p ON s.publisher_id = p.id WHERE p.publisher_name = 'Marvel Comics' AND s.height_cm > 0 AND EXISTS(SELECT 1 FROM hero_power AS hp WHERE hp.hero_id = s.id AND NOT EXISTS(SELECT 1 FROM hero_power AS hp2 JOIN superhero AS s2 ON s2.id = hp2.hero_id JOIN publisher AS p2 ON p2.id = s2.publisher_id WHERE p2.publisher_name = 'DC Comics' AND hp2.power_id = hp.power_id))", "difficulty": "challenging"}
{"question_id": 344, "db_id": "superhero", "question": "For a segment on strength heroes, I want to know how many superpowers are held only by heroes who have Super Strength. A power counts as held only if at least one hero who has Super Strength holds it, and Super Strength itself should be included if it meets that condition. Just give me the count.", "evidence": "Super Strength is a super power name.", "SQL": "WITH strength_heroes AS (SELECT hp.hero_id FROM hero_power AS hp INNER JOIN superpower AS sp ON hp.power_id = sp.id WHERE sp.power_name = 'Super Strength') SELECT COUNT(*) AS power_count FROM superpower AS s WHERE EXISTS(SELECT 1 FROM hero_power AS hp WHERE hp.power_id = s.id AND hp.hero_id IN (SELECT hero_id FROM strength_heroes)) AND NOT EXISTS(SELECT 1 FROM hero_power AS hp2 WHERE hp2.power_id = s.id AND NOT hp2.hero_id IN (SELECT hero_id FROM strength_heroes))", "difficulty": "challenging"}
{"question_id": 345, "db_id": "superhero", "question": "I'm setting a typical weight for a green-skinned creature class. Can you tell me the average weight in kg of the heroes with green skin? Count only heroes whose weight is known, and give me one number rounded to one decimal place.", "evidence": "Green skin means the hero's skin colour is green.", "SQL": "SELECT ROUND(AVG(T1.weight_kg), 1) AS average_weight_kg FROM superhero AS T1 INNER JOIN colour AS T2 ON T1.skin_colour_id = T2.id WHERE T2.colour = 'Green' AND T1.weight_kg > 0", "difficulty": "challenging"}
{"question_id": 346, "db_id": "superhero", "question": "I'm writing an article about heroes who fall outside the classic good-versus-evil divide. How many superheroes in the database have an alignment that is neither good nor bad? Please give me just that count. Note that this should cover all superheroes in the database.", "evidence": "good: a superhero whose alignment is Good; bad: a superhero whose alignment is Bad; alignment: the moral category assigned to a superhero", "SQL": "SELECT COUNT(*) AS neither_good_nor_bad FROM superhero AS s LEFT JOIN alignment AS a ON s.alignment_id = a.id WHERE a.alignment IS NULL OR NOT a.alignment IN ('Good', 'Bad')", "difficulty": "challenging"}
{"question_id": 347, "db_id": "superhero", "question": "I'm building a fact box on Marvel heroes' civilian identities. Among Marvel Comics superheroes whose full name (their civilian identity, like 'Richard Milhouse Jones') is known, which superpower is the most common, and how many of those heroes have it? If several superpowers tie for most common, list all of them with their counts. Just give me the superpower name(s) and the counts.", "evidence": "", "SQL": "WITH pc AS (SELECT sp.power_name, COUNT(DISTINCT hp.hero_id) AS hero_count FROM hero_power AS hp JOIN superpower AS sp ON hp.power_id = sp.id JOIN superhero AS s ON hp.hero_id = s.id JOIN publisher AS p ON s.publisher_id = p.id WHERE p.publisher_name = 'Marvel Comics' AND NOT s.full_name IS NULL AND s.full_name <> '-' GROUP BY sp.power_name) SELECT power_name, hero_count FROM pc WHERE hero_count = (SELECT MAX(hero_count) FROM pc) ORDER BY power_name", "difficulty": "challenging"}
{"question_id": 348, "db_id": "superhero", "question": "I want to profile the cohort of heroes whose Intelligence score matches Abomination's Intelligence score. What is their average measured weight in kg? Please round the average to two decimals.", "evidence": "Intelligence is one of the six attribute scores a hero has (Intelligence, Strength, Speed, Durability, Power, Combat)", "SQL": "SELECT ROUND(AVG(CASE WHEN s.weight_kg > 0 THEN s.weight_kg END), 2) AS average_weight_kg FROM superhero AS s JOIN hero_attribute AS ha ON ha.hero_id = s.id JOIN attribute AS a ON a.id = ha.attribute_id WHERE a.attribute_name = 'Intelligence' AND ha.attribute_value = (SELECT abom_ha.attribute_value FROM superhero AS abom JOIN hero_attribute AS abom_ha ON abom_ha.hero_id = abom.id JOIN attribute AS abom_a ON abom_a.id = abom_ha.attribute_id WHERE abom.superhero_name = 'Abomination' AND abom_a.attribute_name = 'Intelligence')", "difficulty": "challenging"}
{"question_id": 349, "db_id": "superhero", "question": "I'm putting together a trivia page profiling blue-haired heroes by their abilities. For each gender, male and female, how many blue-haired superheroes have at least ten listed powers? I need the count for both groups, and by 'at least ten' I mean ten or more.", "evidence": "Listed powers: the superpowers recorded for a hero.", "SQL": "SELECT g.gender AS gender, COUNT(s.id) AS superhero_count FROM gender AS g LEFT JOIN superhero AS s ON s.gender_id = g.id AND s.hair_colour_id = (SELECT id FROM colour WHERE colour = 'Blue') AND (SELECT COUNT(*) FROM hero_power AS hp WHERE hp.hero_id = s.id) >= 10 WHERE g.gender IN ('Male', 'Female') GROUP BY g.gender ORDER BY g.gender", "difficulty": "challenging"}
{"question_id": 350, "db_id": "superhero", "question": "I'm putting together a comparison of the heaviest brick-strength characters. What is the average weight, in kilograms, of all superheroes whose Strength score equals the Hulk's? I just need a single integer rounded to the nearest kilogram. Include every superhero in the database, no restrictions on publisher or alignment. If a hero's weight is unknown, leave them out and average only over the heroes whose weight has actually been measured.", "evidence": "Strength is one of the six measured hero attributes, each scored on a 1-100 scale; the Hulk is the superhero named 'Hulk'; weight is the superhero's weight in kilograms.", "SQL": "SELECT CAST(ROUND(AVG(s.weight_kg)) AS SIGNED) AS average_weight_kg FROM superhero AS s INNER JOIN hero_attribute AS ha ON ha.hero_id = s.id INNER JOIN attribute AS a ON a.id = ha.attribute_id WHERE a.attribute_name = 'Strength' AND ha.attribute_value = (SELECT ha2.attribute_value FROM superhero AS s2 INNER JOIN hero_attribute AS ha2 ON ha2.hero_id = s2.id INNER JOIN attribute AS a2 ON a2.id = ha2.attribute_id WHERE s2.superhero_name = 'Hulk' AND a2.attribute_name = 'Strength') AND s.weight_kg > 0", "difficulty": "challenging"}
{"question_id": 351, "db_id": "superhero", "question": "For my 'giants of the genre' feature, I want to headline how varied the abilities of the tallest heroes are. How many different superpowers appear among the ten tallest superheroes? Rank heroes by height and take the top ten; if several heroes tie at the tenth-tallest height, include all of them. A hero counts among the ten tallest even if no powers are on file for them. Please give me just that single number.", "evidence": "superpower = an ability such as Agility or Accelerated Healing, as named in the superpower list", "SQL": "WITH top10 AS (SELECT id FROM superhero ORDER BY height_cm DESC LIMIT 10) SELECT COUNT(DISTINCT T3.power_name) AS superpowers FROM top10 JOIN hero_power AS T2 ON top10.id = T2.hero_id JOIN superpower AS T3 ON T2.power_id = T3.id", "difficulty": "challenging"}
{"question_id": 352, "db_id": "superhero", "question": "How many characters published by A-Bomb's publisher have no race listed? I just need a single count. (By A-Bomb's publisher, I mean the publisher that publishes the character A-Bomb.)", "evidence": "race: the character's race or group, e.g. Human, Alien, Mutant", "SQL": "SELECT COUNT(*) AS character_count FROM superhero WHERE publisher_id = (SELECT publisher_id FROM superhero WHERE superhero_name = 'A-Bomb') AND (race_id IS NULL OR race_id = (SELECT id FROM race WHERE race = '-'))", "difficulty": "challenging"}
{"question_id": 353, "db_id": "superhero", "question": "Hey, following up on my count of the God / Eternal heroes – among those who are male, what's the average number of superpowers per hero? Just give me the average rounded to two decimal places.", "evidence": "A superpower is any power linked to a hero.", "SQL": "WITH power_counts AS (SELECT s.id, (SELECT COUNT(*) FROM hero_power AS hp WHERE hp.hero_id = s.id) AS power_count FROM superhero AS s INNER JOIN race AS r ON s.race_id = r.id INNER JOIN gender AS g ON s.gender_id = g.id WHERE r.race = 'God / Eternal' AND g.gender = 'Male') SELECT ROUND(AVG(power_count), 2) AS average_superpowers FROM power_counts", "difficulty": "challenging"}
{"question_id": 354, "db_id": "superhero", "question": "For my cryokinesis page, I want to know how broad the power portfolios are around ice-powered heroes. Consider all heroes who share at least one superpower with a cryokinesis holder - including the cryokinesis holders themselves, since they share cryokinesis with each other. What is the average number of superpowers these heroes have, rounded to one decimal place? Please send back just that single number.", "evidence": "Cryokinesis is the superpower to generate and control ice.", "SQL": "WITH sharers AS (SELECT DISTINCT hp2.hero_id FROM hero_power AS hp1 JOIN hero_power AS hp2 ON hp2.power_id = hp1.power_id WHERE hp1.hero_id IN (SELECT hero_id FROM hero_power WHERE power_id = (SELECT id FROM superpower WHERE power_name = 'Cryokinesis'))), counts AS (SELECT hero_id, COUNT(*) AS cnt FROM hero_power WHERE hero_id IN (SELECT hero_id FROM sharers) GROUP BY hero_id) SELECT ROUND(AVG(cnt), 1) AS avg_superpower_count FROM counts", "difficulty": "challenging"}
{"question_id": 355, "db_id": "superhero", "question": "What is the average weight in kilograms of the DC Comics heroes whose eye colour is also shared by at least one Marvel Comics hero? Leave out any heroes whose weight is unknown, round the result to the nearest kilogram, and treat 'No Colour' as an eye colour like any other when matching between publishers. I just want that single number.", "evidence": "", "SQL": "SELECT ROUND(AVG(CASE WHEN s.weight_kg > 0 THEN s.weight_kg END)) AS average_weight_kg FROM superhero AS s JOIN publisher AS p ON s.publisher_id = p.id WHERE p.publisher_name = 'DC Comics' AND s.eye_colour_id IN (SELECT s2.eye_colour_id FROM superhero AS s2 JOIN publisher AS p2 ON s2.publisher_id = p2.id WHERE p2.publisher_name = 'Marvel Comics')", "difficulty": "challenging"}
{"question_id": 356, "db_id": "superhero", "question": "I'm researching heroes like A-Bomb. What is the average height in centimetres of the superheroes in A-Bomb's group? Please give me just that single number, rounded to one decimal place. Note that A-Bomb itself belongs to its group and should be included, and only heroes whose height is actually on record should count toward the average-anyone without a recorded height should be left out rather than counted as some height.", "evidence": "In this request, \"group\" refers to race.", "SQL": "SELECT ROUND(AVG(CASE WHEN height_cm > 0 THEN height_cm END), 1) AS average_height_cm FROM superhero WHERE race_id = (SELECT race_id FROM superhero WHERE superhero_name = 'A-Bomb')", "difficulty": "challenging"}
{"question_id": 357, "db_id": "superhero", "question": "What is the average weight, in kg, of the heroes who belong to races in which no hero is female? Heroes whose weight is not recorded should not count toward the average. I just need that single value.", "evidence": "female: the hero's gender is female", "SQL": "SELECT AVG(CAST(T1.weight_kg AS DOUBLE)) AS average_weight_kg FROM superhero AS T1 INNER JOIN race AS T2 ON T1.race_id = T2.id WHERE T1.weight_kg > 0 AND NOT EXISTS(SELECT 1 FROM superhero AS T3 INNER JOIN gender AS T4 ON T3.gender_id = T4.id WHERE T3.race_id = T2.id AND T4.gender = 'Female')", "difficulty": "challenging"}
{"question_id": 358, "db_id": "superhero", "question": "I'm writing a piece about which real publishing companies have put out very tall heroes. How many publishers in the database have released at least one hero taller than 200 cm? Note that taller than 200 cm means strictly more than 200 cm, and it counts if even one of their heroes is that tall. I just need the number of publishers, nothing else.", "evidence": "A hero's publisher being 'released' means the publisher the hero is attributed to in the database.", "SQL": "SELECT COUNT(DISTINCT T1.publisher_id) AS publisher_count FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id WHERE T1.height_cm > 200 AND T2.publisher_name <> ''", "difficulty": "challenging"}
{"question_id": 359, "db_id": "superhero", "question": "For a licensing survey of non-DC heroic characters, I need a single total count of superheroes whose alignment is Good and who are not published by DC Comics. Just that one number, please.", "evidence": "Good means the hero's alignment is Good; DC Comics means the publisher named DC Comics.", "SQL": "SELECT COUNT(*) AS hero_count FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id WHERE T2.alignment = 'Good' AND NOT EXISTS(SELECT 1 FROM publisher AS T3 WHERE T3.id = T1.publisher_id AND T3.publisher_name = 'DC Comics')", "difficulty": "challenging"}
{"question_id": 360, "db_id": "superhero", "question": "I'm comparing superhero body weights to typical human weights for an article. What is the average weight in kilograms of superheroes published by DC Comics, rounded to one decimal place, and how many DC Comics superheroes is that average based on? Only superheroes with a known weight should count toward the average, so the count should be the number of superheroes it's based on. DC Comics means the publisher named DC Comics.", "evidence": "", "SQL": "SELECT ROUND(AVG(s.weight_kg), 1) AS avg_weight_kg, COUNT(*) AS hero_count FROM superhero AS s JOIN publisher AS p ON s.publisher_id = p.id WHERE p.publisher_name = 'DC Comics' AND s.weight_kg > 0", "difficulty": "challenging"}
{"question_id": 361, "db_id": "superhero", "question": "How many heroes published by Blackwulf's publisher have an eye colour that at least one hero from a different publisher also has? By \"that publisher's heroes\" I mean all of its heroes, not just Blackwulf. A different publisher means any other publisher, and heroes with no publisher listed shouldn't count as coming from a different publisher. I just want that single count back.", "evidence": "Eye colour: the colour of a hero's eyes as catalogued for that hero.", "SQL": "WITH blk AS (SELECT publisher_id AS pid FROM superhero WHERE superhero_name = 'Blackwulf') SELECT COUNT(*) AS hero_count FROM superhero AS m WHERE m.publisher_id = (SELECT pid FROM blk) AND m.eye_colour_id IN (SELECT d.eye_colour_id FROM superhero AS d WHERE NOT d.publisher_id IS NULL AND d.publisher_id <> (SELECT pid FROM blk))", "difficulty": "challenging"}
{"question_id": 362, "db_id": "superhero", "question": "Which race is the most common among the superheroes published by the same publisher as the superhero whose full name is Charles Chandler? I'd like, for that publisher's superheroes only, the name of the most common race and the count of that publisher's superheroes of that race. Ignore any superhero with no race recorded. If several races tie for most common, list every tied race with its count.", "evidence": "Race: the superhero's species or type, e.g. Human, Mutant, Alien.", "SQL": "WITH counts AS (SELECT r.race AS race, COUNT(*) AS hero_count FROM superhero AS s INNER JOIN race AS r ON s.race_id = r.id WHERE s.publisher_id = (SELECT publisher_id FROM superhero WHERE full_name = 'Charles Chandler') AND r.race <> '-' GROUP BY r.id, r.race) SELECT race, hero_count FROM counts WHERE hero_count = (SELECT MAX(hero_count) FROM counts)", "difficulty": "challenging"}
{"question_id": 363, "db_id": "superhero", "question": "What is the average weight in kg of the Female heroes in the database? Round it to two decimal places, and skip any heroes whose weight is unknown. I just need that single number.", "evidence": "kg: kilograms", "SQL": "SELECT ROUND(AVG(weight_kg), 2) AS average_weight_kg FROM superhero WHERE gender_id = (SELECT id FROM gender WHERE gender = 'Female') AND weight_kg > 0", "difficulty": "challenging"}
{"question_id": 364, "db_id": "superhero", "question": "I'm writing a power-profile feature on heroes with super speed or death touch. Can you give me one number: the average intelligence score of the superheroes who have either of those powers? Round it to one decimal place, and only count the heroes who actually have an intelligence score in the database.", "evidence": "\"Super speed\" and \"death touch\" are superpower names as used in the database; \"intelligence\" is the hero attribute by that name.", "SQL": "SELECT ROUND(AVG(v), 1) AS average_intelligence FROM (SELECT DISTINCT T1.id, T4.attribute_value AS v FROM superhero AS T1 INNER JOIN hero_power AS T2 ON T1.id = T2.hero_id INNER JOIN superpower AS T3 ON T2.power_id = T3.id INNER JOIN hero_attribute AS T4 ON T4.hero_id = T1.id INNER JOIN attribute AS T5 ON T4.attribute_id = T5.id WHERE T3.power_name IN ('Super Speed', 'Death Touch') AND T5.attribute_name = 'Intelligence') AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 365, "db_id": "superhero", "question": "I'm comparing how power-rich male and female heroes are. For all male heroes and all female heroes that have a documented real full name, what is the average number of superpowers per hero for each gender? Please compute each average over the entire hero population of that gender, not just the heroes that happen to have power records. Give me both averages, each rounded to two decimal places, and nothing else.", "evidence": "Full name: the hero's real, full personal name (first name plus last name, and optionally middle names); single names such as mononyms or aliases are not a full name.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN g.gender = 'Male' THEN COALESCE(pc.cnt, 0) ELSE 0 END) AS FLOAT) / SUM(CASE WHEN g.gender = 'Male' THEN 1 ELSE 0 END), 2) AS avg_superpowers_male, ROUND(CAST(SUM(CASE WHEN g.gender = 'Female' THEN COALESCE(pc.cnt, 0) ELSE 0 END) AS FLOAT) / SUM(CASE WHEN g.gender = 'Female' THEN 1 ELSE 0 END), 2) AS avg_superpowers_female FROM superhero AS s INNER JOIN gender AS g ON s.gender_id = g.id LEFT JOIN (SELECT hero_id, COUNT(*) AS cnt FROM hero_power GROUP BY hero_id) AS pc ON pc.hero_id = s.id WHERE s.full_name LIKE '% %'", "difficulty": "challenging"}
{"question_id": 366, "db_id": "superhero", "question": "I'm putting together a physical profile of the green-skinned villain corner of the universe for a fan wiki page. Could you tell me the average height in centimetres and the average weight in kilograms of the green-skinned villains? Please average only over the characters whose measurement is actually on record - a character with no recorded height or weight shouldn't drag the average down - and round each average to two decimals. I just need those two numbers.", "evidence": "By 'villain' I mean a character whose alignment is Bad, and by 'green-skinned' I mean a character whose skin colour is Green. Height in centimetres and weight in kilograms are the character's height_cm and weight_kg as commonly understood physical measurements.", "SQL": "SELECT ROUND(AVG(CASE WHEN T1.height_cm > 0 THEN T1.height_cm END), 2) AS avg_height_cm, ROUND(AVG(CASE WHEN T1.weight_kg > 0 THEN T1.weight_kg END), 2) AS avg_weight_kg FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id INNER JOIN colour AS T3 ON T1.skin_colour_id = T3.id WHERE T2.alignment = 'Bad' AND T3.colour = 'Green'", "difficulty": "challenging"}
{"question_id": 367, "db_id": "superhero", "question": "I'm profiling publisher rosters and now want to look at the physical build of George Lucas's heroes. What is the average height of the heroes he created, in centimetres, and their average weight, in kilograms? Please round each average to one decimal place, and only include heroes whose height (for the height average) or weight (for the weight average) is actually known.", "evidence": "", "SQL": "SELECT ROUND(AVG(CASE WHEN s.height_cm > 0 THEN s.height_cm END), 1) AS average_height_cm, ROUND(AVG(CASE WHEN s.weight_kg > 0 THEN s.weight_kg END), 1) AS average_weight_kg FROM superhero AS s INNER JOIN publisher AS p ON s.publisher_id = p.id WHERE p.publisher_name = 'George Lucas'", "difficulty": "challenging"}
{"question_id": 368, "db_id": "superhero", "question": "I'd like to know how tall the heroes are who share at least one superpower with 3-D Man. Can you give me the average height in centimetres of those heroes, rounded to one decimal place? Please leave 3-D Man himself out of it, and don't count heroes whose height isn't known.", "evidence": "", "SQL": "SELECT ROUND(AVG(s.height_cm), 1) AS avg_height_cm FROM superhero AS s WHERE s.height_cm > 0 AND s.id <> (SELECT id FROM superhero WHERE superhero_name = '3-D Man') AND s.id IN (SELECT hp2.hero_id FROM hero_power AS hp2 WHERE hp2.power_id IN (SELECT power_id FROM hero_power WHERE hero_id = (SELECT id FROM superhero WHERE superhero_name = '3-D Man')))", "difficulty": "challenging"}
{"question_id": 369, "db_id": "superhero", "question": "I'm writing an article about green-skinned flying villains and need a body-statistics fact. What is the average weight, in kilograms, of all green-skinned villains who can fly? By villain I mean a character whose moral affiliation is Bad. Please include only characters whose weight was actually measured-any character whose weight was never measured should be left out of the average. Give me just the single number, rounded to the nearest kilogram.", "evidence": "Flight: the power to fly.", "SQL": "SELECT ROUND(AVG(CASE WHEN s.weight_kg > 0 THEN s.weight_kg END)) AS average_weight_kg FROM superhero AS s INNER JOIN alignment AS a ON s.alignment_id = a.id INNER JOIN colour AS c ON s.skin_colour_id = c.id INNER JOIN hero_power AS hp ON hp.hero_id = s.id INNER JOIN superpower AS sp ON sp.id = hp.power_id WHERE a.alignment = 'Bad' AND c.colour = 'Green' AND sp.power_name = 'Flight'", "difficulty": "challenging"}
{"question_id": 370, "db_id": "superhero", "question": "I'm doing a physical-profile breakdown of the George Lucas catalogue. For the heroes published by George Lucas that have at least one superpower in the database, what is their average weight in kilograms, counting only the heroes whose weight is recorded? Please give me just that one number, rounded to two decimal places.", "evidence": "George Lucas refers to the publisher name.", "SQL": "SELECT ROUND(AVG(CASE WHEN s.weight_kg > 0 THEN s.weight_kg END), 2) AS avg_weight_kg FROM superhero AS s INNER JOIN publisher AS p ON s.publisher_id = p.id WHERE p.publisher_name = 'George Lucas' AND EXISTS(SELECT 1 FROM hero_power AS hp WHERE hp.hero_id = s.id)", "difficulty": "challenging"}
{"question_id": 371, "db_id": "superhero", "question": "For the article I'm writing on heroic female characters, I'd like a physique stat for the trivia box: what is the average weight in kilograms of female superheroes whose alignment is good? Only count superheroes whose weight is known. Please round the result to two decimal places.", "evidence": "Alignment: the superhero's moral category, e.g. good, bad, neutral.", "SQL": "SELECT ROUND(AVG(s.weight_kg), 2) AS average_weight_kg FROM superhero AS s JOIN gender AS g ON g.id = s.gender_id JOIN alignment AS a ON a.id = s.alignment_id WHERE g.gender = 'Female' AND a.alignment = 'Good' AND s.weight_kg > 0", "difficulty": "challenging"}
{"question_id": 372, "db_id": "superhero", "question": "I'm picking powers for a lightweight male hero archetype. How many different superpowers are held by at least one male superhero who weighs under 70 kilograms? Heroes whose weight isn't recorded shouldn't count as weighing under 70.", "evidence": "", "SQL": "SELECT COUNT(DISTINCT hp.power_id) AS power_count FROM superhero AS s JOIN hero_power AS hp ON hp.hero_id = s.id JOIN superpower AS sp ON sp.id = hp.power_id JOIN gender AS g ON g.id = s.gender_id WHERE g.gender = 'Male' AND s.weight_kg > 0 AND s.weight_kg < 70", "difficulty": "challenging"}
{"question_id": 373, "db_id": "superhero", "question": "I'm putting together a trivia fact box on tiny heroes. Could you tell me the hair colour of the shortest human superhero? Please treat heroes with no recorded height as unmeasured rather than as being the shortest. I just need the colour, nothing else.", "evidence": "", "SQL": "SELECT DISTINCT c.colour FROM superhero AS s INNER JOIN race AS r ON s.race_id = r.id INNER JOIN colour AS c ON s.hair_colour_id = c.id WHERE r.race = 'Human' AND s.height_cm = (SELECT MIN(x.height_cm) FROM superhero AS x INNER JOIN race AS y ON x.race_id = y.id WHERE y.race = 'Human' AND x.height_cm > 0)", "difficulty": "challenging"}
{"question_id": 374, "db_id": "superhero", "question": "I want to know about the lightest superhero whose weight has actually been recorded. Among all heroes sharing that lightest weight, give me the largest number of superpowers any of them has. If such a hero has no powers, that counts as 0. Please return just that one number.", "evidence": "A superpower is one power a hero has, identified by its name.", "SQL": "SELECT MAX(cnt) AS power_count FROM (SELECT COUNT(hp.power_id) AS cnt FROM superhero AS h LEFT JOIN hero_power AS hp ON h.id = hp.hero_id WHERE h.weight_kg = (SELECT MIN(weight_kg) FROM superhero WHERE weight_kg > 0) GROUP BY h.id) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 375, "db_id": "superhero", "question": "I'm auditing identity info on our hero profile pages. How many neutral-alignment heroes have a known full name? Just give me the count.", "evidence": "By \"full name\" I mean the hero's real-world identity name, not the superhero/costume name.", "SQL": "SELECT COUNT(*) AS neutral_heroes_with_known_full_name FROM superhero AS T1 INNER JOIN alignment AS T2 ON T1.alignment_id = T2.id WHERE T2.alignment = 'Neutral' AND NOT T1.full_name IS NULL AND T1.full_name <> '-'", "difficulty": "challenging"}
{"question_id": 376, "db_id": "superhero", "question": "I'm building a profile page crediting the fastest characters. Among all superheroes that share the top Speed attribute value (everyone tied at the highest Speed value counts), can you list the ones whose real name is known? For each, I need the superhero name and the full name — the civilian identity behind the mask — and nothing else. Please leave out anyone whose real name isn't identifiable.", "evidence": "", "SQL": "SELECT s.superhero_name, s.full_name FROM superhero AS s JOIN hero_attribute AS h ON h.hero_id = s.id JOIN attribute AS a ON a.id = h.attribute_id WHERE a.attribute_name = 'Speed' AND h.attribute_value = (SELECT MAX(h2.attribute_value) FROM hero_attribute AS h2 JOIN attribute AS a2 ON a2.id = h2.attribute_id WHERE a2.attribute_name = 'Speed') AND NOT s.full_name IS NULL AND s.full_name <> '-' ORDER BY s.superhero_name", "difficulty": "challenging"}
{"question_id": 377, "db_id": "superhero", "question": "I'm looking at how designers pair hair and eye colours. For every eye colour that appears on at least one brown-haired hero, how many heroes have that eye colour while their hair is NOT brown? Just give me each eye colour and that count, listing the eye colour with the highest count first. If two eye colours have the same count, the one whose name comes first alphabetically should come first.", "evidence": "By a brown-haired hero I mean a hero whose hair colour is Brown.", "SQL": "WITH cohort AS (SELECT DISTINCT s.eye_colour_id AS eid FROM superhero AS s INNER JOIN colour AS h ON s.hair_colour_id = h.id WHERE h.colour = 'Brown') SELECT c.colour AS eye_colour, COUNT(CASE WHEN h.colour <> 'Brown' THEN 1 END) AS heroes FROM cohort AS t INNER JOIN colour AS c ON c.id = t.eid LEFT JOIN superhero AS s ON s.eye_colour_id = t.eid LEFT JOIN colour AS h ON h.id = s.hair_colour_id GROUP BY c.colour ORDER BY heroes DESC, eye_colour", "difficulty": "challenging"}
{"question_id": 378, "db_id": "superhero", "question": "I'm preparing a report on Marvel's roster and want to gauge how heroic their catalogued heroes are. Among Marvel Comics superheroes whose civilian full name is documented, what percentage are good? Please give me just that single percentage, rounded to two decimal places. Note: the percentage should be taken over all Marvel Comics superheroes with a known full name - those whose moral alignment is unknown still count toward the total, just not as good.", "evidence": "Good refers to alignment = 'Good'. A full name means the hero's real-world civilian identity, i.e. an actual person's name such as 'Charles Chandler' or 'Richard Milhouse Jones'.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN T3.alignment = 'Good' THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(*), 2) AS percentage FROM superhero AS T1 INNER JOIN publisher AS T2 ON T1.publisher_id = T2.id LEFT JOIN alignment AS T3 ON T1.alignment_id = T3.id WHERE T2.publisher_name = 'Marvel Comics' AND NOT T1.full_name IS NULL AND T1.full_name <> '-'", "difficulty": "challenging"}
{"question_id": 379, "db_id": "superhero", "question": "What percentage of Marvel Comics superheroes with a recorded superpower are classified as good? Round the percentage to two decimal places, and give me just that single value.", "evidence": "Good means alignment 'Good'; superpower refers to a hero's recorded power.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN a.alignment = 'Good' THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(*), 2) AS good_percentage FROM superhero AS s JOIN publisher AS p ON s.publisher_id = p.id LEFT JOIN alignment AS a ON s.alignment_id = a.id WHERE p.publisher_name = 'Marvel Comics' AND EXISTS(SELECT 1 FROM hero_power AS hp WHERE hp.hero_id = s.id)", "difficulty": "challenging"}
{"question_id": 380, "db_id": "superhero", "question": "I'm comparing the builds of heroes whose power sets overlap with 3-D Man's. What is the average weight in kg of the heroes other than 3-D Man that share at least one superpower with him? Please round it to two decimal places, leave out any heroes whose weight isn't recorded, and return just that single number.", "evidence": "", "SQL": "SELECT ROUND(AVG(weight_kg), 2) AS average_weight_kg FROM superhero WHERE superhero_name <> '3-D Man' AND weight_kg > 0 AND id IN (SELECT hero_id FROM hero_power WHERE power_id IN (SELECT power_id FROM hero_power WHERE hero_id = (SELECT id FROM superhero WHERE superhero_name = '3-D Man')))", "difficulty": "challenging"}
{"question_id": 381, "db_id": "superhero", "question": "Among superheroes whose weight is not recorded, how many more have the 'No Colour' eye category than have blue eyes? I want a single whole number: the count of 'No Colour' eyes minus the count of blue eyes in that group - it can be negative if blue is more common. Please give me just that one number, with no other results or breakdowns.", "evidence": "'No Colour' is an eye category meaning the hero's eye colour is unspecified.", "SQL": "SELECT SUM(CASE WHEN co.colour = 'No Colour' THEN 1 ELSE 0 END) - SUM(CASE WHEN co.colour = 'Blue' THEN 1 ELSE 0 END) AS diff FROM superhero AS s JOIN colour AS co ON co.id = s.eye_colour_id WHERE s.weight_kg = 0 OR s.weight_kg IS NULL", "difficulty": "challenging"}
{"question_id": 382, "db_id": "thrombosis_prediction", "question": "Among distinct patients with at least one uric-acid result above the sex-specific upper limit, what is the ratio of male to female patients?", "evidence": "For this task, the uric-acid upper limit is 8.0 for males and 6.5 for females.", "SQL": "SELECT CAST(SUM(CASE WHEN p.SEX = 'M' THEN 1 ELSE 0 END) AS FLOAT) / NULLIF(SUM(CASE WHEN p.SEX = 'F' THEN 1 ELSE 0 END), 0) FROM Patient AS p WHERE (p.SEX = 'M' AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.UA > 8.0)) OR (p.SEX = 'F' AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.UA > 6.5))", "difficulty": "challenging"}
{"question_id": 383, "db_id": "thrombosis_prediction", "question": "Across laboratory records with PLT > 400 for female patients whose patient profile lists an SLE diagnosis, what is the average ALB value rounded to four decimal places?", "evidence": "", "SQL": "SELECT ROUND(AVG(CAST(l.ALB AS DECIMAL(10, 4))), 4) FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE l.PLT > 400 AND ((CONCAT(',', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(COALESCE(p.Diagnosis, ''), CHAR(13), ','), CHAR(10), ','), CHAR(29), ','), CHAR(11), ','), ' ', ','), ' ', ''), ',')) LIKE '%,SLE,%' OR (CONCAT(',', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(COALESCE(p.Diagnosis, ''), CHAR(13), ','), CHAR(10), ','), CHAR(29), ','), CHAR(11), ','), ' ', ','), ' ', ''), ',')) LIKE '%,SLE(%') AND p.SEX = 'F'", "difficulty": "moderate"}
{"question_id": 384, "db_id": "thrombosis_prediction", "question": "How many distinct patients with a triglyceride result of at least 200 were older than 50 on 2026-10-09?", "evidence": "", "SQL": "SELECT COUNT(*) FROM Patient AS p WHERE p.Birthday < '1976-10-09' AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.TG >= 200)", "difficulty": "moderate"}
{"question_id": 385, "db_id": "thrombosis_prediction", "question": "List patient IDs, sex, and completed age on 2026-10-09 for patients with at least one laboratory record showing glucose at least 180 and total cholesterol below 250.", "evidence": "", "SQL": "SELECT p.ID, p.SEX, (CAST(SUBSTRING(CAST('2026-10-09' AS CHAR(10)), 1, 4) AS DECIMAL(4, 0)) - CAST(SUBSTRING(CAST(p.Birthday AS CHAR(10)), 1, 4) AS DECIMAL(4, 0)) - CASE WHEN SUBSTRING(CAST('2026-10-09' AS CHAR(10)), 6, 5) < SUBSTRING(CAST(p.Birthday AS CHAR(10)), 6, 5) THEN 1 ELSE 0 END) AS age FROM Patient AS p WHERE NOT p.Birthday IS NULL AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.GLU >= 180 AND l.`T-CHO` < 250) ORDER BY p.ID", "difficulty": "challenging"}
{"question_id": 386, "db_id": "thrombosis_prediction", "question": "List the IDs and completed ages on 2026-10-09 of patients with at least two laboratory results having hematocrit of 52 or higher.", "evidence": "", "SQL": "SELECT p.ID, (CAST(SUBSTRING(CAST('2026-10-09' AS CHAR(10)), 1, 4) AS DECIMAL(4, 0)) - CAST(SUBSTRING(CAST(p.Birthday AS CHAR(10)), 1, 4) AS DECIMAL(4, 0)) - CASE WHEN SUBSTRING(CAST('2026-10-09' AS CHAR(10)), 6, 5) < SUBSTRING(CAST(p.Birthday AS CHAR(10)), 6, 5) THEN 1 ELSE 0 END) AS age FROM Patient AS p JOIN (SELECT ID FROM Laboratory WHERE HCT >= 52 GROUP BY ID HAVING COUNT(*) >= 2) AS qualified ON qualified.ID = p.ID WHERE NOT p.Birthday IS NULL ORDER BY p.ID", "difficulty": "challenging"}
{"question_id": 387, "db_id": "thrombosis_prediction", "question": "Among patients older than 55 on 2026-10-09 who have at least one abnormal PT result, what percentage are female? Round to two decimals.", "evidence": "For this task, PT of at least 14 is abnormal.", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN p.SEX = 'F' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM Patient AS p WHERE p.Birthday < '1971-10-09' AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.PT >= 14)", "difficulty": "challenging"}
{"question_id": 388, "db_id": "thrombosis_prediction", "question": "How many distinct patients have at least one positive CRP laboratory result and no recorded patient description?", "evidence": "Plus-marked CRP results indicate positivity.", "SQL": "SELECT COUNT(DISTINCT p.ID) FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE l.CRP LIKE '%+' AND p.Description IS NULL", "difficulty": "moderate"}
{"question_id": 389, "db_id": "thrombosis_prediction", "question": "How many distinct female patients have a normal anti-Scl-70 result and no recorded non-null symptom on any examination?", "evidence": "Normal anti-Scl-70 is recorded as 'negative' or '0'.", "SQL": "SELECT COUNT(*) FROM Patient AS p WHERE p.SEX = 'F' AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.SC170 IN ('negative', '0')) AND NOT EXISTS(SELECT 1 FROM Examination AS e WHERE e.ID = p.ID AND NOT e.Symptoms IS NULL)", "difficulty": "challenging"}
{"question_id": 390, "db_id": "thrombosis_prediction", "question": "Among patients in the thrombosis registry born between 1930 and 1940 inclusive who had laboratory tests, what percentage were inpatients? Please give me just the percentage rounded to two decimal places.", "evidence": "An inpatient is a patient who was admitted to the hospital; an outpatient is a patient who was followed at the outpatient clinic.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN Admission = '+' THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(*), 2) AS percentage FROM Patient WHERE DATE_FORMAT(Birthday, '%Y') BETWEEN '1930' AND '1940' AND ID IN (SELECT ID FROM Laboratory)", "difficulty": "challenging"}
{"question_id": 391, "db_id": "thrombosis_prediction", "question": "Among the lab tests with the strongest anti-ribonuclear protein result (i.e., the highest result value), find the highest total bilirubin level and give me that test's total bilirubin level, the date of the lab test, the patient's ID, sex, and birthday. If several of those tests share the highest total bilirubin level, list each of them, one row per test.", "evidence": "Anti-ribonuclear protein refers to the anti-RNP antibody lab test; total bilirubin refers to the total serum bilirubin lab test (a liver marker).", "SQL": "SELECT T2.`T-BIL`, T2.`Date`, T1.ID, T1.SEX, T1.Birthday FROM `Patient` AS T1 INNER JOIN `Laboratory` AS T2 ON T1.ID = T2.ID WHERE CAST(T2.`RNP` AS FLOAT) = (SELECT MAX(CAST(`RNP` AS FLOAT)) FROM `Laboratory`) AND T2.`T-BIL` = (SELECT MAX(`T-BIL`) FROM `Laboratory` WHERE CAST(`RNP` AS FLOAT) = (SELECT MAX(CAST(`RNP` AS FLOAT)) FROM `Laboratory`))", "difficulty": "challenging"}
{"question_id": 392, "db_id": "thrombosis_prediction", "question": "I'm describing our young-patient group and want to show how unusual a raised RNP antibody is in these patients. Could you tell me how many patients in the thrombosis cohort born after 1 January 1960 never had a raised RNP antibody result? A few points: the group should cover every patient born after that date, including patients with no laboratory results at all - they count as never having had a raised result. \"Raised\" means a result strictly above 10, so a result of exactly 10 doesn't count, and a result of \"negative\" (no antibody detected) is never raised. Please return just one row with a single integer: the number of these patients.", "evidence": "RNP: anti-ribonuclear protein antibody; a result of \"negative\" means no antibody was detected. A raised RNP result is a laboratory result strictly above 10.", "SQL": "SELECT COUNT(*) AS patient_count FROM Patient AS p WHERE p.Birthday > '1960-01-01' AND NOT EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND NOT l.RNP IS NULL AND l.RNP <> 'negative' AND CAST(l.RNP AS FLOAT) > 10)", "difficulty": "challenging"}
{"question_id": 393, "db_id": "thrombosis_prediction", "question": "Among patients followed at the outpatient clinic who ever had an abnormal anti-SSA result, which one showed the highest anti-RNP titer? Please give me the patient's ID and the anti-RNP titer value. This should cover the hospital's full records across all years, and if several patients tie for the highest anti-RNP titer, list every one of them.", "evidence": "Abnormal anti-SSA means any SSA result other than negative or 0. \"Followed at the outpatient clinic\" is the admission status marked with a minus sign. Anti-RNP titer is the strength of the anti-ribonuclear protein result.", "SQL": "WITH cohort AS (SELECT DISTINCT T1.ID FROM Patient AS T1 JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Admission = '-' AND NOT T2.SSA IS NULL AND NOT T2.SSA IN ('negative', '0')), titers AS (SELECT T.ID, T.RNP FROM Laboratory AS T JOIN cohort AS C ON T.ID = C.ID WHERE NOT T.RNP IS NULL AND T.RNP <> 'negative') SELECT DISTINCT ID, RNP FROM titers WHERE CAST(RNP AS FLOAT) = (SELECT MAX(CAST(RNP AS FLOAT)) FROM titers)", "difficulty": "challenging"}
{"question_id": 394, "db_id": "thrombosis_prediction", "question": "I'm studying antibody and platelet profiles in mixed connective tissue disease (MCTD). Can you tell me how many patients diagnosed with MCTD alone - meaning MCTD is their only recorded diagnosis - have had at least one platelet reading within the normal range and at least one anti-RNP antibody level above 5 (strictly greater than 5)? I just need the patient count.", "evidence": "A platelet level within the normal range means from 100 to 400, both ends included; below 100 or above 400 is outside the normal range.", "SQL": "SELECT COUNT(DISTINCT T1.ID) AS patient_count FROM Patient AS T1 WHERE T1.Diagnosis = 'MCTD' AND T1.ID IN (SELECT ID FROM Laboratory WHERE PLT BETWEEN 100 AND 400) AND T1.ID IN (SELECT ID FROM Laboratory WHERE CAST(RNP AS FLOAT) > 5)", "difficulty": "challenging"}
{"question_id": 395, "db_id": "thrombosis_prediction", "question": "As part of the data-completeness review, I'd like to know how much laboratory follow-up our never-examined patients actually have, split by sex. Could you give me, for each sex (F and M), the average number of laboratory test dates recorded for the patients of that sex who have no examination record at all? Please cover the whole registry, all years, and round the averages to two decimal places. Nothing else needed beyond the two averages.", "evidence": "F denotes a female patient and M denotes a male patient. A laboratory test date is a date on which laboratory tests were recorded for a patient.", "SQL": "SELECT p.SEX, ROUND(AVG(COALESCE(c.n_dates, 0)), 2) AS avg_lab_test_dates FROM Patient AS p LEFT JOIN (SELECT ID, COUNT(*) AS n_dates FROM Laboratory GROUP BY ID) AS c ON c.ID = p.ID WHERE p.SEX IN ('F', 'M') AND NOT EXISTS(SELECT 1 FROM Examination WHERE Examination.ID = p.ID) GROUP BY p.SEX", "difficulty": "challenging"}
{"question_id": 396, "db_id": "thrombosis_prediction", "question": "I'm reviewing autoimmune antibody profiles in our thrombosis registry. Among the female patients who were admitted to the hospital as inpatients, I need to find the laboratory test record with the highest anti-DNA antibody level, for a case review. Please give me the patient ID, the laboratory test date of that record, and the anti-DNA antibody level reported in it - nothing else. Order the results by patient ID, and if several lab test records share the highest level, list each of them.", "evidence": "Anti-DNA antibody level means the anti-DNA test result recorded in the laboratory tests.", "SQL": "SELECT p.ID, l.Date, l.DNA AS anti_dna FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE p.SEX = 'F' AND p.Admission = '+' AND NOT l.DNA IS NULL AND CAST(l.DNA AS FLOAT) = (SELECT MAX(CAST(l2.DNA AS FLOAT)) FROM Laboratory AS l2 JOIN Patient AS p2 ON p2.ID = l2.ID WHERE p2.SEX = 'F' AND p2.Admission = '+' AND NOT l2.DNA IS NULL) ORDER BY p.ID", "difficulty": "challenging"}
{"question_id": 397, "db_id": "thrombosis_prediction", "question": "Among patients who have ever had an anti-ribonuclear protein (anti-RNP) antibody result above 16 on any laboratory reading, whenever it was taken, how many were admitted to the hospital and how many were followed at the outpatient clinic? Please give one row per care setting, using '+' for admitted to the hospital and '-' for followed at the outpatient clinic, showing the number of such patients in each setting.", "evidence": "", "SQL": "SELECT P.Admission AS care_setting, COUNT(DISTINCT P.ID) AS patients FROM Patient AS P WHERE P.Admission IN ('+', '-') AND EXISTS(SELECT 1 FROM Laboratory AS L WHERE L.ID = P.ID AND CAST(L.RNP AS FLOAT) > 16) GROUP BY P.Admission ORDER BY P.Admission COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 398, "db_id": "thrombosis_prediction", "question": "Among the thrombosis registry patients followed at the outpatient clinic, how many have a non-normal hematocrit and an anti-ribonuclear protein measurement above 16? I need a single count. A patient counts if they have at least one hematocrit reading outside the normal range, regardless of test date, and at least one anti-ribonuclear protein reading above 16, regardless of test date. Include every patient in the registry, not only those with a recorded thrombosis event.", "evidence": "Hematocrit is normal when the value lies strictly between 29 and 52; outside that range it is abnormal. A negative anti-ribonuclear protein result means none was detected.", "SQL": "WITH cohort AS (SELECT DISTINCT p.ID FROM Patient AS p JOIN Laboratory AS l ON p.ID = l.ID WHERE p.Admission = '-' AND (l.HCT >= 52 OR l.HCT <= 29)) SELECT COUNT(DISTINCT l.ID) AS patient_count FROM Laboratory AS l WHERE l.ID IN (SELECT ID FROM cohort) AND NOT l.RNP IS NULL AND CAST(l.RNP AS FLOAT) > 16", "difficulty": "challenging"}
{"question_id": 399, "db_id": "thrombosis_prediction", "question": "For the patients followed at our thrombosis unit's outpatient clinic, what is the highest anti-ribonuclear protein value on record? I just need that single highest value for my review.", "evidence": "Anti-ribonuclear protein (anti-RNP) is a blood antibody test result recorded for patients.", "SQL": "SELECT MAX(CAST(l.RNP AS FLOAT)) AS highest_anti_ribonuclear_protein_value FROM Laboratory AS l INNER JOIN Patient AS p ON p.ID = l.ID WHERE p.Admission = '-'", "difficulty": "challenging"}
{"question_id": 400, "db_id": "thrombosis_prediction", "question": "I'm studying patients who carry exactly the rheumatoid arthritis and Sjögren's syndrome overlap. Please look at each patient's own record and find those whose record names exactly rheumatoid arthritis and Sjögren's syndrome, in either order, and no other disease – a disease recorded only as suspected does not count as a diagnosis. For those patients, considering their whole recorded laboratory history regardless of date, I need two numbers: how many have had at least one laboratory result showing a normal platelet level, and how many have never had a laboratory result showing a normal platelet level – count a patient with no laboratory results at all as never having had a normal platelet result.", "evidence": "Rheumatoid arthritis is recorded as the code RA and Sjögren's syndrome as the code SJS. A normal platelet level means a platelet count above 100 and below 400.", "SQL": "SELECT SUM(CASE WHEN EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.PLT > 100 AND l.PLT < 400) THEN 1 ELSE 0 END) AS had_normal_platelet_result, SUM(CASE WHEN NOT EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.PLT > 100 AND l.PLT < 400) THEN 1 ELSE 0 END) AS never_normal_platelet_result FROM Patient AS p WHERE CHAR_LENGTH(LOWER(REPLACE(p.Diagnosis, ' ', ''))) - CHAR_LENGTH(REPLACE(LOWER(REPLACE(p.Diagnosis, ' ', '')), ',', '')) = 1 AND REPLACE(REPLACE(REPLACE(LOWER(REPLACE(p.Diagnosis, ' ', '')), 'ra', ''), 'sjs', ''), ',', '') = ''", "difficulty": "challenging"}
{"question_id": 401, "db_id": "thrombosis_prediction", "question": "I'm writing a report section on abnormal total protein in female SLE patients and need one summary figure. Among the laboratory records of female patients diagnosed with systemic lupus erythematosus at an examination visit, where total protein is above the normal bound of 8.5, what is the average deviation of total protein from that bound across all qualifying records, rounded to three decimal places? A few points: an examination visit counts as an SLE diagnosis when systemic lupus erythematosus is among the diseases that visit's diagnosis lists, whether it's the only one or appears alongside others; the normal bound is 8.5, and a record counts as above the bound only when its TP is greater than 8.5; a record's deviation is its TP minus 8.5; and the average should cover all qualifying laboratory records across all dates.", "evidence": "SLE: systemic lupus erythematosus.", "SQL": "SELECT ROUND(AVG(L.TP - 8.5), 3) AS avg_tp_deviation FROM Patient AS P INNER JOIN Laboratory AS L ON L.ID = P.ID WHERE P.SEX = 'F' AND L.TP > 8.5 AND P.ID IN (SELECT ID FROM Examination WHERE Diagnosis LIKE '%SLE%')", "difficulty": "challenging"}
{"question_id": 402, "db_id": "thrombosis_prediction", "question": "What percentage of patients in the registry with a diagnosis of psoriatic arthritis were born in 1960 or later? Please give a single percentage rounded to one decimal place.", "evidence": "Psoriatic arthritis is a rheumatologic diagnosis recorded for patients in the registry.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN DATE_FORMAT(Birthday, '%Y') >= '1960' THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(*), 1) AS percentage FROM Patient WHERE LOWER(TRIM(Diagnosis)) = 'psoriatic arthritis'", "difficulty": "challenging"}
{"question_id": 403, "db_id": "thrombosis_prediction", "question": "I'm putting together a demographic summary of our low-albumin patients. Could you tell me how many patients with an albumin measurement below 3.5 are female and how many are male? I'd like one row per sex group showing the sex (F or M) and the number of patients in that group.", "evidence": "F stands for female and M stands for male.", "SQL": "SELECT T1.SEX AS sex, COUNT(DISTINCT T1.ID) AS patient_count FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.ALB < 3.5 AND T1.SEX IN ('F', 'M') GROUP BY T1.SEX ORDER BY T1.SEX", "difficulty": "challenging"}
{"question_id": 404, "db_id": "thrombosis_prediction", "question": "I'm preparing a department audit on how often anti-ribonuclear protein testing comes back clearly elevated among the women in the thrombosis cohort. Among the women in the cohort, what percentage of those with an available anti-ribonuclear protein test result had a clearly elevated result? Please give me the percentage rounded to two decimal places on the 0-100 scale. Note: elevated means a titer strictly above 1:64. Patients never tested for anti-ribonuclear protein should be excluded from both the numerator and the denominator, while a negative reading counts as an available result and is never elevated.", "evidence": "Anti-ribonuclear protein is a serology test reported as a titer reading; a negative reading is a result of zero titer.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN EXISTS(SELECT 1 FROM Laboratory AS L WHERE L.ID = P.ID AND CAST(L.RNP AS FLOAT) > 64) THEN 1 ELSE 0 END) AS FLOAT) * 100 / COUNT(*), 2) AS pct FROM Patient AS P WHERE P.SEX = 'F' AND EXISTS(SELECT 1 FROM Laboratory AS L WHERE L.ID = P.ID AND NOT L.RNP IS NULL)", "difficulty": "challenging"}
{"question_id": 405, "db_id": "thrombosis_prediction", "question": "What was the average age of the register's patients in 1999, considering all patients who ever had marked or worse proteinuria on a lab test? Age in 1999 means 1999 minus the patient's year of birth. Marked or worse proteinuria means grade 3 or 4 on the original scale, or 300, 1000 or above on the scale used since 1987; traces and grades 1 and 2 don't count. I just need the one average number, in years.", "evidence": "U-PRO = proteinuria result of a laboratory test; TR = traces of proteinuria.", "SQL": "SELECT AVG('1999' - CAST(DATE_FORMAT(Birthday, '%Y') AS SIGNED)) AS average_age FROM Patient WHERE ID IN (SELECT ID FROM Laboratory WHERE `U-PRO` IN ('3', '4') OR CAST(REPLACE(`U-PRO`, '>=', '') AS FLOAT) >= 300)", "difficulty": "challenging"}
{"question_id": 406, "db_id": "thrombosis_prediction", "question": "I'm looking at patients whose anti-ribonuclear protein antibody measurement came out higher than 32. Of those patients, how many were women and how many were men? Note that 'higher than 32' means strictly above 32, not equal to it, and a patient qualifies if any of their laboratory measurements exceeded 32.", "evidence": "A woman means a patient recorded as F, and a man means a patient recorded as M.", "SQL": "SELECT COUNT(DISTINCT CASE WHEN T1.SEX = 'F' THEN T1.ID END) AS women, COUNT(DISTINCT CASE WHEN T1.SEX = 'M' THEN T1.ID END) AS men FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE CAST(T2.RNP AS FLOAT) > 32", "difficulty": "challenging"}
{"question_id": 407, "db_id": "thrombosis_prediction", "question": "I'm studying how early in life a patient in the thrombosis cohort can show a high anti-ribonuclear protein (RNP) reading. Please tell me the youngest age, in whole years, at which a patient had a laboratory test showing an anti-RNP result of at least 64. Age in whole years means the year of the test minus the year of birth. If several patients or tests share that youngest age, report that age once. I just need that single youngest age value, nothing else.", "evidence": "Anti-ribonuclear protein (RNP): an antibody measured in the laboratory panel, reported as a titer number or as negative.", "SQL": "SELECT MIN(DATE_FORMAT(T2.`Date`, '%Y') - DATE_FORMAT(T1.Birthday, '%Y')) AS youngest_age FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE CAST(T2.RNP AS FLOAT) >= 64", "difficulty": "challenging"}
{"question_id": 408, "db_id": "thrombosis_prediction", "question": "For the patients in the registry with a diagnosis of psoriatic arthritis, I'd like to know: (1) the total number of laboratory tests recorded for these patients, counting tests from all dates, and (2) how many of these patients have no laboratory tests recorded at all (i.e., patients with no laboratory record count as having no laboratory tests).", "evidence": "Psoriatic arthritis: a rheumatic disease diagnosis.", "SQL": "SELECT COUNT(l.ID) AS total_tests, SUM(CASE WHEN l.ID IS NULL THEN 1 ELSE 0 END) AS no_test_patients FROM Patient AS p LEFT JOIN Laboratory AS l ON l.ID = p.ID WHERE LOWER(p.Diagnosis) = 'psoriatic arthritis'", "difficulty": "challenging"}
{"question_id": 409, "db_id": "thrombosis_prediction", "question": "For our annual report, I need the count of patients in the thrombosis cohort who showed thrombosis at any examination performed between 01/01/1997 and 12/31/1997, inclusive. Please give me just that number of patients.", "evidence": "Thrombosis refers to the formation of blood clots, recorded at each examination as a graded finding.", "SQL": "SELECT COUNT(DISTINCT ID) AS patient_count FROM Examination WHERE `Examination Date` BETWEEN '1997-01-01' AND '1997-12-31' AND Thrombosis > 0", "difficulty": "challenging"}
{"question_id": 410, "db_id": "thrombosis_prediction", "question": "I'm putting together a monitoring checklist for SLE patients. Among the thrombotic episodes recorded for patients diagnosed with SLE, which single symptom appears most frequently? I just need the symptom name back. Please count all recorded episodes with no date restriction. If two symptoms are equally frequent, give the one that comes first alphabetically. Note that a patient counts as having SLE only if their own diagnosis record names SLE among their diseases.", "evidence": "SLE: systemic lupus erythematosus, an autoimmune disease. Thrombotic episode: an episode in which the patient experienced thrombosis.", "SQL": "WITH episodes AS (SELECT e.Symptoms FROM Examination AS e JOIN Patient AS p ON e.ID = p.ID WHERE LOCATE('SLE', p.Diagnosis) > 0 AND e.Thrombosis > 0) SELECT Symptoms FROM episodes GROUP BY Symptoms HAVING COUNT(*) = (SELECT MAX(n) FROM (SELECT COUNT(*) AS n FROM episodes GROUP BY Symptoms) AS __photo_derived_1) ORDER BY Symptoms LIMIT 1", "difficulty": "challenging"}
{"question_id": 411, "db_id": "thrombosis_prediction", "question": "In our autoimmune disease cohort, what percentage of thrombosis patients were diagnosed with SLE at the examination visit? I need the percentage on a 0-100 scale, rounded to two decimal places. Please use the diagnosis recorded at the examination visit, not the diagnosis on the patient's overall file. This is for a write-up on which diagnoses accompany thrombotic events in this cohort.", "evidence": "SLE: systemic lupus erythematosus, an autoimmune disease; thrombosis: formation of a blood clot within a blood vessel", "SQL": "SELECT ROUND(CAST(COUNT(DISTINCT CASE WHEN Diagnosis LIKE '%SLE%' THEN ID END) AS FLOAT) * 100 / COUNT(DISTINCT ID), 2) AS percentage FROM Examination WHERE Thrombosis > 0", "difficulty": "challenging"}
{"question_id": 412, "db_id": "thrombosis_prediction", "question": "For the thrombosis cohort, I need to describe how long admitted patients typically wait from their first hospital visit until their first examination. Please give me the average delay in days across admitted patients, based on each patient's own first visit and first examination, rounded to the nearest whole number. A patient counts as admitted whenever her admission entry carries a plus sign, regardless of anything else in that entry.", "evidence": "", "SQL": "SELECT ROUND(AVG(gap), 0) AS average_days FROM (SELECT T1.ID, MIN(TO_DAYS(T3.`Examination Date`)) - TO_DAYS(T1.`First Date`) AS gap FROM Patient AS T1 INNER JOIN Examination AS T3 ON T1.ID = T3.ID WHERE T1.Admission LIKE '%+%' GROUP BY T1.ID) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 413, "db_id": "thrombosis_prediction", "question": "For a demographics summary of our 1994 laboratory cohort: how many female patients and how many male patients had a normal AST glutamic oxaloacetic transaminase (GOT) index on laboratory tests done during the calendar year 1994? Please give me the patient count for each sex (F and M) and nothing else. The calendar year 1994 means laboratory test dates from 1994-01-01 through 1994-12-31.", "evidence": "AST glutamic oxaloacetic transaminase (GOT) index within normal range means a value below 60.", "SQL": "SELECT p.SEX, COUNT(DISTINCT p.ID) AS patient_count FROM Patient AS p INNER JOIN Laboratory AS l ON p.ID = l.ID WHERE l.GOT < 60 AND l.Date BETWEEN '1994-01-01' AND '1994-12-31' AND p.SEX IN ('F', 'M') GROUP BY p.SEX", "difficulty": "challenging"}
{"question_id": 414, "db_id": "thrombosis_prediction", "question": "I'm reviewing thrombosis ward patients and need a chart-review list. Can you give me, for every patient who had a single lab visit where the panel showed both an LDH result strictly between 600 and 800 and urine protein of 300 mg/dL or more, the patient ID and their completed age in years as of 2026-10-09? If any one visit's panel shows both findings, that patient qualifies. Please note that a proteinuria result reported as \"at least\" a level counts at that stated level (e.g., \"at least 300\" counts as 300 mg/dL or more), and a plain number is in mg/dL. Nothing else needed, just patient ID and completed age.", "evidence": "Proteinuria result codes: '-' means negative, 'TR' means trace.", "SQL": "SELECT p.ID, CAST(SUBSTRING('2026-10-09', 1, 4) AS SIGNED) - CAST(SUBSTRING(CAST(p.Birthday AS CHAR(10)), 1, 4) AS SIGNED) - CASE WHEN SUBSTRING('2026-10-09', 6, 5) < SUBSTRING(CAST(p.Birthday AS CHAR(10)), 6, 5) THEN 1 ELSE 0 END AS age FROM Patient AS p WHERE NOT p.Birthday IS NULL AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.LDH > 600 AND l.LDH < 800 AND CAST(REPLACE(REPLACE(CAST(l.`U-PRO` AS CHAR), '>', ''), '=', '') AS FLOAT) >= 300) ORDER BY p.ID", "difficulty": "challenging"}
{"question_id": 415, "db_id": "thrombosis_prediction", "question": "For the RA patients whose urea nitrogen was within the normal index, how many more women are there than men? Please give me a single integer: the count of women minus the count of men. Women means sex F and men means sex M, and the difference may be negative.", "evidence": "Within the UN normal index means UN < 30; RA means a Diagnosis of RA.", "SQL": "SELECT SUM(CASE WHEN SEX = 'F' THEN 1 ELSE 0 END) - SUM(CASE WHEN SEX = 'M' THEN 1 ELSE 0 END) AS women_minus_men FROM Patient WHERE Diagnosis = 'RA' AND ID IN (SELECT ID FROM Laboratory WHERE UN < 30)", "difficulty": "challenging"}
{"question_id": 416, "db_id": "thrombosis_prediction", "question": "I'm reviewing renal function in the thrombosis cohort and want to compare how often creatinine runs out of the normal range between men and women. For each sex (M and F), please give me: the number of patients of that sex with at least one creatinine result out of the normal range, the total number of patients of that sex, and the share those patients represent of that sex's total as a percentage rounded to one decimal place. Rules: out of the normal range means a creatinine result of 1.5 or higher; the total per sex counts every patient of that sex on file whether or not any lab result exists for them.", "evidence": "Creatinine out of the normal range: a CRE value of 1.5 or higher. Male is SEX = 'M'; female is SEX = 'F'.", "SQL": "SELECT P.SEX AS sex, COUNT(DISTINCT CASE WHEN L.CRE >= 1.5 THEN P.ID END) AS out_of_range_patients, COUNT(DISTINCT P.ID) AS total_patients, ROUND(100.0 * COUNT(DISTINCT CASE WHEN L.CRE >= 1.5 THEN P.ID END) / COUNT(DISTINCT P.ID), 1) AS share_pct FROM Patient AS P LEFT JOIN Laboratory AS L ON P.ID = L.ID WHERE P.SEX IN ('M', 'F') GROUP BY P.SEX ORDER BY P.SEX", "difficulty": "challenging"}
{"question_id": 417, "db_id": "thrombosis_prediction", "question": "In this cohort, I want to compare the most extreme total cholesterol (T-CHO) readings between patients admitted to the hospital and those followed at the outpatient clinic. Please give me, for each of the two groups, the single highest T-CHO reading, along with the admission status ('+' admitted, '-' outpatient) and the patient ID whose reading is the group's highest. List the admitted group's row first, then the outpatient group's. If several patients tie at a group's highest reading, list each of them.", "evidence": "T-CHO: total cholesterol. '+': the patient was admitted to the hospital. '-': the patient was followed at the outpatient clinic.", "SQL": "SELECT l.`T-CHO` AS `T-CHO`, p.Admission AS status, p.ID FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID JOIN (SELECT p2.Admission AS adm, MAX(l2.`T-CHO`) AS mx FROM Patient AS p2 JOIN Laboratory AS l2 ON l2.ID = p2.ID WHERE p2.Admission IN ('+', '-') GROUP BY p2.Admission) AS t ON t.adm = p.Admission AND t.mx = l.`T-CHO` ORDER BY CASE p.Admission WHEN '+' THEN 0 ELSE 1 END, p.ID", "difficulty": "challenging"}
{"question_id": 418, "db_id": "thrombosis_prediction", "question": "Among patients whose first visit to the hospital was in 1991, which patients mounted the strongest anti-ribonuclear protein (RNP) response? Please give me the patient ID and anti-RNP level for every patient tied at the highest recorded level. Only consider patients for whom a level was actually recorded.", "evidence": "anti-ribonuclear protein (RNP): an antibody titer; a higher titer means a higher level.", "SQL": "SELECT DISTINCT T1.ID, T2.RNP FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE DATE_FORMAT(T1.`First Date`, '%Y') = '1991' AND NOT T2.RNP IS NULL AND CAST(T2.RNP AS FLOAT) = (SELECT MAX(CAST(L.RNP AS FLOAT)) FROM Patient AS P INNER JOIN Laboratory AS L ON P.ID = L.ID WHERE DATE_FORMAT(P.`First Date`, '%Y') = '1991' AND NOT L.RNP IS NULL)", "difficulty": "challenging"}
{"question_id": 419, "db_id": "thrombosis_prediction", "question": "I'm reviewing the 1991 lab records of the thrombosis cohort, checking whether heavy proteinuria went hand in hand with lower hematocrit that year, as a sign of anemia in kidney involvement. Among the laboratory tests done in 1991 that reported proteinuria of at least 300 mg/dL, what was the average hematocrit value? Please note: proteinuria levels are measured in mg/dL; a proteinuria result reported only as a lower bound that the reading reached or exceeded still counts as being at least that level; a trace result is below 30 mg/dL; and tests without a hematocrit reading should be left out of the average.", "evidence": "", "SQL": "SELECT ROUND(AVG(HCT), 2) AS average_hematocrit FROM Laboratory WHERE DATE_FORMAT(Date, '%Y') = '1991' AND CAST(REPLACE(`U-PRO`, '>=', '') AS FLOAT) >= 300", "difficulty": "challenging"}
{"question_id": 420, "db_id": "thrombosis_prediction", "question": "I'm putting together a care-setting summary of severe SLE cases for the rheumatology department. Among patients diagnosed with SLE, considering only those whose only diagnosis is SLE and who had abnormally high proteinuria, how many were admitted to the hospital and how many were followed at the outpatient clinic? Please count each patient based on their full history at the hospital.", "evidence": "Abnormally high proteinuria means a proteinuria level of 30 or higher.", "SQL": "SELECT COUNT(DISTINCT CASE WHEN T1.Admission = '+' THEN T1.ID END) AS admitted_to_hospital, COUNT(DISTINCT CASE WHEN T1.Admission = '-' THEN T1.ID END) AS followed_at_outpatient_clinic FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.Diagnosis = 'SLE' AND CAST(T2.`U-PRO` AS FLOAT) >= 30", "difficulty": "challenging"}
{"question_id": 421, "db_id": "thrombosis_prediction", "question": "How many patients in our thrombosis ward are followed at the outpatient clinic (rather than admitted) with a normal Rheumatoid Factor and no positive measure of degree of coagulation? Please give me a single number. For context: a normal Rheumatoid Factor is '-' or '+-', a positive measure of degree of coagulation is '+' on any of the coagulation measures (KCT, RVVT, LAC), and an outpatient-clinic patient is one with Admission = '-'. If a patient has no recorded coagulation measure, count them as having no positive measure.", "evidence": "", "SQL": "SELECT COUNT(DISTINCT T1.ID) AS patient_count FROM Patient AS T1 WHERE T1.Admission = '-' AND T1.ID IN (SELECT ID FROM Laboratory WHERE RA IN ('-', '+-')) AND NOT EXISTS(SELECT 1 FROM Examination AS E WHERE E.ID = T1.ID AND (E.KCT = '+' OR E.RVVT = '+' OR E.LAC = '+'))", "difficulty": "challenging"}
{"question_id": 422, "db_id": "thrombosis_prediction", "question": "I'm reviewing our cohort and need to identify patients whose most recent laboratory sample on file was collected after 1 January 1997 (strictly later than that date) and whose most recent anti-Scl-70 result on file was normal. Please return only the patient IDs for these patients.", "evidence": "anti-Scl-70: anti-topoisomerase I antibody, an autoantibody measured in the laboratory. A normal anti-Scl-70 result is a result of 'negative' or 0.", "SQL": "WITH lab AS (SELECT ID, MAX(Date) AS LastDate FROM Laboratory GROUP BY ID), last_sc AS (SELECT s.ID AS ID, s.SC170 AS SC170 FROM Laboratory AS s WHERE NOT s.SC170 IS NULL AND s.Date = (SELECT MAX(s2.Date) FROM Laboratory AS s2 WHERE s2.ID = s.ID AND NOT s2.SC170 IS NULL)) SELECT l.ID FROM lab AS l JOIN last_sc AS c ON c.ID = l.ID WHERE l.LastDate > '1997-01-01' AND c.SC170 IN ('negative', '0') ORDER BY l.ID", "difficulty": "challenging"}
{"question_id": 423, "db_id": "thrombosis_prediction", "question": "I'd like to know how many patients on record have both an abnormal anti-SSA antibody result and a positive proteinuria finding at some point in their record. Abnormal anti-SSA means any recorded test result other than negative or zero. Proteinuria counts as positive if any urine test on file returned a result other than negative or none. The two findings don't need to come from the same visit – I'm looking across each patient's entire record. Please just give me the number of such patients.", "evidence": "anti-SSA: anti-SSA antibody laboratory test; proteinuria: protein found in the urine", "SQL": "SELECT COUNT(*) AS patient_count FROM Patient AS T1 WHERE T1.ID IN (SELECT ID FROM Laboratory WHERE NOT SSA IS NULL AND NOT SSA IN ('negative', '0')) AND T1.ID IN (SELECT ID FROM Laboratory WHERE NOT `U-PRO` IS NULL AND NOT `U-PRO` IN ('-', '0'))", "difficulty": "challenging"}
{"question_id": 424, "db_id": "thrombosis_prediction", "question": "For a study of laboratory test patterns, I need to size a cohort. How many female patients have at least one anti-DNA antibody level below 8 (the upper bound of the normal range)? Any laboratory visit of the patient qualifies; there is no time scope. I just need that single count back.", "evidence": "anti-DNA level: the anti-DNA antibody concentration measured in the laboratory tests", "SQL": "SELECT COUNT(DISTINCT T1.ID) AS patient_count FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND CAST(T2.DNA AS FLOAT) < 8", "difficulty": "challenging"}
{"question_id": 425, "db_id": "thrombosis_prediction", "question": "For patients admitted to the hospital, how many never had an alkaliphosphatase level above the normal ceiling in their lab results? I just need that single count.", "evidence": "A patient is admitted when their status is anything other than the outpatient-clinic code; the outpatient-clinic code is '-' and admitted is '+'. A normal alkaliphosphatase level is below 300; a level of 300 or more is above the normal ceiling.", "SQL": "SELECT COUNT(*) AS admitted_never_high_alp FROM Patient WHERE Admission <> '-' AND NOT EXISTS(SELECT 1 FROM Laboratory WHERE Laboratory.ID = Patient.ID AND ALP >= 300)", "difficulty": "challenging"}
{"question_id": 426, "db_id": "thrombosis_prediction", "question": "Among patients in the thrombosis prediction database whose creatinine level is normal (below 1.5), what is the highest anti-RNP antibody level recorded? Please return just that single number; if several measurements tie for the highest, the tied value is the answer.", "evidence": "Anti-RNP antibody = anti-ribonuclear protein antibody, measured by the laboratory panel.", "SQL": "SELECT MAX(CAST(T2.RNP AS FLOAT)) AS max_rnp_level FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.CRE < 1.5", "difficulty": "challenging"}
{"question_id": 427, "db_id": "thrombosis_prediction", "question": "I'd like to see how severe anemia is distributed across the sexes in the registry. Please give me, for each sex, the number of patients of that sex who ever showed severe anemia on any lab test, with the rows labeled 'female' and 'male'.", "evidence": "Severe anemia means a hemoglobin value below 7.0 g/dL on a lab test.", "SQL": "SELECT CASE p.SEX WHEN 'F' THEN 'female' WHEN 'M' THEN 'male' END AS sex, COUNT(DISTINCT p.ID) AS severe_anemia_patients FROM Patient AS p INNER JOIN Laboratory AS l ON l.ID = p.ID WHERE l.HGB < 7.0 GROUP BY p.SEX HAVING p.SEX IN ('F', 'M')", "difficulty": "challenging"}
{"question_id": 428, "db_id": "thrombosis_prediction", "question": "Among the laboratory tests whose AST glutamic oxaloacetic transaminase (GOT) index was above the normal range (60 or higher), I want to find the test with the highest anti-ribonuclear protein reading. Please give me the patient's identification, the date of the laboratory test, and the anti-ribonuclear protein reading for that test. If several tests tie for the highest anti-ribonuclear protein reading, list every one of them. The date should be the date the laboratory test was performed.", "evidence": "AST glutamic oxaloacetic transaminase (GOT) index: a liver enzyme measurement; values of 60 or higher are considered above the normal range.", "SQL": "SELECT ID, Date, RNP FROM Laboratory WHERE GOT >= 60 AND CAST(RNP AS FLOAT) = (SELECT MAX(CAST(RNP AS FLOAT)) FROM Laboratory WHERE GOT >= 60)", "difficulty": "challenging"}
{"question_id": 429, "db_id": "thrombosis_prediction", "question": "I'm screening our thrombosis cohort for a study and need an eligibility count. How many patients born after 1980-01-01 had at least one abnormal fibrinogen result or at least one severe proteinuria result? A fibrinogen result is abnormal if it's below 150 or above 450; the normal range 150-450 is inclusive. Severe proteinuria means 300 mg/dl or more on the urinalysis scale, i.e., dipstick 3+ or 4+; trace, 1+ and 2+ are not severe. I just need the single count, nothing else.", "evidence": "Urinalysis protein scale: '-' and '0' mean no protein, 'TR' means trace, grades '1','2','3','4' mean 1+ to 4+, where 3+ is about 300 mg/dl and 4+ about 1000 mg/dl or more; a plain number is a reading in mg/dl, and a '>=' prefix means 'or more'.", "SQL": "SELECT COUNT(DISTINCT p.ID) AS patient_count FROM Patient AS p JOIN Laboratory AS l ON p.ID = l.ID WHERE p.Birthday > '1980-01-01' AND ((l.FG < 150 OR l.FG > 450) OR (l.`U-PRO` IN ('3', '4') OR CAST(REPLACE(l.`U-PRO`, '>=', '') AS FLOAT) >= 300))", "difficulty": "challenging"}
{"question_id": 430, "db_id": "thrombosis_prediction", "question": "In the thrombosis and autoimmune-disease cohort, I want to compare how often lactate dehydrogenase stays in the normal range between patients admitted to the hospital and patients followed at the outpatient clinic. Please give me one row per patient group showing the number of lactate dehydrogenase measurements within the normal range recorded for that group, with the admitted group's row first. Label the rows 'admitted to the hospital' for the Admission = '+' group and 'followed at the outpatient clinic' for the Admission = '-' group. Every laboratory measurement recorded for those patients across the whole study period counts. Nothing else is needed.", "evidence": "The normal range for lactate dehydrogenase means a value below 500.", "SQL": "SELECT CASE WHEN P.Admission = '+' THEN 'admitted to the hospital' ELSE 'followed at the outpatient clinic' END AS patient_group, COUNT(*) AS normal_ldh_measurements FROM Patient AS P JOIN Laboratory AS L ON P.ID = L.ID WHERE P.Admission IN ('+', '-') AND L.LDH < 500 GROUP BY 1 ORDER BY CASE WHEN patient_group IS NULL THEN 1 ELSE 0 END, patient_group", "difficulty": "challenging"}
{"question_id": 431, "db_id": "thrombosis_prediction", "question": "For patients whose sex is not recorded in the registry, I need two counts for the annual quality report: how many have at least one laboratory result on file, and of those, how many have at least one laboratory result showing elevated total bilirubin. The report covers all dates.", "evidence": "A patient's sex is not recorded when the registry holds no sex entry for that patient. Total bilirubin of 2.0 or higher counts as elevated.", "SQL": "SELECT COUNT(DISTINCT T2.ID) AS patients_with_lab_results, COUNT(DISTINCT CASE WHEN T2.`T-BIL` >= 2.0 THEN T2.ID END) AS patients_with_elevated_bilirubin FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX IS NULL OR T1.SEX = ''", "difficulty": "challenging"}
{"question_id": 432, "db_id": "thrombosis_prediction", "question": "For an audit, I need the number of admitted female patients born between 1945 and 1989 (inclusive) who have an ANA examination where the observed pattern is exactly P, with no other pattern alongside it. Please return just that single count.", "evidence": "ANA pattern: the pattern observed in the ANA examination, e.g. 'P' or 'P,S'; the admission mark starting with a plus indicates the patient was admitted.", "SQL": "SELECT COUNT(DISTINCT T1.ID) FROM Patient AS T1 INNER JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.Admission LIKE '+%' AND T1.SEX = 'F' AND DATE_FORMAT(T1.Birthday, '%Y') BETWEEN '1945' AND '1989' AND T2.`ANA Pattern` = 'P'", "difficulty": "challenging"}
{"question_id": 433, "db_id": "thrombosis_prediction", "question": "I'm screening outpatient clinic patients with anemia for rheumatologic autoimmunity. Among patients who were followed as outpatients (rather than admitted to the hospital) and who ever had a hemoglobin value below 10 on any lab test, who showed the strongest anti-ribonuclear protein antibody response? Please return, for every patient whose anti-ribonuclear protein antibody level reached the highest point ever recorded on their lab tests (list all of them if several share that highest level): the patient ID, the patient's sex, and that highest-ever recorded anti-ribonuclear protein antibody level. Nothing else.", "evidence": "Anti-ribonuclear protein refers to the antibody measured in the laboratory tests (anti-RNP).", "SQL": "SELECT p.ID, p.SEX, MAX(CAST(r.RNP AS FLOAT)) AS highest_level FROM Patient AS p JOIN Laboratory AS r ON r.ID = p.ID WHERE p.Admission = '-' AND EXISTS(SELECT 1 FROM Laboratory AS h WHERE h.ID = p.ID AND h.HGB < 10) GROUP BY p.ID, p.SEX HAVING MAX(CAST(r.RNP AS FLOAT)) = (SELECT MAX(CAST(r2.RNP AS FLOAT)) FROM Patient AS p2 JOIN Laboratory AS r2 ON r2.ID = p2.ID WHERE p2.Admission = '-' AND EXISTS(SELECT 1 FROM Laboratory AS h2 WHERE h2.ID = p2.ID AND h2.HGB < 10))", "difficulty": "challenging"}
{"question_id": 434, "db_id": "thrombosis_prediction", "question": "Among the patients in the thrombosis prediction data, how many have a first laboratory record showing both a normal glutamic oxaloacetic transaminase (GOT) level and an elevated anti-ribonuclear protein (RNP) concentration? By normal GOT I mean a value below 60, and by elevated RNP I mean a value above 10. By first laboratory record I mean the one with the earliest laboratory test date for that patient. I need just a single count of these patients.", "evidence": "GOT stands for glutamic oxaloacetic transaminase (also known as aspartate aminotransferase, AST); RNP stands for anti-ribonuclear protein.", "SQL": "SELECT COUNT(DISTINCT L.ID) FROM Laboratory AS L WHERE L.Date = (SELECT MIN(Date) FROM Laboratory WHERE ID = L.ID) AND L.GOT < 60 AND CAST(L.RNP AS FLOAT) > 10", "difficulty": "challenging"}
{"question_id": 435, "db_id": "thrombosis_prediction", "question": "I'm reviewing the current kidney involvement status of the thrombosis prediction cohort. For every patient who has had a proteinuria test, I need their patient identifier, sex, the date of their most recent proteinuria test, and the proteinuria level measured on that test. \"Most recent\" means the latest proteinuria test by test date.", "evidence": "A proteinuria test is a test that measures the level of protein in the urine; the proteinuria level is the result value it reports.", "SQL": "SELECT p.ID AS patient_id, p.SEX AS sex, l.Date AS most_recent_test_date, l.`U-PRO` AS proteinuria_level FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE NOT l.`U-PRO` IS NULL AND l.Date = (SELECT MAX(l2.Date) FROM Laboratory AS l2 WHERE l2.ID = l.ID AND NOT l2.`U-PRO` IS NULL) ORDER BY p.ID", "difficulty": "challenging"}
{"question_id": 436, "db_id": "thrombosis_prediction", "question": "I'm screening the thrombosis cohort for a follow-up panel. Can you give me the patient ids of outpatients (patients followed at the outpatient clinic rather than admitted) whose creatinine phosphokinase is in the normal range (below 250) but whose anti-ribonuclear protein antibody level is above 4 (strictly greater than 4)? Please note that an anti-ribonuclear protein result reported as negative means no antibody was detected. I just need the patient ids, nothing else.", "evidence": "", "SQL": "SELECT DISTINCT T1.ID FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.CPK < 250 AND T1.Admission = '-' AND CAST(T2.RNP AS FLOAT) > 4", "difficulty": "challenging"}
{"question_id": 437, "db_id": "thrombosis_prediction", "question": "I'd like to know how many patients in the cohort have a positive anti-ribonuclear protein (RNP) result but no thrombosis. A positive RNP result means the anti-ribonuclear protein level is above 0, and no thrombosis means the thrombosis degree is 0. Please return just the number of such patients.", "evidence": "", "SQL": "SELECT COUNT(DISTINCT T1.ID) FROM Examination AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE CAST(T2.RNP AS FLOAT) > 0 AND T1.Thrombosis = 0", "difficulty": "challenging"}
{"question_id": 438, "db_id": "thrombosis_prediction", "question": "I'm reviewing patients with an elevated anti-ribonuclear protein result. Among patients who ever had an anti-ribonuclear protein result of 16 or higher, I want to follow up the three whose liver enzymes stayed in the normal range. The normal range for GPT is below 60. For each patient, take their highest GPT value among their laboratory tests that fall in the normal range. Rank patients from that highest value down; if two patients share the same value, the one with the smaller patient ID comes first. Please return exactly three patients, one row per patient, with only each patient's Birthday.", "evidence": "GPT stands for glutamic pyruvic transaminase, a liver enzyme; anti-ribonuclear protein is an autoantibody measured in laboratory tests.", "SQL": "SELECT T1.Birthday FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T2.GPT < 60 AND T1.ID IN (SELECT ID FROM Laboratory WHERE CAST(RNP AS FLOAT) >= 16) GROUP BY T1.ID ORDER BY MAX(T2.GPT) DESC, T1.ID ASC LIMIT 3", "difficulty": "challenging"}
{"question_id": 439, "db_id": "thrombosis_prediction", "question": "I'm trying to size a subgroup in the thrombosis cohort: how many female patients had a normal prothrombin time (below 14 seconds) along with an elevated anti-ribonuclear protein level (16 or higher)? Please use the prothrombin time and anti-ribonuclear protein level from the same laboratory record for each patient. I just need the count of such female patients.", "evidence": "Normal prothrombin time: below 14 seconds. Elevated anti-ribonuclear protein: a measured level of 16 or higher.", "SQL": "SELECT COUNT(DISTINCT T1.ID) AS patient_count FROM Patient AS T1 INNER JOIN Laboratory AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND T2.PT < 14 AND CAST(T2.RNP AS FLOAT) >= 16", "difficulty": "challenging"}
{"question_id": 440, "db_id": "thrombosis_prediction", "question": "Among inpatients (admission marked '+'), find the laboratory anti-DNA antibody test with the highest recorded level, and report the patient's age in completed years at that test date and the patient's diagnosis. If several tests share the highest level, use the one with the earliest test date.", "evidence": "An inpatient is a patient admitted to the hospital: the Admission record is marked '+' (a '-' marks an outpatient followed at the clinic). Age in completed years means the age at the last birthday reached on or before the test date. The anti-DNA antibody level is a laboratory reading reported alongside the other antibody tests.", "SQL": "WITH cand AS (SELECT p.Diagnosis, CAST(DATE_FORMAT(l.Date, '%Y') AS SIGNED) - CAST(DATE_FORMAT(p.Birthday, '%Y') AS SIGNED) - CASE WHEN SUBSTRING(l.Date, 6, 5) < SUBSTRING(p.Birthday, 6, 5) THEN 1 ELSE 0 END AS age, CAST(l.DNA AS FLOAT) AS level, l.Date AS test_date FROM Patient AS p JOIN Laboratory AS l ON p.ID = l.ID WHERE NOT l.DNA IS NULL AND NOT p.Birthday IS NULL AND p.Admission = '+') SELECT age, Diagnosis FROM cand WHERE level = (SELECT MAX(level) FROM cand) ORDER BY test_date LIMIT 1", "difficulty": "challenging"}
{"question_id": 441, "db_id": "thrombosis_prediction", "question": "I need to find lupus patients with liver lab abnormalities. Can you give me the ID and sex of every patient who has at least one total bilirubin (T-BIL) result at or above the upper normal limit of 1.2 mg/dL, and who has a confirmed diagnosis of systemic lupus erythematosus (SLE)? SLE counts if it's among the patient's confirmed diagnoses, even when other diseases are diagnosed or suspected alongside it, but a suspected SLE alone doesn't count. The diagnosis should be the patient's overall diagnosis, not something noted at a single examination. Please order results by sex, then patient ID, and return only the ID and sex.", "evidence": "T-BIL: total bilirubin; SLE: systemic lupus erythematosus; susp.: suspected, not a confirmed diagnosis", "SQL": "SELECT p.ID, p.SEX FROM Patient AS p WHERE p.ID IN (SELECT ID FROM Laboratory WHERE `T-BIL` >= 1.2) AND LOCATE(CONCAT(',', 'SLE', ','), CONCAT(',', REPLACE(p.Diagnosis, ' ', ''), ',')) > 0 ORDER BY p.SEX, p.ID", "difficulty": "challenging"}
{"question_id": 442, "db_id": "thrombosis_prediction", "question": "I'm reviewing how often older female patients show elevated anti-RNP antibody results, split by whether they were admitted to the hospital or followed at the outpatient clinic. For female patients aged at least 50 as of 2026-10-09, please give me a two-row breakdown by care setting (admitted to the hospital vs. followed at the outpatient clinic), showing for each setting how many patients had at least one anti-RNP laboratory result of at least 4, and how many had no such result. A patient's admission marker of '+' counts as admitted to the hospital and '-' counts as followed at the outpatient clinic; patients with any other admission marker are out of scope. Order the two rows alphabetically by care setting.", "evidence": "anti-RNP: anti-ribonuclear protein antibody, measured in laboratory results; admission marker: the patient's recorded admission sign.", "SQL": "SELECT CASE WHEN p.Admission = '+' THEN 'admitted to the hospital' ELSE 'followed at the outpatient clinic' END AS care_setting, SUM(CASE WHEN EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND CAST(l.RNP AS FLOAT) >= 4) THEN 1 ELSE 0 END) AS patients_with_rnp_at_least_4, SUM(CASE WHEN EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND CAST(l.RNP AS FLOAT) >= 4) THEN 0 ELSE 1 END) AS patients_without_such_result FROM Patient AS p WHERE p.SEX = 'F' AND p.Birthday <= CONCAT(CAST(SUBSTRING('2026-10-09', 1, 4) AS SIGNED) - 50, SUBSTRING('2026-10-09', 5)) AND p.Admission IN ('+', '-') GROUP BY 1 ORDER BY care_setting", "difficulty": "challenging"}
{"question_id": 443, "db_id": "thrombosis_prediction", "question": "I'm putting together a cohort summary and need one number: how many patients followed at the outpatient clinic (admission marker '-') have a most recent IgG lab result of 2000 or higher? By most recent, I mean the IgG measurement with the greatest laboratory date for that patient - since a patient has at most one lab record per date, there should be no ambiguity.", "evidence": "", "SQL": "WITH latest_igg AS (SELECT ID, MAX(Date) AS LastDate FROM Laboratory WHERE NOT IGG IS NULL GROUP BY ID) SELECT COUNT(*) AS patient_count FROM Patient AS p JOIN latest_igg AS li ON li.ID = p.ID JOIN Laboratory AS l ON l.ID = li.ID AND l.Date = li.LastDate WHERE p.Admission = '-' AND l.IGG >= 2000", "difficulty": "challenging"}
{"question_id": 444, "db_id": "thrombosis_prediction", "question": "Among all patients diagnosed with systemic lupus erythematosus, I want to find the patient whose anti-DNA test result was the strongest ever recorded for that disease. Please report the patient's identifier, the patient's diagnosis, and that patient's highest anti-DNA test result, using the number exactly as the test wrote it. If several patients tie for the highest anti-DNA result, list every tied patient.", "evidence": "Systemic lupus erythematosus (SLE) is an autoimmune disease; anti-DNA is an antibody test reported as a number.", "SQL": "WITH ranked AS (SELECT p.ID AS patient_id, p.Diagnosis AS diagnosis, l.DNA AS highest_anti_dna, ROW_NUMBER() OVER (PARTITION BY p.ID ORDER BY CAST(l.DNA AS FLOAT) DESC, l.Date DESC) AS rn FROM Patient AS p INNER JOIN Laboratory AS l ON p.ID = l.ID WHERE p.Diagnosis LIKE '%SLE%' AND NOT l.DNA IS NULL), best AS (SELECT patient_id, diagnosis, highest_anti_dna FROM ranked WHERE rn = 1) SELECT patient_id, diagnosis, highest_anti_dna FROM best WHERE CAST(highest_anti_dna AS FLOAT) = (SELECT MAX(CAST(highest_anti_dna AS FLOAT)) FROM best) ORDER BY patient_id", "difficulty": "challenging"}
{"question_id": 445, "db_id": "thrombosis_prediction", "question": "For our thrombosis study cohort, I'd like to know how often patients have a normal IgG status at their most recent check, broken down by care setting. Please give me, for patients admitted to the hospital and for patients followed at the outpatient clinic, the percentage of that setting's patients whose most recent IgG measurement was normal. The percentage should be out of every patient in that setting, so patients who never had an IgG measurement count toward the denominator but not the numerator. Please round to one decimal place, and label the two results exactly as 'admitted to the hospital' and 'followed at the outpatient clinic'.", "evidence": "An IgG measurement is considered normal when it is above 900 and below 2000.", "SQL": "WITH latest AS (SELECT ID, IGG, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS rn FROM Laboratory WHERE NOT IGG IS NULL) SELECT CASE WHEN p.Admission = '+' THEN 'admitted to the hospital' ELSE 'followed at the outpatient clinic' END AS care_setting, ROUND(100.0 * SUM(CASE WHEN l.IGG > 900 AND l.IGG < 2000 THEN 1 ELSE 0 END) / COUNT(p.ID), 1) AS patient_share FROM Patient AS p LEFT JOIN latest AS l ON l.ID = p.ID AND l.rn = 1 WHERE p.Admission IN ('+', '-') GROUP BY 1 ORDER BY 1", "difficulty": "challenging"}
{"question_id": 446, "db_id": "thrombosis_prediction", "question": "In the thrombosis prediction cohort, I'd like to know whether the female predominance I saw for strongly positive anti-RNP results across follow-up also holds at patients' current status. Please give me a single integer: the number of female patients whose most recent visit shows a strongly positive anti-RNP result, minus the number of male patients whose most recent visit shows such a result. Use only the result at each patient's most recent visit, not earlier visits. A strongly positive anti-RNP result means a level of 32 or higher.", "evidence": "anti-ribonuclear protein (RNP): an autoantibody measured in the laboratory work-up; visit: a date on which the patient's laboratory tests were performed", "SQL": "WITH latest AS (SELECT ID, MAX(Date) AS MaxDate FROM Laboratory GROUP BY ID) SELECT COUNT(DISTINCT CASE WHEN p.SEX = 'F' AND CAST(l.RNP AS FLOAT) >= 32 THEN p.ID END) - COUNT(DISTINCT CASE WHEN p.SEX = 'M' AND CAST(l.RNP AS FLOAT) >= 32 THEN p.ID END) AS female_minus_male FROM Patient AS p JOIN latest AS la ON p.ID = la.ID JOIN Laboratory AS l ON l.ID = la.ID AND l.Date = la.MaxDate", "difficulty": "challenging"}
{"question_id": 447, "db_id": "thrombosis_prediction", "question": "In the thrombosis prediction cohort, I want to gauge how often the most recent anti-ribonuclear protein measurement among female patients was markedly elevated while CPK stayed low at that same measurement. Please give me a single integer: the number of female patients whose most recent anti-ribonuclear protein titer was above 64 and whose CPK from that same laboratory record was below 250. Above 64 means strictly greater than 64, and below 250 means strictly less than 250.", "evidence": "Anti-ribonuclear protein is an autoantibody measured as a titer in the blood; a negative result means the antibody was not detected.", "SQL": "SELECT COUNT(DISTINCT p.ID) AS female_patients FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE p.SEX = 'F' AND NOT l.RNP IS NULL AND l.Date = (SELECT MAX(l2.Date) FROM Laboratory AS l2 WHERE l2.ID = p.ID AND NOT l2.RNP IS NULL) AND CAST(l.RNP AS FLOAT) > 64 AND l.CPK < 250", "difficulty": "challenging"}
{"question_id": 448, "db_id": "thrombosis_prediction", "question": "I'm preparing a capacity report for the lupus service. Among the patients whose profile lists a confirmed SLE diagnosis (not just suspected), I need: (1) how many were admitted to the hospital as inpatients, (2) how many were followed at the outpatient clinic, and (3) what percentage of the confirmed-SLE patients who were in one of these two care settings were inpatients. Please round the percentage to two decimals.", "evidence": "SLE means systemic lupus erythematosus. A disease name followed by 'susp' (e.g., 'SLE susp') means only suspected, not confirmed, and does not count.", "SQL": "SELECT SUM(CASE WHEN Admission = '+' THEN 1 ELSE 0 END) AS inpatients, SUM(CASE WHEN Admission = '-' THEN 1 ELSE 0 END) AS outpatients, ROUND(100.0 * SUM(CASE WHEN Admission = '+' THEN 1 ELSE 0 END) / SUM(CASE WHEN Admission IN ('+', '-') THEN 1 ELSE 0 END), 2) AS inpatient_pct FROM Patient WHERE Diagnosis LIKE '%SLE%' AND Diagnosis NOT LIKE '%SLE susp%'", "difficulty": "challenging"}
{"question_id": 449, "db_id": "thrombosis_prediction", "question": "I'm putting together a renal-involvement review. Could you pull the demographics of patients who show both marked tissue damage and clinically significant proteinuria? Specifically, I need the patient ID, sex, and birthday of every patient who has at least one LDH result of 500 or higher and at least one urinary protein result of 100 mg/dL or more. A few details: an LDH of exactly 500 counts, and a urinary protein of exactly 100 mg/dL counts. The qualifying LDH and the qualifying urinary protein don't have to come from the same lab visit. Please give me one row per patient, ordered by patient ID, and nothing beyond those three fields.", "evidence": "Urinary protein is reported in mg/dL; a dipstick grade may carry the equivalent concentration in mg/dL in parentheses, e.g. '+2(100)' is 100 mg/dL. A result written as '>=' followed by a value means at least that many mg/dL, e.g. '>=300' is 300 mg/dL or more. 'TR' means a trace and '-' means none detected; any other marker is not a quantified mg/dL concentration. An LDH of 500 or higher is outside the normal range.", "SQL": "SELECT DISTINCT p.ID, p.SEX, p.Birthday FROM Patient AS p WHERE EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.LDH >= 500) AND EXISTS(SELECT 1 FROM Laboratory AS u WHERE u.ID = p.ID AND CASE WHEN u.`U-PRO` LIKE '%(%' THEN CAST(SUBSTRING(u.`U-PRO`, LOCATE('(', u.`U-PRO`) + 1, LOCATE(')', u.`U-PRO`) - LOCATE('(', u.`U-PRO`) - 1) AS FLOAT) WHEN u.`U-PRO` LIKE '>=%' THEN CAST(SUBSTRING(u.`U-PRO`, 3) AS FLOAT) ELSE CAST(u.`U-PRO` AS FLOAT) END >= 100) ORDER BY p.ID", "difficulty": "challenging"}
{"question_id": 450, "db_id": "thrombosis_prediction", "question": "Some registered patients have unknown thrombosis status because no examination has ever been recorded under their patient number. How many of these patients are women and how many are men? Please give me one row per sex with the sex of the patients and the number of such patients of that sex, and nothing else.", "evidence": "F is the code for female and M is the code for male in the patient profile.", "SQL": "SELECT P.SEX AS sex, COUNT(*) AS patients FROM Patient AS P WHERE P.SEX IN ('F', 'M') AND NOT EXISTS(SELECT 1 FROM Examination AS E WHERE E.ID = P.ID) GROUP BY P.SEX ORDER BY P.SEX", "difficulty": "challenging"}
{"question_id": 451, "db_id": "thrombosis_prediction", "question": "I need the number of female patients whose first visit to the hospital fell in 1998 (1 January 1998 through 31 December 1998) and who were admitted to the hospital. Only count patients whose sex is recorded as female; if there is no sex entry, don't count them.", "evidence": "An admission mark beginning with a plus sign means the patient was admitted to the hospital; a minus sign means the patient was followed at the outpatient clinic.", "SQL": "SELECT COUNT(*) FROM `Patient` WHERE DATE_FORMAT(`First Date`, '%Y') = '1998' AND SEX = 'F' AND `Admission` LIKE '+%'", "difficulty": "challenging"}
{"question_id": 452, "db_id": "thrombosis_prediction", "question": "I'm reviewing confirmed SLE cases for a study of neurologic involvement. Among patients whose examination lists SLE among the diagnosed diseases and who have a symptom recorded at such an examination, I need the case detail of the youngest such patient. Please send me the symptom recorded at that qualifying examination and that patient's overall diagnosis (their overall diagnosis, not the diagnosis written at the examination). If two patients share the same birth date, use the one with the smaller patient ID; and if that patient has more than one qualifying examination, use the most recent one.", "evidence": "SLE is systemic lupus erythematosus. A disease name followed by 'susp' means the disease was only suspected, not diagnosed.", "SQL": "WITH target AS (SELECT 'SLE' AS d) SELECT e.Symptoms, p.Diagnosis AS overall_diagnosis FROM Patient AS p JOIN Examination AS e ON e.ID = p.ID WHERE NOT p.Birthday IS NULL AND NOT e.Symptoms IS NULL AND TRIM(e.Symptoms) <> '' AND EXISTS(SELECT 1 FROM target WHERE REPLACE(CONCAT(',', REPLACE(e.Diagnosis, ' ', ''), ','), CONCAT(',', d, ','), '') <> CONCAT(',', REPLACE(e.Diagnosis, ' ', ''), ',')) ORDER BY p.Birthday DESC, p.ID, e.`Examination Date` DESC LIMIT 1", "difficulty": "challenging"}
{"question_id": 453, "db_id": "thrombosis_prediction", "question": "I'm auditing inpatient intake during the February 1998 admission wave. Among patients first seen at the hospital in the second half of February 1998 (visit date from 15 to 28 February 1998), find the oldest inpatient at first presentation and give me that patient's diagnosis only. If two patients tie in age, use the one with the smaller patient ID.", "evidence": "'Inpatient' means the patient was admitted to the hospital rather than followed at the outpatient clinic, regardless of whether the record notes extra detail about the admission.", "SQL": "SELECT p.Diagnosis FROM Patient AS p WHERE p.`First Date` >= '1998-02-15' AND p.`First Date` <= '1998-02-28' AND p.Admission LIKE '+%' ORDER BY p.Birthday ASC, p.ID ASC LIMIT 1", "difficulty": "challenging"}
{"question_id": 454, "db_id": "thrombosis_prediction", "question": "I'm summarizing anti-cardiolipin IgM levels for lupus patients. What was the average anti-cardiolipin IgM concentration across examinations performed between 1993-10-01 and 1993-10-31 (both days inclusive) in which systemic lupus erythematosus (SLE) was diagnosed? Please round the average to 1 decimal place.", "evidence": "SLE = systemic lupus erythematosus", "SQL": "SELECT ROUND(AVG(e.`aCL IgM`), 1) AS avg_aCL_IgM FROM Examination AS e WHERE e.`Examination Date` BETWEEN '1993-10-01' AND '1993-10-31' AND LOCATE(CONCAT(',', 'SLE', ','), CONCAT(',', REPLACE(e.Diagnosis, ' ', ''), ',')) > 0", "difficulty": "challenging"}
{"question_id": 455, "db_id": "thrombosis_prediction", "question": "How many patients in the thrombosis prediction cohort have a diagnosis of psoriatic arthritis? The count should cover every patient ever recorded in the registry, with no restriction to a time period or follow-up status. I just need that single number.", "evidence": "Psoriatic arthritis: a chronic inflammatory joint and skin disease belonging to the rheumatic diagnoses.", "SQL": "SELECT COUNT(*) AS patient_count FROM Patient WHERE UPPER(REPLACE(Diagnosis, ' ', '')) = UPPER(REPLACE('Psoriatic arthritis', ' ', ''))", "difficulty": "challenging"}
{"question_id": 456, "db_id": "thrombosis_prediction", "question": "I need to size a comparison group for my study of liver-enzyme abnormalities. How many patients in the registry have never had an ALT result above the normal range? Please give me the count broken down by sex: the number of male patients and the number of female patients. Every patient in the registry counts, including patients with no laboratory results at all, since they have never had an abnormal result. The report should cover exactly the two sexes, male and female.", "evidence": "ALT is measured by the GPT laboratory value; a GPT result of 60 or higher exceeds the normal range.", "SQL": "SELECT P.SEX AS sex, COUNT(*) AS patient_count FROM Patient AS P WHERE P.SEX IN ('M', 'F') AND NOT EXISTS(SELECT 1 FROM Laboratory AS L WHERE L.ID = P.ID AND L.GPT >= 60) GROUP BY P.SEX ORDER BY P.SEX", "difficulty": "challenging"}
{"question_id": 457, "db_id": "thrombosis_prediction", "question": "For patients with at least one red-blood-cell result below 3.5 (RBC), I need a breakdown by care setting: how many patients were admitted to the hospital (+) versus followed at the outpatient clinic (-), and the average completed age of each group on 2026-10-09, rounded to one decimal place. Age means completed years on 2026-10-09.", "evidence": "Red-blood-cell result below 3.5 (RBC); admission status + marks a patient admitted to the hospital, - marks a patient followed at the outpatient clinic.", "SQL": "SELECT p.Admission AS care_setting, COUNT(*) AS patient_count, ROUND(AVG(CAST(DATE_FORMAT('2026-10-09', '%Y') AS SIGNED) - CAST(DATE_FORMAT(p.Birthday, '%Y') AS SIGNED) - CASE WHEN DATE_FORMAT('2026-10-09', '%m-%d') < DATE_FORMAT(p.Birthday, '%m-%d') THEN 1 ELSE 0 END), 1) AS average_age FROM Patient AS p WHERE p.Admission IN ('+', '-') AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.RBC < 3.5) GROUP BY p.Admission ORDER BY p.Admission COLLATE utf8mb4_bin", "difficulty": "challenging"}
{"question_id": 458, "db_id": "thrombosis_prediction", "question": "Among the patients who have laboratory test records on file, how many are female and how many are male? Please give me one line for the female patients and one line for the male patients, each showing the sex and the number of patients of that sex.", "evidence": "", "SQL": "SELECT p.SEX AS sex, COUNT(DISTINCT p.ID) AS patient_count FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE p.SEX IN ('F', 'M') GROUP BY p.SEX", "difficulty": "challenging"}
{"question_id": 459, "db_id": "thrombosis_prediction", "question": "I'm studying antiphospholipid antibodies in Sjögren's syndrome (SJS). Could you tell me the average anti-cardiolipin IgM concentration among SJS patients, rounded to two decimal places? To clarify: use only patients with an established SJS diagnosis recorded at the patient level (a diagnosis marked 'susp', such as 'SJS susp', is only a suspicion and those patients should not be included). Include every examination recorded for these patients regardless of date. A recorded anti-cardiolipin IgM value of 0 means the antibody was not detected at that examination, so treat it as no measurement and leave it out of the average - count only examinations where a concentration was detected.", "evidence": "SJS is the abbreviation used for Sjögren's syndrome; a diagnosis marked 'susp' (e.g. 'SJS susp') is only a suspicion of the disease, not an established diagnosis.", "SQL": "WITH RECURSIVE tokens AS (SELECT ID, CAST('' AS CHAR(2048)) AS tok, CONCAT(COALESCE(Diagnosis, ''), ',') AS rest FROM Patient UNION ALL SELECT ID, TRIM(SUBSTRING(rest, 1, LOCATE(',', rest) - 1)), SUBSTRING(rest, LOCATE(',', rest) + 1) FROM tokens WHERE rest <> '') SELECT ROUND(AVG(CASE WHEN e.`aCL IgM` > 0 THEN e.`aCL IgM` END), 2) AS avg_aCL_IgM FROM Examination AS e WHERE e.ID IN (SELECT ID FROM tokens WHERE tok = 'SJS')", "difficulty": "challenging"}
{"question_id": 460, "db_id": "thrombosis_prediction", "question": "How many female patients have a Sjögren's syndrome diagnosis recorded in a medical examination? Please count across the full examination history with no date restriction, and note that suspected cases don't count—only an actual SjS diagnosis should be included. I just need that single number.", "evidence": "SjS is the standard medical abbreviation for Sjögren's syndrome, and the diagnosis is recorded under that abbreviation.", "SQL": "SELECT COUNT(DISTINCT T1.ID) AS n_female_sjs_patients FROM Patient AS T1 JOIN Examination AS T2 ON T1.ID = T2.ID WHERE T1.SEX = 'F' AND (CONCAT(',', REPLACE(T2.Diagnosis, ' ', ''), ',')) LIKE (CONCAT('%', ',', 'SjS', ',', '%'))", "difficulty": "challenging"}
{"question_id": 461, "db_id": "thrombosis_prediction", "question": "How many patients who were never admitted to the hospital (outpatient follow-up only) had at least one normal anti-ribonuclear protein (RNP) result? A normal RNP result means the test found no anti-ribonuclear protein antibody: a negative result, or a measured value of zero. I just need a single number.", "evidence": "anti-ribonuclear protein (RNP): an antibody test", "SQL": "SELECT COUNT(DISTINCT p.ID) AS patient_count FROM Patient AS p JOIN Laboratory AS l ON p.ID = l.ID WHERE p.Admission = '-' AND l.RNP IN ('negative', '0')", "difficulty": "challenging"}
{"question_id": 462, "db_id": "thrombosis_prediction", "question": "I'd like to know, among patients who have at least one normal anti-SM laboratory result (recorded as 'negative' or '0') and whose examinations show no thrombosis, how many have ever had significant proteinuria on any laboratory record. Significant proteinuria means 30 mg/dl or more; '-' and 'TR' count as no proteinuria. I only need the number of such patients.", "evidence": "anti-SM: normal is recorded as 'negative' or '0'; proteinuria is measured semi-quantitatively as '-', 'TR', or the approximate daily urinary protein excretion in mg/dl", "SQL": "SELECT COUNT(*) AS patient_count FROM Patient AS p WHERE EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND l.SM IN ('negative', '0')) AND EXISTS(SELECT 1 FROM Examination AS e WHERE e.ID = p.ID AND e.Thrombosis = 0) AND NOT EXISTS(SELECT 1 FROM Examination AS e WHERE e.ID = p.ID AND e.Thrombosis <> 0) AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND CAST(l.`U-PRO` AS FLOAT) >= 30)", "difficulty": "challenging"}
{"question_id": 463, "db_id": "thrombosis_prediction", "question": "Which patients followed at the outpatient clinic have both an abnormal red blood cell count and a positive anti-ribonuclear protein antibody result? Please return the patient IDs. Note: the two findings don't need to be from the same laboratory visit - a patient qualifies if at least one lab test shows an abnormal RBC and at least one, possibly different, lab test shows a positive anti-ribonuclear protein antibody. Here, a positive anti-ribonuclear protein antibody means a titer above zero, an abnormal RBC means RBC <= 3.5 or RBC >= 6.0, and outpatient follow-up means Admission = '-'.", "evidence": "", "SQL": "SELECT T1.ID FROM Patient AS T1 WHERE T1.Admission = '-' AND EXISTS(SELECT 1 FROM Laboratory AS L1 WHERE L1.ID = T1.ID AND (L1.RBC <= 3.5 OR L1.RBC >= 6)) AND EXISTS(SELECT 1 FROM Laboratory AS L2 WHERE L2.ID = T1.ID AND CAST(L2.RNP AS FLOAT) > 0) ORDER BY T1.ID", "difficulty": "challenging"}
{"question_id": 464, "db_id": "thrombosis_prediction", "question": "In our autoimmune-cohort registry, I'm profiling young patients with strongly positive anti-RNP findings. What is the average age, in years, of the patients who were younger than 70 as of 2026-10-09 and who have at least one anti-RNP result of 64 or higher? Please give the average as a single number to one decimal place.", "evidence": "anti-ribonuclear protein (anti-RNP) result: the reading recorded for a patient's anti-RNP test in the laboratory record", "SQL": "SELECT ROUND(AVG(CAST(SUBSTRING('2026-10-09', 1, 4) AS SIGNED) - CAST(SUBSTRING(p.Birthday, 1, 4) AS SIGNED) - (SUBSTRING('2026-10-09', 6) < SUBSTRING(p.Birthday, 6))), 1) AS average_age FROM Patient AS p WHERE (CAST(SUBSTRING('2026-10-09', 1, 4) AS SIGNED) - CAST(SUBSTRING(p.Birthday, 1, 4) AS SIGNED) - (SUBSTRING('2026-10-09', 6) < SUBSTRING(p.Birthday, 6))) < 70 AND EXISTS(SELECT 1 FROM Laboratory AS l WHERE l.ID = p.ID AND CAST(l.RNP AS FLOAT) >= 64)", "difficulty": "challenging"}
{"question_id": 465, "db_id": "thrombosis_prediction", "question": "I'd like a single number: how many female patients in the thrombosis prediction data have a laboratory record showing a normal white blood cell count, an abnormal fibrinogen level, and an anti-ribonuclear protein (RNP) reading above 15, considering all recorded laboratory dates?", "evidence": "A normal white blood cell count means strictly between 3.5 and 9.0; an abnormal fibrinogen level means at most 150 or at least 450.", "SQL": "SELECT COUNT(DISTINCT p.ID) FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE p.SEX = 'F' AND l.WBC > 3.5 AND l.WBC < 9.0 AND (l.FG <= 150 OR l.FG >= 450) AND CAST(l.RNP AS FLOAT) > 15", "difficulty": "challenging"}
{"question_id": 466, "db_id": "thrombosis_prediction", "question": "As part of our clinical audit I'm profiling patients born between 1936 and 1956 inclusive who never had a creatinine phosphokinase (CPK) result above the normal range. A CPK of 250 or higher counts as above the normal range, and patients with no CPK results on record count as never having exceeded it. For that group, please give me the women's percentage of the group's men and women, rounded to one decimal place.", "evidence": "Creatinine phosphokinase (CPK) of 250 or higher is above the normal range.", "SQL": "SELECT ROUND(CAST(SUM(CASE WHEN SEX = 'F' THEN 1 ELSE 0 END) AS FLOAT) * 100 / SUM(CASE WHEN SEX IN ('M', 'F') THEN 1 ELSE 0 END), 1) AS percentage FROM Patient WHERE DATE_FORMAT(Birthday, '%Y') BETWEEN '1936' AND '1956' AND NOT EXISTS(SELECT 1 FROM Laboratory WHERE Laboratory.ID = Patient.ID AND Laboratory.CPK >= 250)", "difficulty": "challenging"}
{"question_id": 467, "db_id": "thrombosis_prediction", "question": "I'm preparing a case series on early renal involvement and need to size my cohort. How many patients were under age 50 on the day of a laboratory test performed between 1 January 1981 and 31 December 1986 inclusive, had a platelet count from 100 through 400 at that test, and showed proteinuria at that test? Age means completed years on the day of the test, so under 50 is strictly below 50. The platelet range is inclusive. I just need the number of patients satisfying all conditions.", "evidence": "A patient showed proteinuria at a test when that test's dipstick reading reports protein: a dash or zero means no protein was found, a number is the amount of protein found, TR stands for trace protein, and a reading written in percent signs is the dipstick saturated, the strongest reading.", "SQL": "SELECT COUNT(DISTINCT p.ID) AS patient_count FROM Patient AS p JOIN Laboratory AS l ON l.ID = p.ID WHERE SUBSTRING(l.Date, 1, 4) BETWEEN '1981' AND '1986' AND l.PLT BETWEEN 100 AND 400 AND NOT p.Birthday IS NULL AND (CAST(SUBSTRING(l.Date, 1, 4) AS SIGNED) - CAST(SUBSTRING(p.Birthday, 1, 4) AS SIGNED) - CASE WHEN SUBSTRING(l.Date, 6, 5) < SUBSTRING(p.Birthday, 6, 5) THEN 1 ELSE 0 END) < 50 AND NOT l.`U-PRO` IS NULL AND NOT l.`U-PRO` IN ('-', '0')", "difficulty": "challenging"}
{"question_id": 468, "db_id": "toxicology", "question": "Among molecules containing at least one single bond, what is the average number of oxygen atoms per molecule? Include molecules with no oxygen and round to four decimal places.", "evidence": "The '-' bond-type symbol denotes a single bond.", "SQL": "WITH molecules AS (SELECT DISTINCT molecule_id FROM bond WHERE bond_type = '-'), oxygen AS (SELECT molecule_id, COUNT(*) AS n FROM atom WHERE element = 'o' GROUP BY molecule_id) SELECT ROUND(AVG(COALESCE(oxygen.n, 0)), 4) FROM molecules LEFT JOIN oxygen ON oxygen.molecule_id = molecules.molecule_id", "difficulty": "moderate"}
{"question_id": 469, "db_id": "toxicology", "question": "Among carcinogenic molecules with at least one single bond, what is the average number of single bonds per molecule?", "evidence": "In this dataset, '+' denotes a carcinogenic molecule and '-' denotes a single bond.", "SQL": "SELECT AVG(single_bond_count) FROM (SELECT b.molecule_id, COUNT(*) AS single_bond_count FROM bond AS b JOIN molecule AS m ON m.molecule_id = b.molecule_id WHERE m.label = '+' AND b.bond_type = '-' GROUP BY b.molecule_id) AS per_molecule", "difficulty": "challenging"}
{"question_id": 470, "db_id": "toxicology", "question": "Which elements have the fewest atom occurrences across non-carcinogenic molecules? Include all elements tied for the minimum.", "evidence": "A '-' carcinogenicity label means non-carcinogenic.", "SQL": "WITH counts AS (SELECT a.element, COUNT(*) AS n FROM atom AS a JOIN molecule AS m ON m.molecule_id = a.molecule_id WHERE m.label = '-' GROUP BY a.element) SELECT element FROM counts WHERE n = (SELECT MIN(n) FROM counts) ORDER BY element", "difficulty": "challenging"}
{"question_id": 471, "db_id": "toxicology", "question": "How many distinct iodine atoms and distinct sulfur atoms, respectively, participate in at least one single bond?", "evidence": "The '-' bond-type symbol denotes a single bond.", "SQL": "SELECT COUNT(DISTINCT CASE WHEN T1.element = 'i' THEN T1.atom_id ELSE NULL END) AS iodine_nums, COUNT(DISTINCT CASE WHEN T1.element = 's' THEN T1.atom_id ELSE NULL END) AS sulfur_nums FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id INNER JOIN bond AS T3 ON T2.bond_id = T3.bond_id WHERE T3.bond_type = '-'", "difficulty": "challenging"}
{"question_id": 472, "db_id": "toxicology", "question": "Among carcinogenic molecules, what percentage contain no fluorine atoms? Round to two decimal places.", "evidence": "A '+' carcinogenicity label means carcinogenic.", "SQL": "SELECT ROUND(100.0 * SUM(CASE WHEN NOT EXISTS(SELECT 1 FROM atom AS a WHERE a.molecule_id = m.molecule_id AND a.element = 'f') THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) FROM molecule AS m WHERE m.label = '+'", "difficulty": "challenging"}
{"question_id": 473, "db_id": "toxicology", "question": "What is the most common bond type in molecule TR010, and is that molecule carcinogenic? Return the bond type and YES or NO.", "evidence": "In this dataset, a molecule labeled '+' is carcinogenic; a molecule labeled '-' is not.", "SQL": "SELECT b.bond_type, CASE WHEN m.label = '+' THEN 'YES' ELSE 'NO' END FROM bond AS b JOIN molecule AS m ON m.molecule_id = b.molecule_id WHERE b.molecule_id = 'TR010' GROUP BY b.bond_type, m.label ORDER BY COUNT(*) DESC, b.bond_type LIMIT 1", "difficulty": "challenging"}
{"question_id": 474, "db_id": "toxicology", "question": "What are the bonds that have phosphorus and nitrogen as their atom elements?", "evidence": "", "SQL": "SELECT T2.bond_id FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id WHERE T2.bond_id IN (SELECT T3.bond_id FROM connected AS T3 INNER JOIN atom AS T4 ON T3.atom_id = T4.atom_id WHERE T4.element = 'p') AND T1.element = 'n'", "difficulty": "moderate"}
{"question_id": 475, "db_id": "toxicology", "question": "List the distinct elements of atoms that do not participate in any bond.", "evidence": "", "SQL": "SELECT DISTINCT a.element FROM atom AS a WHERE NOT a.atom_id IN (SELECT atom_id FROM connected UNION SELECT atom_id2 FROM connected) ORDER BY a.element", "difficulty": "challenging"}
{"question_id": 476, "db_id": "toxicology", "question": "How many atoms occur in molecules that have at least one triple bond and at least one phosphorus or bromine atom?", "evidence": "The '#' bond-type symbol denotes a triple bond.", "SQL": "WITH triple AS (SELECT DISTINCT molecule_id FROM bond WHERE bond_type = '#'), hetero AS (SELECT DISTINCT molecule_id FROM atom WHERE element IN ('p', 'br')), qualified AS (SELECT t.molecule_id FROM triple AS t JOIN hetero AS h ON h.molecule_id = t.molecule_id) SELECT COUNT(*) FROM atom AS a JOIN qualified AS q ON q.molecule_id = a.molecule_id", "difficulty": "moderate"}
{"question_id": 477, "db_id": "toxicology", "question": "Among all atoms in molecules containing at least one single bond, what percentage are chlorine atoms? Round to four decimal places.", "evidence": "The '-' bond-type symbol denotes a single bond.", "SQL": "WITH molecules AS (SELECT DISTINCT molecule_id FROM bond WHERE bond_type = '-') SELECT ROUND(100.0 * SUM(CASE WHEN a.element = 'cl' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 4) FROM molecules AS m JOIN atom AS a ON a.molecule_id = m.molecule_id", "difficulty": "challenging"}
{"question_id": 478, "db_id": "toxicology", "question": "What fraction of all atoms in molecule TR006 are hydrogen? Give the fraction and the molecule's recorded carcinogenicity label.", "evidence": "", "SQL": "WITH SubQuery AS (SELECT DISTINCT T1.atom_id, T1.element, T1.molecule_id, T2.label FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.molecule_id = 'TR006') SELECT CAST(COUNT(CASE WHEN element = 'h' THEN atom_id ELSE NULL END) AS FLOAT) / (CASE WHEN COUNT(atom_id) = 0 THEN NULL ELSE COUNT(atom_id) END) AS ratio, label FROM SubQuery GROUP BY label", "difficulty": "challenging"}
{"question_id": 479, "db_id": "toxicology", "question": "I want to know whether molecular saturation is associated with carcinogenicity in our compound library. Please report, for molecules in which every bond is a single bond: the number of carcinogenic molecules minus the number of non-carcinogenic molecules. And for all other molecules: the same difference (carcinogenic count minus non-carcinogenic count). Rules: label '+' means the molecule is carcinogenic; label '-' means non-carcinogenic; bond type '-' denotes a single bond; each molecule belongs to exactly one of the two groups.", "evidence": "In the labels, '+' indicates a carcinogenic molecule and '-' indicates a non-carcinogenic molecule; for bond types, '-' indicates a single bond.", "SQL": "SELECT (SELECT SUM(CASE WHEN m.label = '+' THEN 1 ELSE -1 END) FROM molecule AS m WHERE NOT EXISTS(SELECT 1 FROM bond AS b WHERE b.molecule_id = m.molecule_id AND b.bond_type <> '-')) AS diff_molecules_with_only_single_bonds, (SELECT SUM(CASE WHEN m.label = '+' THEN 1 ELSE -1 END) FROM molecule AS m WHERE EXISTS(SELECT 1 FROM bond AS b WHERE b.molecule_id = m.molecule_id AND b.bond_type <> '-')) AS diff_other_molecules", "difficulty": "challenging"}
{"question_id": 480, "db_id": "toxicology", "question": "In our toxicology library, how many carbon-carbon pairs joined by a double bond are there in total across the carcinogenic compounds? I want a single number for the whole library.", "evidence": "A compound is carcinogenic when its label is '+' and non-carcinogenic when its label is '-'. In the bond notation, '-' is a single bond, '=' is a double bond, and '#' is a triple bond.", "SQL": "SELECT COUNT(*) AS num_pairs FROM connected AS c JOIN bond AS b ON b.bond_id = c.bond_id JOIN molecule AS m ON m.molecule_id = b.molecule_id JOIN atom AS a1 ON a1.atom_id = c.atom_id JOIN atom AS a2 ON a2.atom_id = c.atom_id2 WHERE m.label = '+' AND b.bond_type = '=' AND a1.element = 'c' AND a2.element = 'c' AND c.atom_id < c.atom_id2", "difficulty": "challenging"}
{"question_id": 481, "db_id": "toxicology", "question": "Among the molecules labeled '+' (carcinogenic), which chemical element is the most common among the atoms that take part in at least one bond? Also give the percentage of all atoms in those '+' molecules that this element accounts for, rounded to two decimal places. Count the percentage over every atom of the '+' molecules, whether or not it takes part in a bond. If several elements tie for most common, report each of them.", "evidence": "", "SQL": "WITH plus_atoms AS (SELECT a.atom_id, a.element FROM atom AS a JOIN molecule AS m ON m.molecule_id = a.molecule_id WHERE m.label = '+'), bonded AS (SELECT atom_id, element FROM plus_atoms WHERE atom_id IN (SELECT atom_id FROM connected) OR atom_id IN (SELECT atom_id2 FROM connected)), bonded_counts AS (SELECT element, COUNT(*) AS n FROM bonded GROUP BY element), top AS (SELECT MAX(n) AS mx FROM bonded_counts), all_counts AS (SELECT element, COUNT(*) AS na FROM plus_atoms GROUP BY element), total AS (SELECT COUNT(*) AS tot FROM plus_atoms) SELECT bc.element, ROUND(100.0 * ac.na / t.tot, 2) AS pct FROM bonded_counts AS bc JOIN top ON bc.n = top.mx JOIN all_counts AS ac ON ac.element = bc.element CROSS JOIN total AS t ORDER BY bc.element", "difficulty": "challenging"}
{"question_id": 482, "db_id": "toxicology", "question": "For the molecule containing atom TR041_10, I'd like to know the molecule id, whether it's carcinogenic (YES or NO), and the number of multiple bonds in that molecule. Please use the rule that a molecule labeled '+' is carcinogenic (YES) and one labeled '-' is not (NO).", "evidence": "", "SQL": "SELECT T2.molecule_id, IF(T2.label = '+', 'YES', 'NO') AS flag_carcinogenic, COUNT(T3.bond_id) AS multiple_bonds FROM atom AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN bond AS T3 ON T3.molecule_id = T2.molecule_id WHERE T1.atom_id = 'TR041_10' AND T3.bond_type <> '-' GROUP BY T2.molecule_id, T2.label", "difficulty": "challenging"}
{"question_id": 483, "db_id": "toxicology", "question": "For the carcinogenic molecules in the toxicology database, how many carbon-carbon bonds are there of each bond type (single, double, and triple)? Please give me the bond type and the corresponding count.", "evidence": "A molecule labelled '+' is carcinogenic. Bond types are recorded as follows: a single bond as '-', a double bond as '=', and a triple bond as '#'. A carbon-carbon bond is a bond whose two bonded atoms are both carbon.", "SQL": "SELECT b.bond_type, COUNT(DISTINCT c.bond_id) AS bond_count FROM connected AS c JOIN atom AS a1 ON a1.atom_id = c.atom_id JOIN atom AS a2 ON a2.atom_id = c.atom_id2 JOIN bond AS b ON b.bond_id = c.bond_id JOIN molecule AS m ON m.molecule_id = b.molecule_id WHERE a1.element = 'c' AND a2.element = 'c' AND m.label = '+' GROUP BY b.bond_type ORDER BY b.bond_type", "difficulty": "challenging"}
{"question_id": 484, "db_id": "toxicology", "question": "I want to know how widely chlorine atoms bond to other atoms across the toxicology database. Please give me a single number: the count of atoms that bond with chlorine atoms. Nothing else.", "evidence": "Chlorine means the element recorded under the code cl.", "SQL": "SELECT COUNT(DISTINCT CASE WHEN a1.element = 'cl' THEN c.atom_id2 ELSE c.atom_id END) AS bonded_atoms FROM connected AS c JOIN atom AS a1 ON c.atom_id = a1.atom_id JOIN atom AS a2 ON c.atom_id2 = a2.atom_id WHERE a1.element = 'cl' OR a2.element = 'cl'", "difficulty": "challenging"}
{"question_id": 485, "db_id": "toxicology", "question": "I'm studying the immediate chemical environment of sulfur atoms in carcinogenic molecules. Please tell me, as a single number, how many atoms are directly bonded to a sulfur atom in carcinogenic molecules. A molecule labeled '+' is carcinogenic; a molecule labeled '-' is not.", "evidence": "Sulfur refers to the element 's'. A direct bond is a bond between two atoms.", "SQL": "SELECT COUNT(DISTINCT T2.atom_id2) AS atom_count FROM atom AS T1 INNER JOIN connected AS T2 ON T1.atom_id = T2.atom_id INNER JOIN molecule AS M ON T1.molecule_id = M.molecule_id WHERE T1.element = 's' AND M.label = '+'", "difficulty": "challenging"}
{"question_id": 486, "db_id": "toxicology", "question": "I'm compiling bond records of unusual carcinogenic molecules for a structural alert review. Please find the bonds that belong to carcinogenic molecules (labelled '+') that contain an element recorded for no other molecule in the dataset. Note that this search covers the whole dataset, so an element counts as belonging to no other molecule when no molecule other than the one at hand records it. For each such bond, return only the bond id and molecule id.", "evidence": "A '+' label means carcinogenic.", "SQL": "SELECT T1.bond_id, T1.molecule_id FROM bond AS T1 INNER JOIN molecule AS T2 ON T1.molecule_id = T2.molecule_id WHERE T2.label = '+' AND EXISTS(SELECT 1 FROM atom AS a WHERE a.molecule_id = T1.molecule_id AND a.element IN (SELECT element FROM atom GROUP BY element HAVING COUNT(DISTINCT molecule_id) = 1))", "difficulty": "challenging"}
{"question_id": 487, "db_id": "toxicology", "question": "I'm building a control group of nitrogen-containing structures for a carcinogenicity review. How many molecules in the database contain at least one nitrogen atom, where none of those nitrogen atoms takes part in a double bond or a triple bond? A nitrogen held only by single bonds is fine; any nitrogen in a double or triple bond disqualifies the molecule. Molecules with no nitrogen at all don't count. I just need the single number of such molecules.", "evidence": "Nitrogen refers to the element code 'n'; '=' denotes a double bond; '#' denotes a triple bond; '-' denotes a single bond.", "SQL": "SELECT COUNT(*) AS number_of_molecules FROM molecule AS m WHERE EXISTS(SELECT 1 FROM atom AS a WHERE a.molecule_id = m.molecule_id AND a.element = 'n') AND NOT EXISTS(SELECT 1 FROM atom AS a2 INNER JOIN connected AS c ON c.atom_id = a2.atom_id OR c.atom_id2 = a2.atom_id INNER JOIN bond AS b ON b.bond_id = c.bond_id WHERE a2.molecule_id = m.molecule_id AND a2.element = 'n' AND b.bond_type <> '-')", "difficulty": "challenging"}
{"question_id": 488, "db_id": "toxicology", "question": "In the toxicology database, how many atoms are bonded to chlorine atoms, taken across all molecules? I want a single number. By chlorine I mean the element 'cl'.", "evidence": "cl: chlorine", "SQL": "SELECT COUNT(DISTINCT T1.atom_id) AS bonded_atom_count FROM connected AS T1 INNER JOIN atom AS T2 ON T1.atom_id2 = T2.atom_id WHERE T2.element = 'cl'", "difficulty": "challenging"}
{"question_id": 489, "db_id": "toxicology", "question": "For a report on structural features of carcinogenic compounds, I'm looking at compounds that form a triple bond. Among those, what percent are labeled carcinogenic and what percent are labeled non-carcinogenic, each rounded to two decimal places? The two percents should sum to 100, apart from rounding.", "evidence": "Label '+' means carcinogenic; label '-' means non-carcinogenic.", "SQL": "SELECT ROUND(CAST(COUNT(DISTINCT CASE WHEN m.label = '+' THEN b.molecule_id END) AS FLOAT) * 100 / COUNT(DISTINCT b.molecule_id), 2) AS pct_carcinogenic, ROUND(CAST(COUNT(DISTINCT CASE WHEN m.label = '-' THEN b.molecule_id END) AS FLOAT) * 100 / COUNT(DISTINCT b.molecule_id), 2) AS pct_non_carcinogenic FROM bond AS b JOIN molecule AS m ON b.molecule_id = m.molecule_id WHERE b.bond_type = '#'", "difficulty": "challenging"}
{"question_id": 490, "db_id": "toxicology", "question": "I'm characterizing how strongly rare chemical elements are integrated into the molecular skeleton of carcinogenic compounds. For every carcinogenic molecule that contains at least one atom of an element that appears in no other molecule in the database, I want the number of bonds its atoms of that element take part in. Please judge an element's rarity over every molecule in the database, carcinogenic or not. Return the molecule_id and that bond count for each qualifying molecule, one row per molecule, sorted by molecule_id.", "evidence": "'+' is the label of a carcinogenic molecule, '-' of a non-carcinogenic one; a bond is a link between two atoms of a molecule.", "SQL": "WITH rare AS (SELECT element FROM atom GROUP BY element HAVING COUNT(DISTINCT molecule_id) = 1) SELECT m.molecule_id, COUNT(DISTINCT c.bond_id) AS bond_count FROM molecule AS m INNER JOIN atom AS a ON a.molecule_id = m.molecule_id LEFT JOIN connected AS c ON (c.atom_id = a.atom_id OR c.atom_id2 = a.atom_id) WHERE m.label = '+' AND a.element IN (SELECT element FROM rare) GROUP BY m.molecule_id ORDER BY m.molecule_id", "difficulty": "challenging"}
{"question_id": 491, "db_id": "toxicology", "question": "I'd like a ranked inventory of every molecule in the toxicology database that contains at least one carbon atom. For each qualifying molecule, give me its molecule id, carcinogenicity label, number of atoms, number of bonds, number of carbon atoms, number of chlorine atoms, number of carbon-touching bonds, and number of multiple bonds - one row per molecule, including molecules where some of these counts are zero. Rank the rows from the most carbon-touching bonds to the fewest; break ties by larger total atom count, then by molecule id ascending. Give consecutive rank positions 1, 2, 3, ... with no gaps after ties.", "evidence": "A carbon-touching bond is a bond with a carbon atom at one of its ends; a bond between two carbon atoms counts as one bond. A multiple bond is a double or triple bond. The carcinogenicity label '+' means carcinogenic, '-' means not carcinogenic.", "SQL": "WITH CarbonBonds AS (SELECT a.molecule_id, COUNT(DISTINCT c.bond_id) AS carbon_bond_count FROM connected AS c JOIN atom AS a ON c.atom_id = a.atom_id WHERE a.element = 'c' GROUP BY a.molecule_id), MoleculeStats AS (SELECT m.molecule_id, m.label, (SELECT COUNT(*) FROM atom AS a WHERE a.molecule_id = m.molecule_id) AS atom_count, (SELECT COUNT(*) FROM bond AS b WHERE b.molecule_id = m.molecule_id) AS bond_count, (SELECT COUNT(*) FROM atom AS a WHERE a.molecule_id = m.molecule_id AND a.element = 'c') AS carbon_count, (SELECT COUNT(*) FROM atom AS a WHERE a.molecule_id = m.molecule_id AND a.element = 'cl') AS chlorine_count, (SELECT COUNT(*) FROM bond AS b WHERE b.molecule_id = m.molecule_id AND b.bond_type <> '-') AS multiple_bond_count FROM molecule AS m WHERE m.molecule_id IN (SELECT molecule_id FROM atom WHERE element = 'c')), Ranked AS (SELECT ms.molecule_id, ms.label, ms.atom_count, ms.bond_count, ms.carbon_count, ms.chlorine_count, COALESCE(cb.carbon_bond_count, 0) AS carbon_touching_bonds, ms.multiple_bond_count, ROW_NUMBER() OVER (ORDER BY COALESCE(cb.carbon_bond_count, 0) DESC, ms.atom_count DESC, ms.molecule_id) AS position FROM MoleculeStats AS ms LEFT JOIN CarbonBonds AS cb ON cb.molecule_id = ms.molecule_id) SELECT position, molecule_id, label, atom_count, bond_count, carbon_count, chlorine_count, carbon_touching_bonds, multiple_bond_count FROM Ranked ORDER BY position", "difficulty": "challenging"}
{"question_id": 492, "db_id": "toxicology", "question": "I'm studying the hydrogen bonding pattern of the molecule that contains the yttrium atom. How many bonds in that molecule have a hydrogen atom at one end? Just give me the single overall count, please.", "evidence": "An yttrium atom has element symbol Y; a hydrogen atom has element symbol H.", "SQL": "SELECT COUNT(DISTINCT c.bond_id) AS bond_count FROM connected AS c JOIN atom AS a ON a.atom_id = c.atom_id OR a.atom_id = c.atom_id2 WHERE a.element = 'h' AND a.molecule_id = (SELECT molecule_id FROM atom WHERE element = 'y')", "difficulty": "challenging"}
{"question_id": 493, "db_id": "toxicology", "question": "As part of a connectivity review, I'd like to know how heavily atoms are connected in molecule TR397: what is the average number of bonds an atom of TR397 has? Please give me just that one number, rounded to two decimal places.", "evidence": "", "SQL": "SELECT ROUND(AVG(cnt), 2) AS avg_bonds_per_atom FROM (SELECT a.atom_id, COUNT(DISTINCT c.bond_id) AS cnt FROM atom AS a LEFT JOIN connected AS c ON (c.atom_id = a.atom_id OR c.atom_id2 = a.atom_id) WHERE a.molecule_id = 'TR397' GROUP BY a.atom_id) AS __photo_derived_1", "difficulty": "challenging"}
{"question_id": 494, "db_id": "toxicology", "question": "I'm studying bond patterns in compounds that are not carcinogenic. For each element, how many double or triple bonds join a carbon atom to an atom of that element, across all non-carcinogenic molecules? Give me one row per element with the element and its count of such bonds—nothing else.", "evidence": "A molecule labeled '-' is not carcinogenic; a molecule labeled '+' is carcinogenic.", "SQL": "SELECT a2.element AS element, COUNT(DISTINCT c.bond_id) AS bond_count FROM connected AS c JOIN bond AS b ON c.bond_id = b.bond_id JOIN atom AS a1 ON c.atom_id = a1.atom_id JOIN atom AS a2 ON c.atom_id2 = a2.atom_id JOIN molecule AS m ON b.molecule_id = m.molecule_id WHERE m.label = '-' AND a1.element = 'c' AND b.bond_type <> '-' GROUP BY a2.element ORDER BY a2.element", "difficulty": "challenging"}
{"question_id": 495, "db_id": "toxicology", "question": "For molecule TR377, I'd like a profile of its bond composition, covering single and double bonds only. For each bond kind, please give me: the bond kind symbol, the number of bonds of that kind in the molecule, and the number of element pairs that bond kind joins. Also include the molecule's carcinogenicity label. List the bond kinds from most frequent to least; if two kinds are equally frequent, list them alphabetically by symbol.", "evidence": "A single bond is shown as the symbol '-' and a double bond as '='; a molecule label '+' means carcinogenic and '-' means not carcinogenic.", "SQL": "WITH scoped AS (SELECT bond_type, COUNT(*) AS bond_count FROM bond WHERE molecule_id = 'TR377' AND bond_type IN ('-', '=') GROUP BY bond_type), pairs AS (SELECT b.bond_type, COUNT(DISTINCT CASE WHEN a1.element < a2.element THEN CONCAT(a1.element, '-', a2.element) ELSE CONCAT(a2.element, '-', a1.element) END) AS pair_count FROM bond AS b JOIN connected AS c ON c.bond_id = b.bond_id JOIN atom AS a1 ON a1.atom_id = c.atom_id JOIN atom AS a2 ON a2.atom_id = c.atom_id2 WHERE b.molecule_id = 'TR377' AND b.bond_type IN ('-', '=') GROUP BY b.bond_type) SELECT s.bond_type, s.bond_count, p.pair_count, m.label AS molecule_label FROM scoped AS s JOIN pairs AS p ON p.bond_type = s.bond_type JOIN molecule AS m ON m.molecule_id = 'TR377' ORDER BY s.bond_count DESC, s.bond_type", "difficulty": "challenging"}
{"question_id": 496, "db_id": "toxicology", "question": "I'm screening for molecules to flag for follow-up. Can you give me the molecule_id of the first three molecules, in alphabetical order, that are non-carcinogenic, contain at least one metal atom, and have single bonds between their atoms? Please return only the molecule ids.", "evidence": "A molecule label of '-' means the molecule is non-carcinogenic. A bond type of '-' means a single bond between two atoms. The metals are sodium (na), potassium (k), calcium (ca), copper (cu), zinc (zn), tin (sn), lead (pb), magnesium (mg) and lithium (li).", "SQL": "SELECT DISTINCT T1.molecule_id FROM molecule AS T1 INNER JOIN bond AS T2 ON T1.molecule_id = T2.molecule_id INNER JOIN atom AS T3 ON T1.molecule_id = T3.molecule_id WHERE T2.bond_type = '-' AND T1.label = '-' AND T3.element IN ('na', 'k', 'ca', 'cu', 'zn', 'sn', 'pb', 'mg', 'li') ORDER BY T1.molecule_id LIMIT 3", "difficulty": "challenging"}
{"question_id": 497, "db_id": "toxicology", "question": "I'm profiling the compound library and want to size the fully saturated portion of each element's atom population - atoms attached only by single bonds behave differently from unsaturated sites. For each element symbol in the database, how many atoms are connected only by single bonds and never part of any multiple bond? Please give me one row per element symbol with the element symbol and the number of such atoms, sorted alphabetically by element symbol. This should cover all compounds in the database. Note that an atom with no bonds at all doesn't count as being connected by single bonds, so exclude those.", "evidence": "A single bond is a bond between two atoms sharing exactly one electron pair, denoted by the bond-type symbol '-'. A multiple bond is a double or triple bond, i.e. a bond between two atoms sharing more than one electron pair.", "SQL": "WITH per_atom AS (SELECT a.atom_id AS atom_id, a.element AS element, CASE WHEN EXISTS(SELECT 1 FROM connected AS c WHERE c.atom_id = a.atom_id) AND NOT EXISTS(SELECT 1 FROM connected AS c JOIN bond AS b ON b.bond_id = c.bond_id WHERE c.atom_id = a.atom_id AND b.bond_type <> '-') THEN 1 ELSE 0 END AS saturated FROM atom AS a) SELECT element, SUM(saturated) AS atoms FROM per_atom GROUP BY element ORDER BY element", "difficulty": "challenging"}
{"question_id": 498, "db_id": "toxicology", "question": "In the toxicology compound database, which elements take part in a triple bond, and how widely are they distributed across the tested compounds? For each such element, give me its element symbol and the number of molecules that contain that element. Order the results from the most widespread element to the least; where two elements have equal counts, list them alphabetically by element symbol.", "evidence": "The '#' bond-type symbol denotes a triple bond.", "SQL": "SELECT a.element AS element, COUNT(DISTINCT a.molecule_id) AS n_molecules FROM atom AS a WHERE a.element IN (SELECT at.element FROM bond AS b JOIN connected AS c ON b.bond_id = c.bond_id JOIN atom AS at ON c.atom_id = at.atom_id WHERE b.bond_type = '#') GROUP BY a.element ORDER BY n_molecules DESC, a.element", "difficulty": "challenging"}
{"question_id": 499, "db_id": "toxicology", "question": "For molecule TR397, I want to see which elements form the bonding skeleton. For each element present among its atoms, how many atoms of that element take part in at least one bond? Please report two things per row: the element symbol (e.g. c, h, o) and the number of that element's atoms in TR397 that take part in a bond. One row per element, ordered alphabetically by element symbol. Only atoms belonging to TR397 should count.", "evidence": "Takes part in a bond: the atom is one of the two atoms a bond joins.", "SQL": "SELECT a.element, COUNT(DISTINCT CASE WHEN NOT c.bond_id IS NULL THEN a.atom_id END) AS bonded_atoms FROM atom AS a LEFT JOIN connected AS c ON (c.atom_id = a.atom_id OR c.atom_id2 = a.atom_id) WHERE a.molecule_id = 'TR397' GROUP BY a.element ORDER BY a.element", "difficulty": "challenging"}
|