bloksbgt commited on
Commit
bd4d1ad
·
verified ·
1 Parent(s): 38ab0ce

Upload SQL-SFT-V1-all-rows

Browse files
.gitattributes CHANGED
@@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ data/pajak-train.json filter=lfs diff=lfs merge=lfs -text
62
+ data/pajak-train_4000.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - id
4
+ license: other
5
+ task_categories:
6
+ - text-generation
7
+ - question-answering
8
+ size_categories:
9
+ - 1K<n<10K
10
+ configs:
11
+ - config_name: pajak_eval
12
+ data_files:
13
+ - split: train
14
+ path: data/pajak-eval.json
15
+ - config_name: pajak_train
16
+ data_files:
17
+ - split: train
18
+ path: data/pajak-train.json
19
+ - config_name: pajak_train_4000
20
+ data_files:
21
+ - split: train
22
+ path: data/pajak-train_4000.json
23
+ - config_name: deepseek_v4_1_flash_1017_pajak_train
24
+ data_files:
25
+ - split: train
26
+ path: data/deepseek-v4-1-flash-1017-pajak-train.json
27
+ - config_name: deepseek_v4_1_flash_pajak_train
28
+ data_files:
29
+ - split: train
30
+ path: data/deepseek-v4.1-flash-pajak-train.json
31
+ - config_name: deepseek_v4_1_flash_free_pajak_train
32
+ data_files:
33
+ - split: train
34
+ path: data/deepseek-v4.1-flash-free-pajak-train.json
35
+ - config_name: gemini_3_5_flash_lite_pajak_train
36
+ data_files:
37
+ - split: train
38
+ path: data/gemini-3.5-flash-lite-pajak-train.json
39
+ - config_name: gpt_6_luna_pajak_train
40
+ data_files:
41
+ - split: train
42
+ path: data/gpt-6-luna-pajak-train.json
43
+ - config_name: mm_MiniMax_M3_1_Flash_pajak_train
44
+ data_files:
45
+ - split: train
46
+ path: data/mm-MiniMax-M3.1-Flash-pajak-train.json
47
+ - config_name: nvidia_nemotron_3_ultra_550b_a55b_pajak_train
48
+ data_files:
49
+ - split: train
50
+ path: data/nvidia-nemotron-3-ultra-550b-a55b-pajak-train.json
51
+ - config_name: nvidia_nemotron_3_ultra_550b_a55b_free_pajak_train
52
+ data_files:
53
+ - split: train
54
+ path: data/nvidia-nemotron-3-ultra-550b-a55b-free-pajak-train.json
55
+ - config_name: z_ai_glm_5_3_flash_pajak_train
56
+ data_files:
57
+ - split: train
58
+ path: data/z-ai-glm-5.3-flash-pajak-train.json
59
+ ---
60
+ # SQL-SFT-V1-all-rows
61
+
62
+ Dataset distilasi pertanyaan dan jawaban SQL.
63
+ Formatnya mengikuti [rasbt/math_distill](https://huggingface.co/datasets/rasbt/math_distill).
64
+
65
+ ## Construction
66
+
67
+ - Soal disediakan sendiri oleh pemilik dataset (file `problems.jsonl`) beserta kunci jawaban singkat (`gtruth_answer`).
68
+ - Jawaban (thinking + jawaban akhir) dihasilkan oleh model teacher lewat router API; verifikasi otomatis terhadap kunci jawaban: VERIFY=False, ONLY_CORRECT=False, REQUIRE_THINKING=False.
69
+
70
+ Akurasi teacher sebelum filter:
71
+
72
+ | Model teacher | Sampel | Benar | Dengan thinking |
73
+ |---|---|---|---|
74
+ | `deepseek-v4-1-flash-1017` | 224 | 224 (100.0%) | 179 |
75
+ | `deepseek-v4.1-flash` | 12 | 12 (100.0%) | 12 |
76
+ | `deepseek-v4.1-flash-free` | 40 | 40 (100.0%) | 40 |
77
+ | `gemini-3.5-flash-lite` | 3 | 3 (100.0%) | 3 |
78
+ | `gpt-6-luna` | 2715 | 2715 (100.0%) | 0 |
79
+ | `mm/MiniMax-M3.1-Flash` | 18 | 18 (100.0%) | 18 |
80
+ | `nvidia/nemotron-3-ultra-550b-a55b` | 2890 | 2890 (100.0%) | 2890 |
81
+ | `nvidia/nemotron-3-ultra-550b-a55b:free` | 64 | 64 (100.0%) | 64 |
82
+ | `z-ai/glm-5.3-flash` | 1591 | 1591 (100.0%) | 0 |
83
+
84
+ ## Files
85
+
86
+ - [data/pajak-eval.json](data/pajak-eval.json):
87
+ * 258 soal evaluasi (held-out, tidak ada di file train) beserta jawaban teacher.
88
+ - [data/pajak-train.json](data/pajak-train.json):
89
+ * 7299 sampel train dari seluruh teacher (tidak tumpang tindih dengan set eval).
90
+ - [data/pajak-train_4000.json](data/pajak-train_4000.json):
91
+ * Seperti pajak-train.json tetapi hanya sampel dengan panjang <= 4000 token (setelah chat template): 7296 sampel.
92
+ - [data/deepseek-v4-1-flash-1017-pajak-train.json](data/deepseek-v4-1-flash-1017-pajak-train.json):
93
+ * Sampel train yang dijawab oleh model `deepseek-v4-1-flash-1017`: 214 sampel.
94
+ - [data/deepseek-v4.1-flash-pajak-train.json](data/deepseek-v4.1-flash-pajak-train.json):
95
+ * Sampel train yang dijawab oleh model `deepseek-v4.1-flash`: 12 sampel.
96
+ - [data/deepseek-v4.1-flash-free-pajak-train.json](data/deepseek-v4.1-flash-free-pajak-train.json):
97
+ * Sampel train yang dijawab oleh model `deepseek-v4.1-flash-free`: 40 sampel.
98
+ - [data/gemini-3.5-flash-lite-pajak-train.json](data/gemini-3.5-flash-lite-pajak-train.json):
99
+ * Sampel train yang dijawab oleh model `gemini-3.5-flash-lite`: 3 sampel.
100
+ - [data/gpt-6-luna-pajak-train.json](data/gpt-6-luna-pajak-train.json):
101
+ * Sampel train yang dijawab oleh model `gpt-6-luna`: 2631 sampel.
102
+ - [data/mm-MiniMax-M3.1-Flash-pajak-train.json](data/mm-MiniMax-M3.1-Flash-pajak-train.json):
103
+ * Sampel train yang dijawab oleh model `mm/MiniMax-M3.1-Flash`: 18 sampel.
104
+ - [data/nvidia-nemotron-3-ultra-550b-a55b-pajak-train.json](data/nvidia-nemotron-3-ultra-550b-a55b-pajak-train.json):
105
+ * Sampel train yang dijawab oleh model `nvidia/nemotron-3-ultra-550b-a55b`: 2788 sampel.
106
+ - [data/nvidia-nemotron-3-ultra-550b-a55b-free-pajak-train.json](data/nvidia-nemotron-3-ultra-550b-a55b-free-pajak-train.json):
107
+ * Sampel train yang dijawab oleh model `nvidia/nemotron-3-ultra-550b-a55b:free`: 61 sampel.
108
+ - [data/z-ai-glm-5.3-flash-pajak-train.json](data/z-ai-glm-5.3-flash-pajak-train.json):
109
+ * Sampel train yang dijawab oleh model `z-ai/glm-5.3-flash`: 1532 sampel.
110
+
111
+ ## Fields
112
+
113
+ Each example contains:
114
+
115
+ - `problem`: soal sql
116
+ - `gtruth_answer`: jawaban singkat (kunci)
117
+ - `message_thinking`: thinking trace dari teacher
118
+ - `message_content`: jawaban akhir dari teacher
119
+
120
+ Keduanya dapat digabung, sama seperti math_distill:
121
+
122
+ ```python
123
+ complete_answer = f"<think>{data['message_thinking']}</think>\n\n{data['message_content']}"
124
+ ```
125
+
126
+ ## Dataset Statistics
127
+
128
+ Dihitung dengan `scripts/average_field_lengths_json.py`, misalnya:
129
+
130
+ ```bash
131
+ python scripts/average_field_lengths_json.py --json_path data/pajak-eval.json --tokenizer Qwen/Qwen3-0.6B
132
+ ```
133
+
134
+ ### `data/pajak-eval.json`
135
+
136
+ ```
137
+ Records: 258
138
+ Tokenizer: Qwen/Qwen3-0.6B
139
+ Field AvgTokens MinTokens MaxToken Count
140
+ gtruth_answer 222.24 173 301 258
141
+ message_content 140.90 26 563 258
142
+ message_thinking 103.42 0 604 258
143
+ problem 138.00 138 138 258
144
+
145
+ Verified-correct answers: 258/258 (100.0%)
146
+ ```
147
+
148
+ ### `data/pajak-train.json`
149
+
150
+ ```
151
+ Records: 7299
152
+ Tokenizer: Qwen/Qwen3-0.6B
153
+ Field AvgTokens MinTokens MaxToken Count
154
+ gtruth_answer 294.72 44 565 7299
155
+ message_content 157.63 4 782 7299
156
+ message_thinking 112.90 0 10402 7299
157
+ problem 138.15 122 158 7299
158
+
159
+ Verified-correct answers: 7299/7299 (100.0%)
160
+ ```
161
+
162
+ ### `data/pajak-train_4000.json`
163
+
164
+ ```
165
+ Records: 7296
166
+ Tokenizer: Qwen/Qwen3-0.6B
167
+ Field AvgTokens MinTokens MaxToken Count
168
+ gtruth_answer 294.65 44 565 7296
169
+ message_content 157.56 4 782 7296
170
+ message_thinking 109.93 0 3254 7296
171
+ problem 138.15 122 158 7296
172
+
173
+ Verified-correct answers: 7296/7296 (100.0%)
174
+ ```
175
+
176
+ ### `data/deepseek-v4-1-flash-1017-pajak-train.json`
177
+
178
+ ```
179
+ Records: 214
180
+ Tokenizer: Qwen/Qwen3-0.6B
181
+ Field AvgTokens MinTokens MaxToken Count
182
+ gtruth_answer 291.47 48 555 214
183
+ message_content 225.34 34 776 214
184
+ message_thinking 308.66 0 2082 214
185
+ problem 137.29 122 158 214
186
+
187
+ Verified-correct answers: 214/214 (100.0%)
188
+ ```
189
+
190
+ ### `data/deepseek-v4.1-flash-pajak-train.json`
191
+
192
+ ```
193
+ Records: 12
194
+ Tokenizer: Qwen/Qwen3-0.6B
195
+ Field AvgTokens MinTokens MaxToken Count
196
+ gtruth_answer 327.83 79 542 12
197
+ message_content 243.67 41 460 12
198
+ message_thinking 325.58 213 425 12
199
+ problem 139.50 122 153 12
200
+
201
+ Verified-correct answers: 12/12 (100.0%)
202
+ ```
203
+
204
+ ### `data/deepseek-v4.1-flash-free-pajak-train.json`
205
+
206
+ ```
207
+ Records: 40
208
+ Tokenizer: Qwen/Qwen3-0.6B
209
+ Field AvgTokens MinTokens MaxToken Count
210
+ gtruth_answer 319.05 75 560 40
211
+ message_content 465.27 214 762 40
212
+ message_thinking 331.85 54 1015 40
213
+ problem 141.10 122 158 40
214
+
215
+ Verified-correct answers: 40/40 (100.0%)
216
+ ```
217
+
218
+ ### `data/gemini-3.5-flash-lite-pajak-train.json`
219
+
220
+ ```
221
+ Records: 3
222
+ Tokenizer: Qwen/Qwen3-0.6B
223
+ Field AvgTokens MinTokens MaxToken Count
224
+ gtruth_answer 321.33 267 404 3
225
+ message_content 106.33 57 132 3
226
+ message_thinking 284.00 228 356 3
227
+ problem 137.67 126 154 3
228
+
229
+ Verified-correct answers: 3/3 (100.0%)
230
+ ```
231
+
232
+ ### `data/gpt-6-luna-pajak-train.json`
233
+
234
+ ```
235
+ Records: 2631
236
+ Tokenizer: Qwen/Qwen3-0.6B
237
+ Field AvgTokens MinTokens MaxToken Count
238
+ gtruth_answer 297.56 44 565 2631
239
+ message_content 120.95 25 434 2631
240
+ message_thinking 0.00 0 0 2631
241
+ problem 138.06 122 158 2631
242
+
243
+ Verified-correct answers: 2631/2631 (100.0%)
244
+ ```
245
+
246
+ ### `data/mm-MiniMax-M3.1-Flash-pajak-train.json`
247
+
248
+ ```
249
+ Records: 18
250
+ Tokenizer: Qwen/Qwen3-0.6B
251
+ Field AvgTokens MinTokens MaxToken Count
252
+ gtruth_answer 300.39 75 498 18
253
+ message_content 176.22 58 334 18
254
+ message_thinking 2336.00 230 10402 18
255
+ problem 134.56 122 158 18
256
+
257
+ Verified-correct answers: 18/18 (100.0%)
258
+ ```
259
+
260
+ ### `data/nvidia-nemotron-3-ultra-550b-a55b-pajak-train.json`
261
+
262
+ ```
263
+ Records: 2788
264
+ Tokenizer: Qwen/Qwen3-0.6B
265
+ Field AvgTokens MinTokens MaxToken Count
266
+ gtruth_answer 293.90 44 562 2788
267
+ message_content 135.11 4 705 2788
268
+ message_thinking 244.11 29 1361 2788
269
+ problem 138.30 122 158 2788
270
+
271
+ Verified-correct answers: 2788/2788 (100.0%)
272
+ ```
273
+
274
+ ### `data/nvidia-nemotron-3-ultra-550b-a55b-free-pajak-train.json`
275
+
276
+ ```
277
+ Records: 61
278
+ Tokenizer: Qwen/Qwen3-0.6B
279
+ Field AvgTokens MinTokens MaxToken Count
280
+ gtruth_answer 305.89 44 563 61
281
+ message_content 137.59 14 414 61
282
+ message_thinking 284.03 43 992 61
283
+ problem 138.56 122 158 61
284
+
285
+ Verified-correct answers: 61/61 (100.0%)
286
+ ```
287
+
288
+ ### `data/z-ai-glm-5.3-flash-pajak-train.json`
289
+
290
+ ```
291
+ Records: 1532
292
+ Tokenizer: Qwen/Qwen3-0.6B
293
+ Field AvgTokens MinTokens MaxToken Count
294
+ gtruth_answer 290.34 44 564 1532
295
+ message_content 244.11 40 782 1532
296
+ message_thinking 0.00 0 0 1532
297
+ problem 138.10 122 158 1532
298
+
299
+ Verified-correct answers: 1532/1532 (100.0%)
300
+ ```
301
+
302
+ ## Intended use
303
+
304
+ Untuk pembelajaran pribadi: melatih/distilasi LLM kecil.
305
+
306
+ ## Usage
307
+
308
+ ```python
309
+ from datasets import load_dataset
310
+
311
+ repo_id = "bloksbgt/SQL-SFT-V1-all-rows"
312
+
313
+ train = load_dataset(repo_id, "pajak_train", split="train")
314
+ eval_set = load_dataset(repo_id, "pajak_eval", split="train")
315
+ train_4000 = load_dataset(repo_id, "pajak_train_4000", split="train")
316
+
317
+ print(len(train), len(eval_set), len(train_4000))
318
+ print(train[0].keys())
319
+ ```
data/deepseek-v4-1-flash-1017-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
data/deepseek-v4.1-flash-free-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
data/deepseek-v4.1-flash-pajak-train.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: Show month-over-month change in {metric}\n\nReturn the SQL query followed by a brief explanation.",
4
+ "gtruth_answer": "```sql\nWITH MonthlyPatientActivity AS (\n -- Calculate the number of appointments for each patient per month\n SELECT\n STRFTIME('%Y-%m', date) AS activity_month,\n p.id AS patient_id,\n COUNT(a.id) AS appointment_count\n FROM appointments a\n JOIN patients p ON a.patient_id = p.id\n GROUP BY 1, 2\n),\nMonthlyMetric AS (\n -- Aggregate the metric (e.g., appointment count) by month\n SELECT\n activity_month,\n COUNT(patient_id) AS total_patients_active\n FROM MonthlyPatientActivity\n GROUP BY activity_month\n)\nSELECT\n activity_month,\n total_patients_active,\n LAG(total_patients_active, 1, 0) OVER (ORDER BY activity_month) AS previous_month_count,\n total_patients_active - LAG(total_patients_active, 1, 0) OVER (ORDER BY activity_month) AS month_over_month_change\nFROM MonthlyMetric\nORDER BY activity_month;\n```\n\n**Explanation:**\n\nSince the request asks to \"Show month-over-month change in {metric}\" but does not specify *which* metric, I have chosen to calculate the month-over-month change in the **count of distinct patients who had appointments** (as a representative activity metric).\n\n1. **`MonthlyPatientActivity` CTE:**\n * This CTE first joins `appointments` and `patients`.\n * It extracts the year and month (`STRFTIME('%Y-%m', date)`) from the appointment date.\n * It counts the number of appointments for each patient within each specific month.\n\n2. **`MonthlyMetric` CTE:**\n * This CTE aggregates the data from the first CTE to calculate the total number of *unique patients* who had activity in that month. (Note: I used `COUNT(patient_id)` grouped by month, which counts the number of patient-month combinations. If the intent was unique patients *active* in that month, `COUNT(DISTINCT patient_id)` would be used here).\n\n3. **Final SELECT Statement:**\n * This is the core of the month-over-month calculation.\n * It uses the **Window Function `LAG()`**: `LAG(total_patients_active, 1, 0) OVER (ORDER BY activity_month)` retrieves the `total_patients_active` value from the previous row, ordered by `activity_month`. The default value is `0` if no previous row exists.\n * It calculates the `month_over_month_change` by subtracting the previous month's",
5
+ "message_thinking": "**Considering month-over-month change**\n\nOkay, the user wants to see the month-over-month change in a metric. I think I should create a general SQL template that computes the metric per month, then calculates the change from one month to the next. I'll need to group by month, calculate the metric for each month, and then use a window function or a subquery to compute the difference between months. I'll make sure to explain the query afterward.**Deciding on language and approach**\n\nOkay, the user asked for the answer in Indonesian, so I’ll stick to that. They want a SQL query for month-over-month change in a metric, but the metric is a placeholder. I think I should provide a general SQL template that calculates a monthly metric and then computes the change. I’ll use `LAG()` to get the previous month’s value and calculate the difference and percentage change. I’ll make sure to explain it clearly, but I also want to keep it flexible enough for different metrics.**Clarifying the SQL query**\n\nThe user wants a SQL query to show month-over-month change in a metric. I’ll provide a general template using `date_trunc('month', date)` for PostgreSQL, which is common. I’ll use `LAG()` to calculate the previous month’s value and compute the difference and percentage change. I’ll explain that this query works for any metric, like counting appointments per month, and can be adapted by changing the source table and metric expression. I’ll write the explanation in Indonesian, as requested.",
6
+ "message_content": "## Contoh untuk {metric} = jumlah appointment per bulan (tabel `appointments`, kolom `date`)\n```sql\nWITH monthly_metric AS (\n SELECT\n date_trunc('month', date) AS month,\n COUNT(*) AS metric_value\n FROM appointments\n GROUP BY date_trunc('month', date)\n)\nSELECT\n month,\n metric_value,\n metric_value - LAG(metric_value) OVER (ORDER BY month) AS mom_change,\n CASE\n WHEN LAG(metric_value) OVER (ORDER BY month) IS NULL\n OR LAG(metric_value) OVER (ORDER BY month) = 0\n THEN NULL\n ELSE ROUND(\n (metric_value - LAG(metric_value) OVER (ORDER BY month)) * 100.0\n / LAG(metric_value) OVER (ORDER BY month),\n 2\n )\n END AS mom_change_pct\nFROM monthly_metric\nORDER BY month;\n```\n\n## Penjelasan singkat\n- `monthly_metric` mengagregasi `{metric}` per bulan dengan mengelompokkan berdasarkan awal bulan (`date_trunc('month', date)`), menghasilkan `metric_value` per `month`.\n- `LAG(metric_value) OVER (ORDER BY month)` mengambil nilai `metric_value` pada bulan sebelumnya.\n- `mom_change = metric_value - nilai_bulan_sebelumnya` (perubahan MoM absolut).\n- `mom_change_pct` menghitung perubahan persentase MoM; jika tidak ada bulan sebelumnya atau nilai bulan sebelumnya `0`, hasil di-set `NULL` untuk menghindari error/pembagian nol.\n- Urutan `ORDER BY month` memastikan perhitungan MoM berurutan dari bulan ke bulan.\n\nUntuk `{metric}` lain, ubah bagian agregasi di CTE (tabel sumber, kolom waktu, dan ekspresi metrik), misalnya jumlah diagnosis per bulan dari `diagnoses.date` dengan `COUNT(*)`, atau total resep per bulan jika ada kolom tanggal pada `prescriptions`."
7
+ },
8
+ {
9
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: Show month-over-month change in {metric}\n\nReturn the SQL query followed by a brief explanation.",
10
+ "gtruth_answer": "```sql\nWITH MonthlyPatientActivity AS (\n -- Calculate the number of appointments per month for each patient\n SELECT\n STRFTIME('%Y-%m', date) AS activity_month,\n p.id AS patient_id,\n COUNT(a.id) AS appointment_count\n FROM appointments a\n JOIN patients p ON a.patient_id = p.id\n GROUP BY 1, 2\n),\nMonthlyMetrics AS (\n -- Aggregate the total metric (e.g., appointment count) per month\n SELECT\n activity_month,\n SUM(appointment_count) AS total_metric\n FROM MonthlyPatientActivity\n GROUP BY 1\n)\nSELECT\n activity_month,\n total_metric,\n LAG(total_metric, 1, 0) OVER (ORDER BY activity_month) AS previous_month_metric,\n total_metric - LAG(total_metric, 1, 0) OVER (ORDER BY activity_month) AS month_over_month_change\nFROM MonthlyMetrics\nORDER BY activity_month;\n```\n\n**Explanation:**\n\n1. **`MonthlyPatientActivity` CTE:**\n * This CTE first calculates the activity (in this case, the count of appointments) for each patient for every month they had an appointment.\n * It extracts the year and month (`YYYY-MM`) from the `date` column in the `appointments` table using `STRFTIME` (common in SQLite; syntax might vary slightly for other SQL dialects like `DATE_FORMAT` in MySQL or `TO_CHAR` in PostgreSQL).\n * It groups by the calculated month and `patient_id` to get individual patient activity per month.\n\n2. **`MonthlyMetrics` CTE:**\n * This CTE aggregates the data from `MonthlyPatientActivity` to calculate the *total* metric (total appointments) for each month across all patients.\n\n3. **Final SELECT Statement:**\n * This is where the month-over-month (MoM) change is calculated using a **Window Function**, specifically `LAG()`.\n * `LAG(total_metric, 1, 0) OVER (ORDER BY activity_month)` retrieves the `total_metric` value from the previous row, ordered by `activity_month`. The default value of `0` is used if no previous row exists (for the first month).\n * `month_over_month_change` is calculated by subtracting the previous month's total from the current month's total.\n\nThis approach is efficient because it aggregates the data first and then uses a single pass with the `LAG` window function to perform the required comparison.",
11
+ "message_thinking": "**Considering SQL query structure**\n\nOkay, the user wants a SQL query to show month-over-month change in a metric. The tricky part is that the metric isn't specified, so I need to decide whether to show a general pattern or pick a reasonable example. I think it might be best to show the pattern first, and then maybe add an example metric like the number of appointments or prescriptions. I’ll need to make sure the query calculates the difference between months correctly. Let’s proceed carefully!**Clarifying SQL query approach**\n\nOkay, the user wants a SQL query for month-over-month change in a metric, but the metric is a placeholder. I could either show a general template or pick a specific metric like appointments per month. I think it’s best to explain that {metric} is a placeholder and then provide a general SQL pattern using the LAG function. To make it clearer, I’ll also include a concrete example using appointments. This way, the user gets both the general approach and a practical example. Let’s go with that!**Clarifying SQL query structure**\n\nThe user wants a SQL query for month-over-month change in a metric, but the metric is a placeholder. I’ll provide a general template for this, explaining that {metric} can be any value. I’ll use a concrete example of monthly appointment counts to make it clearer. The query will use the `LAG()` function to calculate the difference and percentage change. I’ll also mention that the query is written in a common SQL style, but the syntax might vary depending on the database system. Let’s go with that!**Finalizing SQL query structure**\n\nI’m thinking of using this form for the SQL query, where we group by the truncated month and select it as `period_date`. I’ll explain the placeholders clearly, so the user understands how to adapt it for different metrics. The subquery will aggregate the metric by month, and then we’ll calculate the month-over-month change using `LAG()`. I’ll make sure to clarify the placeholders and the logic behind the query. This should work well for the user’s request!",
12
+ "message_content": "```sql\nSELECT\n month,\n metric_value,\n metric_value - LAG(metric_value) OVER (ORDER BY month) AS mom_change,\n ROUND(\n 100.0 * (metric_value - LAG(metric_value) OVER (ORDER BY month))\n / NULLIF(LAG(metric_value) OVER (ORDER BY month), 0),\n 2\n ) AS mom_pct_change\nFROM (\n SELECT\n DATE_TRUNC('month', <kolom_tanggal>) AS month,\n <agregasi_metnik> AS metric_value\n FROM <tabel_sumber>\n GROUP BY DATE_TRUNC('month', <kolom_tanggal>)\n) t\nORDER BY month;\n```\n\nPenjelasan singkat:\n- Subquery mengagregasi `{metric}` per bulan dengan mengelompokkan `DATE_TRUNC('month', <kolom_tanggal>)` menjadi `month` dan menghitung `<agregasi_metnik>` sebagai `metric_value`.\n- `LAG(metric_value) OVER (ORDER BY month)` mengambil nilai metrik bulan sebelumnya.\n- `mom_change = metric_value - nilai bulan sebelumnya`.\n- `mom_pct_change` menghitung perubahan persentase MoM; `NULLIF(...,0)` mencegah pembagian oleh nol (hasil `NULL` jika bulan sebelumnya 0 atau tidak ada).\n- Ganti `<kolom_tanggal>`, `<agregasi_metnik>`, dan `<tabel_sumber>` sesuai metrik yang dimaksud (contoh: appointments per bulan dari tabel `appointments` dengan `<kolom_tanggal> = date`, `<agregasi_metnik> = COUNT(*)`)."
13
+ },
14
+ {
15
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: Find {entity} that have never {action}\n\nReturn the SQL query followed by a brief explanation.",
16
+ "gtruth_answer": "```sql\n-- Find patients that have never had a diagnosis\nSELECT p.*\nFROM patients p\nLEFT JOIN diagnoses d ON p.id = d.patient_id\nWHERE d.patient_id IS NULL;\n```\n\n**Explanation:**\n\n1. **`SELECT p.* FROM patients p`**: This selects all columns from the `patients` table, aliased as `p`.\n2. **`LEFT JOIN diagnoses d ON p.id = d.patient_id`**: This performs a `LEFT JOIN` from the `patients` table to the `diagnoses` table on the matching patient IDs. A `LEFT JOIN` ensures that *all* records from the left table (`patients`) are included, even if there are no matching records in the right table (`diagnoses`).\n3. **`WHERE d.patient_id IS NULL`**: This is the crucial filtering step. If a patient has never had a diagnosis, the columns from the `diagnoses` table (including `d.patient_id`) will be `NULL` for that patient's row in the result set. Filtering for `d.patient_id IS NULL` isolates exactly those patients who have no corresponding entries in the `diagnoses` table.",
17
+ "message_thinking": "**Clarifying the task**\n\nOkay, the user is asking for a SQL query to find an entity that has never performed a certain action. The placeholders {entity} and {action} seem like they’re meant to be filled in with specific values, but I’m not sure what those are yet. It could be a template for a general query, or maybe they want an example of how to structure it. I’ll need to figure out how to approach this with the given database schema. Let’s think through it!**Clarifying the query**\n\nOkay, the user wants a SQL query to find an entity that has never performed a certain action. The placeholders {entity} and {action} seem to be a template. I think the best approach is to use a general pattern like NOT EXISTS or LEFT JOIN...IS NULL. I’ll need to apply this to the schema provided. A good example could be finding patients who have never had an appointment. I’ll show the query for that and explain the pattern. This should help the user understand how to adapt it for other cases.**Finalizing the query**\n\nAlright, I think I’ve got it. I’ll go with the example of finding patients who have never had an appointment. This fits the schema well and is a clear example. I’ll use the NOT EXISTS pattern for the query, and briefly mention the LEFT JOIN alternative. The query will return patients who don’t have any matching rows in the appointments table. I’ll keep it simple and precise, focusing on this example for clarity. I could also do a similar query for doctors, but I’ll stick with patients for now. Let’s go with this!",
18
+ "message_content": "## Contoh (paling umum dari skema): pasien yang tidak pernah memiliki janji temu\n\n```sql\nSELECT p.id, p.name\nFROM patients p\nWHERE NOT EXISTS (\n SELECT 1\n FROM appointments a\n WHERE a.patient_id = p.id\n);\n```\n\n**Penjelasan singkat:** Ambil data dari `patients` (`p`), lalu saring dengan `NOT EXISTS` yang mengecek apakah ada baris di `appointments` (`a`) dengan `a.patient_id = p.id`. Jika tidak ada satupun, pasien termasuk hasil (tidak pernah membuat/memiliki janji temu). Pola umum: “entity yang tidak pernah action” → `WHERE NOT EXISTS (SELECT 1 FROM tabel_aksi t WHERE t.fk_entity = entity.id)`. Alternatif lain: `LEFT JOIN tabel_aksi t ON ... WHERE t.<pk> IS NULL`."
19
+ },
20
+ {
21
+ "problem": "Database schema:\n```sql\nCREATE TABLE users (id INT PRIMARY KEY, name VARCHAR, email VARCHAR, created_at TIMESTAMP, country VARCHAR);\nCREATE TABLE products (id INT PRIMARY KEY, name VARCHAR, category VARCHAR, price DECIMAL, stock INT);\nCREATE TABLE orders (id INT PRIMARY KEY, user_id INT, created_at TIMESTAMP, total DECIMAL, status VARCHAR);\nCREATE TABLE order_items (order_id INT, product_id INT, quantity INT, unit_price DECIMAL);\n```\n\nWrite a SQL query to: Find all {entity} where {condition}\n\nReturn the SQL query followed by a brief explanation.",
22
+ "gtruth_answer": "Please provide the specific entity and condition you are interested in.\n\nFor example, you could ask:\n* \"Find all users who live in 'USA'.\"\n* \"Find all products with a price greater than 50.00.\"\n* \"Find all orders that have a status of 'Shipped'.\"\n\nOnce you provide the natural language question, I will write the appropriate SQL query.",
23
+ "message_thinking": "**Clarifying the task**\n\nOkay, the user wants a SQL query template that follows the structure \"Find all {entity} where {condition}\". They’ve provided a database schema, so I think they want me to generate an example query based on that. I should probably pick an entity from the schema, like \"users\" or \"orders,\" and apply a condition, like finding users from a specific country. \n\nLet me think through this carefully and make sure I’m on the right track.**Clarifying the query example**\n\nOkay, the user wants a SQL query in the form \"Find all {entity} where {condition}\". They didn’t fill in the placeholders, so I think they want me to generate a concrete example based on the schema. \n\nI’ll go with something simple like finding all users from a specific country, say 'US'. This fits the schema and makes sense as a clear example. I’ll also include a brief explanation of the query to make it clear.**Choosing a clear example**\n\nOkay, I think it’s better to just go with one clear example to make things easier. I’ll pick something straightforward, like finding all users from a specific country. This will help the user understand the structure of the query without overcomplicating things. I’ll stick with that and provide a simple explanation to go along with it. This should be helpful and clear!",
24
+ "message_content": "```sql\nSELECT *\nFROM users\nWHERE country = 'US';\n```\n\nMengambil semua kolom dari tabel `users` untuk baris dengan `country` bernilai `'US'`."
25
+ },
26
+ {
27
+ "problem": "Database schema:\n```sql\nCREATE TABLE accounts (id INT PRIMARY KEY, name VARCHAR, plan VARCHAR, mrr DECIMAL, created_at TIMESTAMP);\nCREATE TABLE users (id INT PRIMARY KEY, account_id INT, email VARCHAR, role VARCHAR, last_login TIMESTAMP);\nCREATE TABLE events (id INT PRIMARY KEY, user_id INT, event_type VARCHAR, created_at TIMESTAMP, properties JSONB);\nCREATE TABLE subscriptions (id INT PRIMARY KEY, account_id INT, plan VARCHAR, start_date DATE, end_date DATE, arr DECIMAL);\n```\n\nWrite a SQL query to: Show month-over-month change in {metric}\n\nReturn the SQL query followed by a brief explanation.",
28
+ "gtruth_answer": "```sql\nWITH monthly_metrics AS (\n SELECT\n DATE_TRUNC('month', e.created_at) AS month_start,\n SUM(CASE WHEN a.plan = 'Premium' THEN a.mrr ELSE 0 END) AS premium_mrr\n FROM events e\n JOIN users u ON e.user_id = u.id\n JOIN accounts a ON u.account_id = a.id\n GROUP BY 1\n)\nSELECT\n month_start,\n premium_mrr,\n LAG(premium_mrr, 1, 0) OVER (ORDER BY month_start) AS previous_month_mrr,\n premium_mrr - LAG(premium_mrr, 1, 0) OVER (ORDER BY month_start) AS month_over_month_change\nFROM monthly_metrics\nORDER BY month_start;\n```\n\n**Explanation:**\n\n1. **`monthly_metrics` CTE:**\n * This Common Table Expression (CTE) is used to aggregate the relevant metric (in this case, the MRR for 'Premium' accounts) on a monthly basis.\n * It joins `events`, `users`, and `accounts` to link event activity to account plan information.\n * `DATE_TRUNC('month', e.created_at)` truncates the event timestamp to the first day of the month, allowing for proper monthly grouping.\n * It calculates the sum of `mrr` only for accounts where the `plan` is 'Premium'. (Note: In a real-world scenario, MRR aggregation might be more complex, perhaps involving the `subscriptions` table, but based strictly on the provided schema and the request structure, this approach aggregates based on event data linked to account plans).\n\n2. **Final SELECT Statement:**\n * It selects the calculated `month_start` and the `premium_mrr`.\n * It uses the **`LAG()` window function** to retrieve the `premium_mrr` from the previous row (previous month), ordered by `month_start`. The default value of `0` is used for the very first month if no previous record exists.\n * It calculates the **month-over-month change** by subtracting the previous month's MRR from the current month's MRR.\n\nThis query efficiently calculates the required time-series comparison using standard SQL window functions.",
29
+ "message_thinking": "**Considering SQL query for MoM change**\n\nOkay, the user wants a SQL query to show the month-over-month change in a metric, but they haven’t specified which metric. I’m thinking it could be something like total MRR, but I need to keep it general. I’ll write a query that calculates the MoM change for a metric, using a template approach. I’ll also make sure to explain the query afterward, so the user understands how it works. Let’s get started on that!**Thinking through the SQL query template**\n\nOkay, the user wants a SQL query to show month-over-month change in a metric, but they’ve left the metric as a placeholder. I’m thinking it could be something like MRR, ARR, or event counts, but I need to keep it general. I’ll write a template query that calculates the MoM change for any metric, using a common approach with CTEs. I’ll also need to clarify that the user should replace the placeholders with their specific metric and date column. Let’s make sure it’s clear and flexible!**Planning the SQL query template**\n\nOkay, the user wants a SQL query to show month-over-month change in a metric, but they haven’t specified which metric. I’ll write a clear template that can be adapted for any metric. The query will calculate the MoM change using a common pattern with CTEs. I’ll use placeholders like `<metric_expr>` and `<date_col>` so the user can replace them with their specific metric and date column. I’ll also make sure to explain the query briefly afterward. Let’s finalize this!",
30
+ "message_content": "```sql\nWITH monthly AS (\n SELECT\n date_trunc('month', <date_column>) AS month,\n <metric_expression> AS metric\n FROM <source_table>\n GROUP BY 1\n),\nmom AS (\n SELECT\n month,\n metric,\n LAG(metric) OVER (ORDER BY month) AS prev_metric\n FROM monthly\n)\nSELECT\n month,\n metric,\n (metric - prev_metric) AS mom_change,\n CASE\n WHEN prev_metric IS NULL OR prev_metric = 0 THEN NULL\n ELSE ROUND((metric - prev_metric) * 100.0 / prev_metric, 2)\n END AS mom_change_pct\nFROM mom\nORDER BY month;\n```\n\n**Penjelasan singkat**\n- `monthly`: agregasi `{metric}` per bulan dari `<source_table>` menggunakan `<date_column>` dan `<metric_expression>` (ganti sesuai kebutuhan, mis. `SUM(mrr)`, `COUNT(*)`, dll.).\n- `mom`: pakai `LAG(metric)` untuk mengambil nilai bulan sebelumnya.\n- Output menampilkan `month`, nilai `metric`, perubahan absolut (`mom_change`), dan perubahan persen (`mom_change_pct`); bulan pertama (tanpa data sebelumnya) akan `NULL` pada kolom perubahan."
31
+ },
32
+ {
33
+ "problem": "Database schema:\n```sql\nCREATE TABLE accounts (id INT PRIMARY KEY, name VARCHAR, plan VARCHAR, mrr DECIMAL, created_at TIMESTAMP);\nCREATE TABLE users (id INT PRIMARY KEY, account_id INT, email VARCHAR, role VARCHAR, last_login TIMESTAMP);\nCREATE TABLE events (id INT PRIMARY KEY, user_id INT, event_type VARCHAR, created_at TIMESTAMP, properties JSONB);\nCREATE TABLE subscriptions (id INT PRIMARY KEY, account_id INT, plan VARCHAR, start_date DATE, end_date DATE, arr DECIMAL);\n```\n\nWrite a SQL query to: Find duplicate {entity} by {field}\n\nReturn the SQL query followed by a brief explanation.",
34
+ "gtruth_answer": "```sql\nSELECT\n t1.name,\n COUNT(t1.id) AS duplicate_count\nFROM\n accounts t1\nGROUP BY\n t1.name\nHAVING\n COUNT(t1.id) > 1;\n```\n\n**Explanation:**\n\nThis query is designed to find duplicate entries in the `accounts` table based on the `name` field.\n\n1. **`SELECT t1.name, COUNT(t1.id) AS duplicate_count`**: Selects the account name and counts how many records share that name.\n2. **`FROM accounts t1`**: Specifies the table we are querying.\n3. **`GROUP BY t1.name`**: Groups the rows based on the `name` column, so the `COUNT` function can aggregate them for each unique name.\n4. **`HAVING COUNT(t1.id) > 1`**: Filters the grouped results to only include those groups (names) where the count of accounts is greater than 1, indicating a duplicate name.",
35
+ "message_thinking": "**Formulating SQL query pattern**\n\nOkay, the user wants a general SQL query pattern to find duplicates by a field for a given entity. I’ll need to provide a template that can be applied to any table and field. The query will likely involve using `GROUP BY` and `HAVING COUNT(*) > 1` to identify duplicates. I’ll also need to explain that this pattern can be adapted to different tables and fields. Let me think through the structure and make sure it’s clear and flexible for the user.**Clarifying SQL query approach**\n\nOkay, the user wants a SQL query to find duplicates by a field. I think it’s best to give a general query pattern with placeholders for the table and field. I’ll also explain that this query finds duplicate values in a specific field, showing how many times each value appears. If they want the actual duplicate rows, I’ll provide a different query. I’ll keep it simple and clear, and maybe add a concrete example like finding duplicate users by email. Let me finalize the explanation and query.",
36
+ "message_content": "```sql\nSELECT\n {field},\n COUNT(*) AS duplicate_count\nFROM {entity}\nGROUP BY {field}\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC, {field};\n```\n\nPenjelasan singkat: query mengelompokkan baris di `{entity}` berdasarkan `{field}`, menghitung kemunculan tiap nilai, lalu hanya menampilkan nilai `{field}` yang muncul lebih dari satu kali (duplikat) beserta jumlahnya; urutkan dari duplikat terbanyak."
37
+ },
38
+ {
39
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: Get the {ranking} {entity} for each {dimension}\n\nReturn the SQL query followed by a brief explanation.",
40
+ "gtruth_answer": "```sql\nSELECT\n d.name AS doctor_name,\n COUNT(a.id) AS appointment_count\nFROM\n doctors d\nJOIN\n appointments a ON d.id = a.doctor_id\nGROUP BY\n d.id, d.name\nORDER BY\n appointment_count DESC;\n```\n\n**Explanation:**\n\nThe request asks to \"Get the {ranking} {entity} for each {dimension}\". Interpreting this as finding the top doctors (ranking) based on the number of appointments they have held (entity) for each doctor (dimension), the query performs the following steps:\n\n1. **JOIN:** It joins the `doctors` table with the `appointments` table on `doctor_id` to link doctors to their appointments.\n2. **GROUP BY:** It groups the results by doctor (`d.id` and `d.name`) to aggregate the data per doctor.\n3. **COUNT:** It uses `COUNT(a.id)` to count the number of appointments associated with each doctor group.\n4. **ORDER BY:** It sorts the results in descending order based on the calculated `appointment_count` to achieve the ranking (highest count first).\n5. **SELECT:** It selects the doctor's name and their corresponding appointment count.",
41
+ "message_thinking": "**Clarifying the query request**\n\nOkay, the user wants a SQL query to \"Get the {ranking} {entity} for each {dimension}\". This sounds like a template, maybe asking for a \"top N per group\" type of query. But I’m not sure if they want me to infer the specific entities and dimensions or if they’re just asking for a generic pattern. I should probably clarify whether they want a specific example or just a general query template. Let me think about how to approach this.**Clarifying the query request**\n\nOkay, the user wants a SQL query to \"Get the {ranking} {entity} for each {dimension}\". The placeholders are a bit confusing, though. Maybe they want a general template for a \"top-N per group\" query? I could use something like ROW_NUMBER() to rank entities by a dimension, but I’m not sure if they want a specific example or just a pattern. I think I should infer a reasonable example from the schema, like getting the top doctor per specialty by appointment count. Let me think about how to approach this.**Making an assumption for clarity**\n\nOkay, I think I’ll assume a concrete example to make this clearer. Let’s say the user wants the top 1 doctor for each specialty, ranked by the number of appointments. The schema gives me the doctors' specialties, and I can rank them by appointment count. I’ll use ROW_NUMBER() to rank the doctors within each specialty and select the top one. This seems like a reasonable interpretation of the user’s request. I’ll write the query and explain it briefly.",
42
+ "message_content": "```sql\nWITH doctor_appt_counts AS (\n SELECT\n d.id AS doctor_id,\n d.name AS doctor_name,\n d.specialty,\n COUNT(a.id) AS appt_count\n FROM doctors d\n LEFT JOIN appointments a ON a.doctor_id = d.id\n GROUP BY d.id, d.name, d.specialty\n),\nranked AS (\n SELECT\n specialty,\n doctor_id,\n doctor_name,\n appt_count,\n ROW_NUMBER() OVER (PARTITION BY specialty ORDER BY appt_count DESC, doctor_id) AS rn\n FROM doctor_appt_counts\n)\nSELECT specialty, doctor_id, doctor_name, appt_count\nFROM ranked\nWHERE rn = 1\nORDER BY specialty;\n```\n\n**Penjelasan (asumsi contoh):** Query ini mengambil **1 dokter teratas (ranking)** per **spesialisasi (dimension)** berdasarkan **jumlah janji temu terbanyak (metrik peringkat)**. `doctor_appt_counts` menghitung `appt_count` per dokter (termasuk dokter tanpa janji temu karena `LEFT JOIN`). CTE `ranked` memberi peringkat dalam tiap `specialty` dengan `ROW_NUMBER() OVER (PARTITION BY specialty ORDER BY appt_count DESC, doctor_id)`. Filter `rn = 1` mengembalikan entitas teratas untuk setiap dimension; `ORDER BY specialty` untuk hasil rapi."
43
+ },
44
+ {
45
+ "problem": "Database schema:\n```sql\nCREATE TABLE users (id INT PRIMARY KEY, name VARCHAR, email VARCHAR, created_at TIMESTAMP, country VARCHAR);\nCREATE TABLE products (id INT PRIMARY KEY, name VARCHAR, category VARCHAR, price DECIMAL, stock INT);\nCREATE TABLE orders (id INT PRIMARY KEY, user_id INT, created_at TIMESTAMP, total DECIMAL, status VARCHAR);\nCREATE TABLE order_items (order_id INT, product_id INT, quantity INT, unit_price DECIMAL);\n```\n\nWrite a SQL query to: Show month-over-month change in {metric}\n\nReturn the SQL query followed by a brief explanation.",
46
+ "gtruth_answer": "```sql\nWITH MonthlySales AS (\n SELECT\n STRFTIME('%Y-%m', o.created_at) AS sales_month,\n SUM(oi.quantity * oi.unit_price) AS monthly_sales\n FROM orders o\n JOIN order_items oi ON o.id = oi.order_id\n GROUP BY 1\n)\nSELECT\n sales_month,\n monthly_sales,\n LAG(monthly_sales, 1, 0) OVER (ORDER BY sales_month) AS previous_month_sales,\n monthly_sales - LAG(monthly_sales, 1, 0) OVER (ORDER BY sales_month) AS month_over_month_change\nFROM MonthlySales\nORDER BY sales_month;\n```\n\n**Explanation:**\n\n1. **`MonthlySales` CTE (Common Table Expression):**\n * This CTE calculates the total sales for each month.\n * It joins the `orders` table with the `order_items` table to access the quantity and unit price for each item in an order.\n * `STRFTIME('%Y-%m', o.created_at)` extracts the year and month from the order creation timestamp, which is used to group the sales data monthly.\n * `SUM(oi.quantity * oi.unit_price)` calculates the total revenue for that specific order item line.\n * The results are grouped by the extracted month (`sales_month`).\n\n2. **Final SELECT Statement:**\n * This query uses a window function, `LAG()`, to retrieve the sales amount from the previous row (previous month) based on the chronological order of `sales_month`.\n * `LAG(monthly_sales, 1, 0) OVER (ORDER BY sales_month)` fetches the `monthly_sales` value from the row preceding the current row, ordered by `sales_month`. The default value of `0` is used if no previous row exists (for the first month).\n * `monthly_sales - LAG(...)` calculates the month-over-month change by subtracting the previous month's sales from the current month's sales.\n * The results are ordered by `sales_month` for a clear time series view.\n\n*Note: The date function `STRFTIME` is used here, which is common in SQLite. If you are using PostgreSQL, you would use `TO_CHAR(o.created_at, 'YYYY-MM')`, and for SQL Server, you would use `FORMAT(o.created_at, 'yyyy-MM')` or `DATEPART(year, o.created_at) * 100 + DATEPART(month, o.created_at)`.*",
47
+ "message_thinking": "**Breaking down the query**\n\nOkay, I need to figure out how to calculate the month-over-month change for a specific metric. First, I’ll need to decide which metric to focus on — maybe total sales or order count? I’ll likely need to group by month and year, then calculate the difference between the current month and the previous month. I’ll use `DATE_TRUNC` to group by month, and then `LAG` to get the previous month’s value. Let’s see how I can structure this query!**Clarifying the query**\n\nOkay, the user wants a SQL query to show month-over-month change in a metric, but they didn’t specify which metric. I could either write a general template or pick a common metric like total revenue or order count. I think it’s safer to go with a concrete example, like total revenue, since it’s easy to calculate from the orders table. I’ll use a CTE to group by month, then calculate the month-over-month change using `LAG`. I’ll also explain that the user can replace the metric as needed.**Clarifying the query**\n\nThe user wants a SQL query to show month-over-month change in a metric, but they didn’t specify which one. I’ll go with total revenue from orders as a concrete example. I’ll use `DATE_TRUNC` to group by month and `LAG` to get the previous month’s value. Then, I’ll calculate the change and percent change. I’ll explain that the user can replace the metric with something else, like order count or items sold, depending on their needs. This should be a flexible, clear example.",
48
+ "message_content": "```sql\nWITH monthly AS (\n SELECT\n DATE_TRUNC('month', created_at) AS month,\n SUM(total) AS metric_value\n FROM orders\n GROUP BY DATE_TRUNC('month', created_at)\n)\nSELECT\n month,\n metric_value,\n metric_value - LAG(metric_value) OVER (ORDER BY month) AS mom_change,\n ROUND(\n CASE\n WHEN LAG(metric_value) OVER (ORDER BY month) IS NULL OR LAG(metric_value) OVER (ORDER BY month) = 0 THEN NULL\n ELSE (metric_value - LAG(metric_value) OVER (ORDER BY month)) * 100.0 / LAG(metric_value) OVER (ORDER BY month)\n END,\n 2\n ) AS mom_change_pct\nFROM monthly\nORDER BY month;\n```\n\n**Penjelasan (singkat):** Query mengagregasi metrik per bulan dari `orders.created_at` (contoh: `SUM(total)` sebagai `metric_value`). `LAG(metric_value) OVER (ORDER BY month)` mengambil nilai bulan sebelumnya, lalu dihitung selisih MoM (`mom_change`) dan persentase MoM (`mom_change_pct`); bulan pertama bernilai `NULL`. Ganti bagian agregasi di CTE `monthly` sesuai `{metric}` yang diinginkan (mis. `COUNT(*)` untuk jumlah pesanan, atau agregasi dari `order_items` setelah `JOIN` untuk metrik lain)."
49
+ },
50
+ {
51
+ "problem": "Database schema:\n```sql\nCREATE TABLE accounts (id INT PRIMARY KEY, name VARCHAR, plan VARCHAR, mrr DECIMAL, created_at TIMESTAMP);\nCREATE TABLE users (id INT PRIMARY KEY, account_id INT, email VARCHAR, role VARCHAR, last_login TIMESTAMP);\nCREATE TABLE events (id INT PRIMARY KEY, user_id INT, event_type VARCHAR, created_at TIMESTAMP, properties JSONB);\nCREATE TABLE subscriptions (id INT PRIMARY KEY, account_id INT, plan VARCHAR, start_date DATE, end_date DATE, arr DECIMAL);\n```\n\nWrite a SQL query to: List all {entity} that {condition} but not {other_condition}\n\nReturn the SQL query followed by a brief explanation.",
52
+ "gtruth_answer": "```sql\nSELECT\n a.*\nFROM accounts AS a\nWHERE\n a.mrr > 100000 -- Replace with your specific condition for 'entity'\n AND a.plan != 'Basic'; -- Replace with your specific condition for 'condition'\n -- AND a.plan != 'Premium'; -- Replace with your specific condition for 'other_condition'\n```\n\n**Explanation:**\n\nSince the natural language prompt provided a template (\"List all {entity} that {condition} but not {other_condition}\"), and did not specify which tables or columns to use, I have made an assumption to demonstrate the structure of the requested query using the `accounts` table as the entity.\n\n1. **`SELECT a.* FROM accounts AS a`**: This selects all columns from the `accounts` table.\n2. **`WHERE a.mrr > 100000`**: This represents the `{condition}` (e.g., where MRR is greater than 100,000).\n3. **`AND a.plan != 'Basic'`**: This represents the `{other_condition}` (e.g., but not having the 'Basic' plan).\n\nTo use this query for a specific business question, you would replace the placeholder conditions (`a.mrr > 100000` and `a.plan != 'Basic'`) with the actual criteria derived from your request.",
53
+ "message_thinking": "**Clarifying the task**\n\nOkay, the user seems to want a SQL query in a specific format: \"List all {entity} that {condition} but not {other_condition}.\" But, hmm, I’m not sure if they want me to fill in the blanks with specific details from the schema or if they’re asking for a general pattern. I should probably clarify whether they want me to infer the entity, condition, and other condition from the schema or if they have specific examples in mind. Let me think about how to approach this.**Choosing an example query**\n\nOkay, the user’s request is a bit ambiguous, but I think they want me to write a SQL query using the schema provided. The format seems to be asking for a query that lists entities satisfying one condition but not another. I should probably pick a concrete example from the schema to make it clearer.\n\nI’m thinking of using the \"accounts\" table as the entity. Maybe I could write a query to list accounts that have at least one subscription with an ARR greater than 10,000 but not any subscription with the plan \"enterprise.\" That seems like a reasonable example. Let me refine that.**Choosing a clear example**\n\nOkay, I’m thinking of a good example for the query. I could go with something like: \"List all users who logged in after a certain date but don’t have any event of type 'deleted'.\" Or maybe \"List all accounts with MRR > 0 but no users with the role 'admin'.\" But I think I’ll go with a more straightforward example: \"List all accounts that have at least one user with the role 'admin' but no subscription with the plan 'enterprise.'\" That seems like a reasonable business question. Let me write that query.",
54
+ "message_content": "```sql\nSELECT a.*\nFROM accounts a\nWHERE EXISTS (\n SELECT 1\n FROM users u\n WHERE u.account_id = a.id\n AND u.role = 'admin'\n)\nAND NOT EXISTS (\n SELECT 1\n FROM subscriptions s\n WHERE s.account_id = a.id\n AND s.plan = 'enterprise'\n);\n```\n\nPenjelasan: Query mengambil akun yang punya minimal satu user dengan `role = 'admin'` (dicek lewat `EXISTS` pada tabel `users`) dan tidak punya langganan dengan `plan = 'enterprise'` (dicek lewat `NOT EXISTS` pada tabel `subscriptions`). Pola `EXISTS`/`NOT EXISTS` mencegah duplikasi hasil dan jelas untuk kondisi “ada” vs “tidak ada”."
55
+ },
56
+ {
57
+ "problem": "Database schema:\n```sql\nCREATE TABLE users (id INT PRIMARY KEY, name VARCHAR, email VARCHAR, created_at TIMESTAMP, country VARCHAR);\nCREATE TABLE products (id INT PRIMARY KEY, name VARCHAR, category VARCHAR, price DECIMAL, stock INT);\nCREATE TABLE orders (id INT PRIMARY KEY, user_id INT, created_at TIMESTAMP, total DECIMAL, status VARCHAR);\nCREATE TABLE order_items (order_id INT, product_id INT, quantity INT, unit_price DECIMAL);\n```\n\nWrite a SQL query to: Find {entity} that have never {action}\n\nReturn the SQL query followed by a brief explanation.",
58
+ "gtruth_answer": "```sql\nSELECT u.*\nFROM users u\nLEFT JOIN orders o ON u.id = o.user_id\nWHERE o.id IS NULL;\n```\n\n**Explanation:**\n\nThis query aims to find users who have never placed an order.\n\n1. **`SELECT u.* FROM users u`**: Selects all columns from the `users` table, aliased as `u`.\n2. **`LEFT JOIN orders o ON u.id = o.user_id`**: Performs a `LEFT JOIN` from the `users` table to the `orders` table based on the `user_id`. A `LEFT JOIN` ensures that every user record is included, even if there is no matching record in the `orders` table.\n3. **`WHERE o.id IS NULL`**: Filters the results to include only those rows where the join failed to find a match in the `orders` table. If a user has no orders, all columns from the `orders` table (including `o.id`) will be `NULL` for that row, thus identifying users who have never placed an order.",
59
+ "message_thinking": "**Clarifying the task**\n\nOkay, the user wants a SQL query to find an entity that has never performed a certain action. I’m thinking they might want a general template for this kind of query, but I’m not sure if they want a specific example based on the schema provided. The schema includes tables for users, products, orders, and order items, so I’ll need to figure out what \"action\" could mean in this context. Maybe it’s about users who haven’t placed an order, or products that haven’t been sold? I’ll need to clarify that.**Clarifying the query pattern**\n\nOkay, the user seems to want a general SQL query template with placeholders for \"entity\" and \"action.\" I think they’re asking for a pattern that can be applied to different situations, like finding users who haven’t placed an order or products that haven’t been ordered. The key here is using something like `NOT EXISTS` to handle the \"never done\" part, avoiding issues with NULL values. I’ll make sure to provide a flexible query template with a brief explanation, so the user can adapt it to their needs.**Clarifying the response**\n\nOkay, the user wants a SQL query template in Indonesian, but the task was written in English. I’ll stick to the user’s request and answer in Indonesian. The task seems to be asking for a general SQL pattern to find entities that have never performed a certain action. I’ll provide a generic template with placeholders, followed by concrete examples based on the schema. I’ll also make sure to explain how to adapt the query to different situations, like finding users who haven’t placed an order or products that haven’t been ordered. Let’s make this clear and helpful!",
60
+ "message_content": "## Pola umum (sesuaikan nama tabel/kolom/FK)\n```sql\n-- Opsi A: NOT EXISTS (disarankan)\nSELECT e.*\nFROM entity e\nWHERE NOT EXISTS (\n SELECT 1\n FROM action_table a\n WHERE a.entity_id = e.id\n);\n\n-- Opsi B: LEFT JOIN ... IS NULL\nSELECT e.*\nFROM entity e\nLEFT JOIN action_table a\n ON a.entity_id = e.id\nWHERE a.id IS NULL;\n```\n\n**Penjelasan singkat**\n- `entity` = tabel entitas yang dicari (mis. `users`, `products`). `action_table` = tabel yang merekam aksi/relasi (mis. `orders`, `order_items`).\n- `a.entity_id = e.id` = kunci relasi dari aksi ke entitas (contoh skema: `orders.user_id = users.id`, `order_items.product_id = products.id`).\n- `NOT EXISTS` mengembalikan entitas yang tidak memiliki baris terkait di `action_table` (aman terhadap `NULL`).\n- `LEFT JOIN ... WHERE a.<pk/fk> IS NULL` juga valid; pastikan kondisi `ON` tepat dan pakai kolom dari tabel aksi yang memang `NULL` saat tidak ada kecocokan.\n\n**Contoh cepat (berdasarkan skema)**\n- Users yang belum pernah membuat order:\n```sql\nSELECT u.*\nFROM users u\nWHERE NOT EXISTS (\n SELECT 1\n FROM orders o\n WHERE o.user_id = u.id\n);\n```\n- Products yang belum pernah ada di `order_items`:\n```sql\nSELECT p.*\nFROM products p\nWHERE NOT EXISTS (\n SELECT 1\n FROM order_items oi\n WHERE oi.product_id = p.id\n);\n```"
61
+ },
62
+ {
63
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: Count the total number of {entity} grouped by {dimension}\n\nReturn the SQL query followed by a brief explanation.",
64
+ "gtruth_answer": "```sql\nSELECT\n T1.dimension,\n COUNT(T2.id) AS count\nFROM\n your_dimension_table AS T1\nJOIN\n your_entity_table AS T2 ON T1.dimension = T2.dimension\nGROUP BY\n T1.dimension;\n```\n\n**Explanation:**\n\nSince the request is a generic template (\"Count the total number of {entity} grouped by {dimension}\"), I have provided a generic template query structure.\n\nTo make this query functional, you would need to replace the placeholders:\n1. `your_dimension_table` and `your_entity_table` with the actual table names from the provided schema (e.g., `patients`, `appointments`, etc.).\n2. `dimension` with the specific column name you want to group by (e.g., `gender` from `patients` or `specialty` from `doctors`).\n3. `entity` with the table whose records you want to count (e.g., `appointments` or `diagnoses`).\n\n**Example based on the schema (Counting appointments by doctor specialty):**\n\nIf the request were: \"Count the total number of appointments grouped by doctor specialty.\"\n\n```sql\nSELECT\n d.specialty,\n COUNT(a.id) AS appointment_count\nFROM\n doctors d\nJOIN\n appointments a ON d.id = a.doctor_id\nGROUP BY\n d.specialty;\n```",
65
+ "message_thinking": "**Writing SQL query**\n\nOkay, the user wants a SQL query to count the total number of an entity, grouped by a dimension. I need to figure out how to generalize this for any entity and dimension. The schema gives me tables like patients, doctors, appointments, etc. So, I’ll need to structure the query to count rows from a table, grouped by a specific column. I’ll also need to explain how the query works after writing it. Let me think through the general structure for this.**Clarifying query structure**\n\nOkay, the user wants a SQL query to count the total number of an entity grouped by a dimension. I think they want a general template, but with placeholders like {entity} and {dimension} to be filled in. I’ll need to give a few examples based on the schema, like counting appointments by doctor, patients by gender, or diagnoses by icd10. The general pattern seems to be: SELECT {dimension}, COUNT(*) AS total_{entity} FROM {table_for_entity}. I’ll explain this structure and provide a couple of examples.**Clarifying SQL query format**\n\nOkay, the user wants a SQL query to count the total number of an entity grouped by a dimension, followed by a brief explanation. I think I should give a general template for the query and explain the placeholders. The query would look like: `SELECT {dimension}, COUNT(*) AS total_{entity} FROM {entity_table} GROUP BY {dimension};`. Then, I’ll explain how to apply it to the schema, like counting appointments per doctor. I’ll also make sure the explanation is clear and in the right language. Let me finalize this.",
66
+ "message_content": "```sql\nSELECT {dimension}, COUNT(*) AS total_{entity}\nFROM {entity_table}\nGROUP BY {dimension};\n```\n\nPenjelasan: Query menghitung jumlah baris entitas dengan `COUNT(*)`, lalu mengelompokkan hasil berdasarkan kolom dimensi menggunakan `GROUP BY {dimension}`. Ganti `{entity_table}`, `{dimension}`, dan alias `total_{entity}` sesuai tabel/kolom di skema (contoh: jumlah `appointments` per `doctor_id` → `FROM appointments GROUP BY doctor_id`, alias `total_appointments`)."
67
+ },
68
+ {
69
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: Calculate the average {metric} for {entity} per {dimension}\n\nReturn the SQL query followed by a brief explanation.",
70
+ "gtruth_answer": "```sql\nSELECT\n d.specialty,\n AVG(p.days) AS average_prescription_days\nFROM\n prescriptions p\nJOIN\n doctors d ON p.doctor_id = d.id\nGROUP BY\n d.specialty;\n```\n\n**Explanation:**\n\nThe request asks to \"Calculate the average {metric} for {entity} per {dimension}\". Based on the provided schema and the generic template, I have interpreted the request as calculating the average number of days prescribed (`days` from the `prescriptions` table) grouped by the doctor's specialty (`specialty` from the `doctors` table).\n\n1. **`FROM prescriptions p`**: Starts with the `prescriptions` table as it contains the metric we want to average (`days`).\n2. **`JOIN doctors d ON p.doctor_id = d.id`**: Joins with the `doctors` table to access the doctor's specialty, which serves as our grouping dimension.\n3. **`GROUP BY d.specialty`**: Groups the results by the doctor's specialty.\n4. **`SELECT d.specialty, AVG(p.days) AS average_prescription_days`**: Selects the specialty and calculates the average of the `days` column for each group.",
71
+ "message_thinking": "**Filling in placeholders for SQL query**\n\nOkay, the user wants a SQL query to calculate the average of some metric for an entity per a dimension, but the placeholders aren't filled in. I need to figure out what makes sense based on the schema. \n\nFor example, if the metric is the number of appointments, the entity could be \"patients,\" and the dimension could be \"doctor\" or \"date.\" I’ll need to make some assumptions here to fill in the blanks and create a meaningful query.**Choosing the right example for the query**\n\nOkay, the user wants a SQL query to calculate the average of a metric for an entity per a dimension. I need to pick sensible values from the schema. \n\nFor the entity, I could choose \"prescriptions\" or \"patients.\" The metric should be numeric, like \"days\" from prescriptions. The dimension could be something like \"doctor specialty\" or \"patient gender.\"\n\nI think a good example would be calculating the average \"days\" for prescriptions per \"doctor specialty.\" That seems clear and fits the schema well.**Finalizing the SQL query**\n\nOkay, I’ve decided to use \"prescriptions.days\" as the numeric metric. The query will join the prescriptions table with the doctors table, group by doctor specialty, and calculate the average number of days for prescriptions per specialty. \n\nI’ll make sure to explain this clearly: the query calculates the average prescription length (in days) for each doctor specialty. \n\nNow, I just need to present the SQL query and the explanation together.",
72
+ "message_content": "```sql\nSELECT d.specialty AS dimension,\n AVG(p.days) AS avg_metric\nFROM prescriptions p\nJOIN doctors d ON p.doctor_id = d.id\nGROUP BY d.specialty\nORDER BY d.specialty;\n```\n\nPenjelasan singkat: query menggabungkan `prescriptions` (entitas) dengan `doctors`, mengelompokkan berdasarkan `doctors.specialty` (dimensi), lalu menghitung `AVG(p.days)` (metrik rata-rata lama resep/hari) untuk tiap specialty."
73
+ }
74
+ ]
data/gemini-3.5-flash-lite-pajak-train.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "problem": "Database schema:\n```sql\nCREATE TABLE accounts (id INT PRIMARY KEY, name VARCHAR, plan VARCHAR, mrr DECIMAL, created_at TIMESTAMP);\nCREATE TABLE users (id INT PRIMARY KEY, account_id INT, email VARCHAR, role VARCHAR, last_login TIMESTAMP);\nCREATE TABLE events (id INT PRIMARY KEY, user_id INT, event_type VARCHAR, created_at TIMESTAMP, properties JSONB);\nCREATE TABLE subscriptions (id INT PRIMARY KEY, account_id INT, plan VARCHAR, start_date DATE, end_date DATE, arr DECIMAL);\n```\n\nWrite a SQL query to: Show month-over-month change in {metric}\n\nReturn the SQL query followed by a brief explanation.",
4
+ "gtruth_answer": "```sql\nWITH monthly_metrics AS (\n SELECT\n DATE_TRUNC('month', e.created_at) AS month_start,\n COUNT(e.id) AS event_count\n FROM\n events e\n GROUP BY\n 1\n)\nSELECT\n month_start,\n event_count,\n LAG(event_count, 1, 0) OVER (ORDER BY month_start) AS previous_month_count,\n event_count - LAG(event_count, 1, 0) OVER (ORDER BY month_start) AS month_over_month_change\nFROM\n monthly_metrics\nORDER BY\n month_start;\n```\n\n**Explanation:**\n\n1. **`monthly_metrics` CTE:**\n * This Common Table Expression (CTE) is used to aggregate the data from the `events` table.\n * It groups the events by the start of the month (`DATE_TRUNC('month', e.created_at)`).\n * It calculates the total count of events (`event_count`) for each month.\n\n2. **Final SELECT Statement:**\n * It selects the month start date, the current month's event count, and calculates the previous month's count using the `LAG()` window function.\n * `LAG(event_count, 1, 0) OVER (ORDER BY month_start)` retrieves the `event_count` from the preceding row (ordered by `month_start`). The default value of `0` is used if no preceding row exists (for the first month).\n * The `month_over_month_change` is calculated by subtracting the previous month's count from the current month's count.\n * The results are ordered chronologically by `month_start`.\n\n*Note: Since the specific `{metric}` was not defined, this query assumes the desired metric is the count of events in the `events` table. If the metric required aggregation from `accounts` or `subscriptions`, the initial CTE would need to be adjusted accordingly.*",
5
+ "message_thinking": "**Defining the Core Task**\n\nI'm currently focused on defining the core task. I'm assuming the role of an SQL developer and aiming to construct a query that reveals month-over-month changes in a given metric, which is currently unspecified. I'm considering examples such as MRR or user count, but need to decide on one, or make the query more general.\n\n\n**Refining the Metric**\n\nI've decided to proceed with `accounts.mrr` as the metric. I'm thinking of how to make the query dynamic and parameterized for any similar metric. I'm focusing on the schema: `accounts`, `users`, `events`, `subscriptions`. I'm also grappling with the language instructions; the prompt instructs to answer in Indonesian, but then to preserve the user's language. I've determined that the user's prompt is English, so I will continue in English.\n\n\n**Clarifying Language Choice**\n\nI've cleared up the language confusion. Indonesian initially requested, but English overrides due to the specific instructions. The style must be \"terse caveman.\" The query will target `accounts.mrr` summed monthly.\n\n\\n\\n\nI'm zeroing in on terse style. `Accounts.mrr` monthly sum. Use `accounts` table. Month of `created_at` or active month. That's the core. Then, what next?\n\n\n**Constructing the Core Query**\n\nI'm now writing the core SQL. I'm starting with `accounts.mrr` monthly sums but switching to subscriptions and annual recurring revenue (ARR) for more accurate monthly snapshots. I've switched the `created_at` date to `subscriptions.start_date` to ensure a closer linkage to MRR changes. I'm focusing on the `LAG` window function for month-over-month calculations.",
6
+ "message_content": "```sql\nWITH monthly_mrr AS (\n SELECT \n DATE_TRUNC('month', created_at) AS month,\n SUM(mrr) AS total_mrr\n FROM accounts\n GROUP BY 1\n)\nSELECT \n month,\n total_mrr,\n LAG(total_mrr) OVER (ORDER BY month) AS prev_mrr,\n total_mrr - LAG(total_mrr) OVER (ORDER BY month) AS mom_change\nFROM monthly_mrr;\n```\n\nCTE `monthly_mrr` aggregate sum `mrr` by month. `LAG()` window function grab prior row value. Subtraction calculate difference."
7
+ },
8
+ {
9
+ "problem": "Database schema:\n```sql\nCREATE TABLE users (id INT PRIMARY KEY, name VARCHAR, email VARCHAR, created_at TIMESTAMP, country VARCHAR);\nCREATE TABLE products (id INT PRIMARY KEY, name VARCHAR, category VARCHAR, price DECIMAL, stock INT);\nCREATE TABLE orders (id INT PRIMARY KEY, user_id INT, created_at TIMESTAMP, total DECIMAL, status VARCHAR);\nCREATE TABLE order_items (order_id INT, product_id INT, quantity INT, unit_price DECIMAL);\n```\n\nWrite a SQL query to: Get the {ranking} {entity} for each {dimension}\n\nReturn the SQL query followed by a brief explanation.",
10
+ "gtruth_answer": "```sql\nSELECT\n p.name AS product_name,\n SUM(oi.quantity) AS total_ordered_quantity\nFROM\n products p\nJOIN\n order_items oi ON p.id = oi.product_id\nGROUP BY\n p.name\nORDER BY\n total_ordered_quantity DESC;\n```\n\n**Explanation:**\n\nThe request is a template: \"Get the {ranking} {entity} for each {dimension}\". Based on the provided schema, a common and meaningful interpretation of this request would be to find the **top-selling products** (ranking) by **product name** (entity) grouped by some dimension (though the prompt is vague, grouping by product name and summing quantities is a standard aggregation).\n\n1. **JOIN:** We join the `products` table (to get the product name) with the `order_items` table (which contains the quantity ordered for each product).\n2. **GROUP BY:** We group the results by `p.name` to aggregate the quantities for each distinct product.\n3. **SUM:** We calculate the `SUM(oi.quantity)` to find the total number of units sold for each product.\n4. **ORDER BY:** We order the final result in descending order based on the `total_ordered_quantity` to achieve the \"ranking\" (highest quantity first).",
11
+ "message_thinking": "**Assessing the Parameters**\n\nI'm now zeroing in on the specifics: The intended role is an Indonesian-speaking SQL developer tackling SQL problems. I am dissecting the initial instructions and trying to understand all constraints.\n\n\n**Resolving the Language Conflict**\n\nI'm now wrestling with the language directives. The issue revolves around conflicting instructions: the user wrote English, but the developer prompt requests Indonesian. The system prompt then specifies English. I believe the system prompt regarding \"user input = response\" takes precedence, so English is the appropriate choice. I'm focusing on ensuring consistent language use moving forward.\n\n\n**Clarifying Ambiguities**\n\nI'm now clarifying the ambiguities in the user's query. The user provided a template string, so I'm deciding on default values. I'm choosing \"top product by sales per category\" as the assumed intent. I considered other options, such as \"top customer by total spend per country,\" but this default seems most applicable.\n\n\n**Defining the Core Query**\n\nI am now focusing on query structure. I've broken the task into components: ranking, entity, and dimension. My intent is to craft an SQL query that identifies the top-ranked product per category. The style must be terse with no filler, just fragments and action. I'm focusing on SQL structure to retrieve ranking and total sales.",
12
+ "message_content": "```sql\nWITH ranked AS (\n SELECT \n p.category,\n p.name,\n SUM(oi.quantity) AS total_qty,\n ROW_NUMBER() OVER (PARTITION BY p.category ORDER BY SUM(oi.quantity) DESC) AS rnk\n FROM products p\n JOIN order_items oi ON p.id = oi.product_id\n GROUP BY p.category, p.name\n)\nSELECT category, name, total_qty\nFROM ranked\nWHERE rnk = 1;\n```\n\nCTE aggregate product quantity per category. ROW_NUMBER partition category order quantity desc assign rank. Outer query filter rank equals one get top product each category."
13
+ },
14
+ {
15
+ "problem": "Database schema:\n```sql\nCREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR, dob DATE, gender VARCHAR, insurance_id VARCHAR);\nCREATE TABLE doctors (id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, license_num VARCHAR);\nCREATE TABLE appointments (id INT PRIMARY KEY, patient_id INT, doctor_id INT, date TIMESTAMP, status VARCHAR);\nCREATE TABLE diagnoses (id INT PRIMARY KEY, patient_id INT, icd10 VARCHAR, date DATE, notes TEXT);\nCREATE TABLE prescriptions (id INT PRIMARY KEY, patient_id INT, doctor_id INT, drug VARCHAR, dosage VARCHAR, days INT);\n```\n\nWrite a SQL query to: List all {entity} that {condition} but not {other_condition}\n\nReturn the SQL query followed by a brief explanation.",
16
+ "gtruth_answer": "```sql\nSELECT T1.*\nFROM patients AS T1\nWHERE T1.insurance_id IS NOT NULL -- Replace with the actual condition for the entity\n AND T1.gender = 'Male' -- Replace with the actual condition for the entity\n AND T1.insurance_id <> 'INS001'; -- Replace with the actual condition for the other_condition\n```\n\n**Explanation:**\n\nSince the natural language prompt provided a template (\"List all {entity} that {condition} but not {other_condition}\"), and did not provide specific entity, condition, or other condition details, I have written a generic example query targeting the `patients` table.\n\n1. **`SELECT T1.* FROM patients AS T1`**: This selects all columns from the `patients` table.\n2. **`WHERE T1.insurance_id IS NOT NULL`**: This represents the first condition (e.g., \"that has an insurance ID\").\n3. **`AND T1.gender = 'Male'`**: This represents the second condition (e.g., \"and is male\").\n4. **`AND T1.insurance_id <> 'INS001'`**: This represents the exclusion condition (e.g., \"but not having insurance ID 'INS001'\").\n\nTo get a specific, accurate query, please provide the actual values for `{entity}`, `{condition}`, and `{other_condition}`.",
17
+ "message_thinking": "**Reviewing the Instructions**\n\nI'm currently dissecting the instructions, particularly the language requirements. There's a slight contradiction I need to resolve regarding the expected language output, as the system prompt offers a potentially conflicting instruction. I need to clarify if it is Indonesian. I will work with the conflicting sections now.\n\n\n**Clarifying Language Preference**\n\nI'm now focused on the language directive inconsistencies. The core conflict lies between the explicit instruction to answer in Indonesian and the system's instruction to preserve the user's language, which in this case is English. Considering the user's input is in English, I'm leaning toward prioritizing English, but the Indonesian directive warrants caution. It's a complicated directive at the moment.\n\n\n**Formulating Example Queries**\n\nI'm now zeroing in on generating SQL query examples from the prompt. The user provided a template, and I'm crafting a concrete instance using \"patients\" and \"prescriptions vs. diagnoses\". I have settled on the example case, \"List all patients that have prescriptions but no diagnoses\". I am also checking the schema to inform my query's structure, focusing on patients, prescriptions and diagnoses.",
18
+ "message_content": "```sql\nSELECT p.*\nFROM patients p\nJOIN prescriptions pr ON p.id = pr.patient_id\nWHERE p.id NOT IN (\n SELECT patient_id \n FROM diagnoses\n);\n```\n`JOIN` fetches patients having prescriptions. `NOT IN` excludes patients having diagnoses."
19
+ }
20
+ ]
data/gpt-6-luna-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
data/mm-MiniMax-M3.1-Flash-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
data/nvidia-nemotron-3-ultra-550b-a55b-free-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
data/nvidia-nemotron-3-ultra-550b-a55b-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
data/pajak-eval.json ADDED
The diff for this file is too large to render. See raw diff
 
data/pajak-train.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c26d7fbea11d55eb9de7ca8da7e2cd55ef2359b6c39dac4b585782ff7a91a1e0
3
+ size 22407493
data/pajak-train_4000.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bee749c2a936c40246f87b399b5c7a589faaf75438cab480cfab7f9d34ff0201
3
+ size 22295709
data/z-ai-glm-5.3-flash-pajak-train.json ADDED
The diff for this file is too large to render. See raw diff
 
scripts/average_field_lengths_json.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hitung statistik panjang token per field. Contoh:
2
+ # python scripts/average_field_lengths_json.py --json_path data/pajak-eval.json --tokenizer Qwen/Qwen3-0.6B
3
+ import argparse, json
4
+ from transformers import AutoTokenizer
5
+
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument("--json_path", required=True)
8
+ parser.add_argument("--tokenizer", default="Qwen/Qwen3-0.6B")
9
+ args = parser.parse_args()
10
+
11
+ tok = AutoTokenizer.from_pretrained(args.tokenizer)
12
+ data = json.load(open(args.json_path, encoding="utf-8"))
13
+ print(f"Records: {len(data)}")
14
+ print(f"Tokenizer: {args.tokenizer}")
15
+ print(f"{'Field':<17} {'AvgTokens':>9} {'MinTokens':>10} {'MaxToken':>9} {'Count':>6}")
16
+ for field in ["gtruth_answer", "message_content", "message_thinking", "problem"]:
17
+ lens = [len(x) for x in tok([d[field] for d in data], add_special_tokens=False)["input_ids"]]
18
+ print(f"{field:<17} {sum(lens)/len(lens):>9.2f} {min(lens):>10} {max(lens):>9} {len(lens):>6}")
scripts/evaluate_json.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hitung akurasi jawaban (\boxed{...} vs gtruth_answer). Contoh:
2
+ # python scripts/evaluate_json.py --json_path data/pajak-eval.json --gtruth_answer gtruth_answer --generated_text message_content
3
+ import argparse, json, re
4
+
5
+ def extract_boxed(text):
6
+ i = text.rfind("\\boxed{")
7
+ if i < 0: return None
8
+ j, depth, out = i + 7, 1, []
9
+ while j < len(text) and depth:
10
+ c = text[j]
11
+ if c == "{": depth += 1
12
+ elif c == "}": depth -= 1
13
+ if depth: out.append(c)
14
+ j += 1
15
+ return "".join(out) if depth == 0 else None
16
+
17
+ def to_num(s):
18
+ m = re.search(r"-?\d[\d.,]*", s.replace("\\,", ""))
19
+ if not m: return None
20
+ g = m.group(0).rstrip(".,")
21
+ if re.fullmatch(r"\d{1,3}(\.\d{3})+(,\d+)?", g): g = g.replace(".", "").replace(",", ".")
22
+ elif re.fullmatch(r"\d{1,3}(,\d{3})+(\.\d+)?", g): g = g.replace(",", "")
23
+ else: g = g.replace(",", ".")
24
+ try: return float(g)
25
+ except ValueError: return None
26
+
27
+ def norm(s): return re.sub(r"\W+", " ", s.lower()).strip()
28
+
29
+ parser = argparse.ArgumentParser()
30
+ parser.add_argument("--json_path", required=True)
31
+ parser.add_argument("--gtruth_answer", default="gtruth_answer")
32
+ parser.add_argument("--generated_text", default="message_content")
33
+ args = parser.parse_args()
34
+
35
+ data = json.load(open(args.json_path, encoding="utf-8"))
36
+ correct = 0
37
+ for d in data:
38
+ pred, gt = extract_boxed(d[args.generated_text]), d[args.gtruth_answer]
39
+ if pred is None: continue
40
+ a, b = to_num(gt), to_num(pred)
41
+ if a is not None and b is not None: correct += abs(a - b) < 0.5
42
+ else: correct += norm(gt) == norm(pred) or norm(gt) in norm(pred) or norm(pred) in norm(gt)
43
+ print(f"Answer accuracy: {correct/len(data):.1%} ({correct}/{len(data)})")