Enhance dialog context handling for Text2SQL queries by integrating session history. Introduce new methods for summarizing previous assistant messages and determining if the last interaction was a data query. Update environment configuration for embedding options and improve error handling in SQL generation. Add user-facing delivery messages for successful SQL execution. This update supports more coherent follow-up questions and improves user experience in conversational interactions.
This commit is contained in:
@@ -14,7 +14,8 @@ MAX_TOKENS=4096
|
||||
TEXT2SQL_DIALECT=sqlserver
|
||||
|
||||
# ========== Embedding 配置 ==========
|
||||
# false = 使用兼容 OpenAI 的远程 /v1/embeddings(优先 ModelScope,未配置 MODELSCOPE_* 时用 DashScope)
|
||||
# 默认 false:使用远程 /v1/embeddings(须配置下方 OPENAI_* 或 MODELSCOPE_* 等)
|
||||
# 仅当 true 时需设置 EMBEDDING_MODEL_PATH 指向本地 HuggingFace 模型目录
|
||||
USE_LOCAL_EMBEDDING=false
|
||||
# ModelScope 推理 API:https://www.modelscope.cn/docs/inference-api
|
||||
# MODELSCOPE_API_KEY=ms-b95f3233-4797-4efd-90e6-b3728743571d
|
||||
@@ -28,13 +29,17 @@ OPENAI_BASE_URL=http://113.192.49.54:9080/v1
|
||||
OPENAI_API_KEY=sk-proj-FEb2ChHZK5Llm0tBkmNIT3BlbkFJbu0b0zQpTW8762yD6HDv
|
||||
OPENAI_EMBEDDING_MODEL=text-embedding-ada-002
|
||||
|
||||
|
||||
# ========== Schema 配置 ==========
|
||||
SCHEMA_DIR=./data/schemas
|
||||
SCHEMA_FILE=${SCHEMA_DIR}/G3SB_MCDataDictionary_table_structure.json
|
||||
|
||||
# ========== 向量数据库配置 ==========
|
||||
# ========== 数据文件与向量库路径(均相对仓库根目录)==========
|
||||
# G3SB 表结构;api_server 用 SCHEMA_PATH / SCHEMA_META_PATH(勿用 SCHEMA_FILE,代码不读)
|
||||
SCHEMA_PATH=./data/schemas/G3SB_MCDataDictionary_table_structure.json
|
||||
# G3SB 表注释,与 structure 同名配对;粗筛 embedding 文本会含表注释
|
||||
SCHEMA_META_PATH=./data/schemas/G3SB_MCDataDictionary_table_meta.json
|
||||
# Schema 表级向量持久化目录(Chroma 集合名固定为 schema_tables);改 structure/meta 后需强制重建索引
|
||||
VECTOR_DB_PATH=./data/embeddings/chroma
|
||||
# Few-shot 源 JSONL(build_fewshot_chroma_index.py 默认读此变量)
|
||||
FEWSHOT_DATA_PATH=./data/experiences/all_samples.jsonl
|
||||
# Few-shot 向量持久化目录(Chroma 集合名默认 fewshot_samples;勿与 VECTOR_DB_PATH 混用同一目录)
|
||||
FEWSHOT_CHROMA_PATH=./data/embeddings/chroma_fewshot
|
||||
|
||||
# ========== 验证配置 ==========
|
||||
ENABLE_SQL_VALIDATION=true
|
||||
@@ -51,11 +56,14 @@ FEWSHOT_ENABLED=true
|
||||
FEWSHOT_TOP_K=3
|
||||
# 示例最低评分(1-10)
|
||||
FEWSHOT_MIN_RATING=7
|
||||
# 经验数据集路径
|
||||
FEWSHOT_DATA_PATH=./data/experiences/all_samples.jsonl
|
||||
# 优先使用 Chroma 向量库(运行时检索不依赖 JSONL;灌库: python scripts/build_fewshot_chroma_index.py --force)
|
||||
FEWSHOT_USE_CHROMA=true
|
||||
# 留空则用代码默认集合名 fewshot_samples
|
||||
FEWSHOT_CHROMA_COLLECTION=
|
||||
|
||||
# ========== 日志配置 ==========
|
||||
LOG_LEVEL=INFO
|
||||
LOG_FILE=./logs/text2sql.log
|
||||
|
||||
# 业务库 SQLAlchemy URL(试执行探针 / dbhub);也可用 DATABASE_URL
|
||||
database_url=mssql+pymssql://sa:123456@192.168.3.201:1433/G3SB_PROD_HW
|
||||
|
||||
+118
-63
@@ -1,109 +1,164 @@
|
||||
# Impact Analysis Report — NL2SQL 确定性(temperature)
|
||||
# Impact Analysis Report — 会话上文注入 Text2SQL
|
||||
|
||||
## 1. 改动概览
|
||||
|
||||
- **背景与目标**:同一中文问题多次请求时,选表与生成 SQL 因 LLM 采样(默认 `temperature=0.3`)出现不一致。
|
||||
- **涉及模块**:`backend/llm/deepseek_client.py`(选表、校验、便捷 `generate_sql`)、`backend/agents/orchestrator.py`(编排器内 SQL 生成)。
|
||||
- **改动类型**:缺陷修复 / 行为稳定性增强(非功能扩展)。
|
||||
- **背景与目标**:在带 `session_id` 的 NL 对话中,将前几轮已落库的对话摘要注入选表、向量粗筛、SQL 生成与「无数据」说明,支持续问与指代消解。
|
||||
- **涉及模块**:`api_server.py`、`backend/utils/dialog_context.py`(新)、`backend/utils/dialog_classifier.py`、`backend/agents/orchestrator.py`。
|
||||
- **改动类型**:功能新增(向后兼容:无 `session_id` 或空历史时行为与原先一致)。
|
||||
|
||||
## 2. 方法级改动
|
||||
|
||||
| 位置 | 原行为 | 新行为 |
|
||||
|------|--------|--------|
|
||||
| `DeepSeekClient.select_tables` | 使用配置默认 `temperature`(如 0.3) | `setdefault(temperature=0.0, top_p=1.0)` 后调用 `chat_with_json`;调用方仍可通过 `**kwargs` 覆盖 |
|
||||
| `DeepSeekClient.validate_sql` | 同上 | 同上 |
|
||||
| `DeepSeekClient.generate_sql` | 同上 | 同上 |
|
||||
| `Text2SQLOrchestrator._generate_sql` | `chat(messages)` 使用默认温度 | 显式 `temperature=0.0, top_p=1.0` |
|
||||
|
||||
与原有逻辑差异:选表、校验、SQL 文本生成在相同 prompt 下更趋确定;若上游 API 在 `temperature=0` 下仍存在极小浮动,属于服务商实现范畴。
|
||||
| 位置 | 变更 |
|
||||
|------|------|
|
||||
| `LiteNlStore` | 无变更;仍由 `_append_session_if_needed` 在应答后写入。 |
|
||||
| `_load_session_text2sql_context`(api_server) | 新增:读 `get_messages`,构造上文块,并判断上一轮是否为数据查询。 |
|
||||
| `classify_dialog` | 新增可选关键字参数 `last_turn_was_data_query`;为 True 时在非寒暄/非元问题下将输入倾向判为 TEXT2SQL。 |
|
||||
| `messages_to_text2sql_context` 等 | 新工具:消息列表 → 可读摘要;解析 assistant JSON。 |
|
||||
| `Text2SQLOrchestrator.generate` | 新增可选 `dialog_context`;粗筛/选表/续问 broker 优先/生成/无数据反馈使用该上文。 |
|
||||
| `_generate_sql` / `_validate_sql` | 接收 `dialog_context`,Few-shot 检索问题与生成 user 提示含上文。 |
|
||||
|
||||
## 3. 调用方与影响范围
|
||||
|
||||
- **调用方**:`orchestrator._llm_select_tables` → `deepseek.select_tables`;`orchestrator._generate_sql` → `deepseek.chat`;校验链路 → `validate_sql`;脚本或其它代码若直接调用 `generate_sql`/`select_tables`/`validate_sql` 并传入自定义 `temperature`,**仍以调用方 kwargs 为准**(`setdefault` 不覆盖已传值)。
|
||||
- **输入输出**:接口签名未变;返回 JSON/SQL 文本的**内容分布**更集中,极端情况下可能从「多种可接受 SQL」收敛到其中一种。
|
||||
- **破坏性变更**:否(未改公开方法签名;仅默认采样参数与编排器单次 `chat` 参数)。
|
||||
- **调用方**:`/g3sb/api/nl/chat`、`/g3sb/api/nl/chat/stream`(仅当请求带有效 `session_id` 且会话内已有历史消息时生效)。
|
||||
- **CLI `backend/main.py` `single_query`**:现传入 `llm_client`;当 `DIALOG_INTENT_CLASSIFIER=rules` 时与旧规则行为一致。
|
||||
- **破坏性变更**:否(新增可选参数与默认 `False` 的关键字参数)。
|
||||
|
||||
## 4. 风险与回滚
|
||||
|
||||
- **风险级别**:低。可能略微降低「多解探索」多样性;对 Text2SQL 通常可接受。
|
||||
- **回滚**:恢复上述文件中的 `setdefault` / 显式 `temperature` 改动,或于环境变量/配置层为 DeepSeek 提高默认 `temperature`(若未来抽到配置项)。
|
||||
- **回滚方式是否简单**:是(单提交回退即可)。
|
||||
- **风险级别**:中(依赖会话中 assistant 内容为合法 JSON;解析失败时上文退化为截断原文或空段)。
|
||||
- **额外成本**:带历史的请求 prompt 更长,token 与耗时可能上升。
|
||||
- **回滚**:回退本提交即可;无配置开关。
|
||||
|
||||
**回滚方式是否简单**:是。
|
||||
|
||||
## 5. 验证与测试
|
||||
|
||||
- **建议**:对固定中文问题连续请求 5~10 次,比对日志中 `LLM精筛选中表` 与最终 SQL 是否一致。
|
||||
- **说明**:Few-shot / 向量粗筛若存在非确定性实现,仍可能导致差异;本次改动仅消除 **LLM 采样** 主导的不一致。
|
||||
- 已执行:`python -m py_compile` 对改动文件语法检查。
|
||||
- 建议手工:创建 session → 首轮数据查询 → 次轮「按上个月再查一遍」类续问,确认走 TEXT2SQL 且 SQL 与上文一致。
|
||||
|
||||
## 6. 配置变更(temperature 项)
|
||||
## 6. 配置变更
|
||||
|
||||
- 无新增环境变量或配置文件项;未改 `.env`。
|
||||
- 无。
|
||||
|
||||
---
|
||||
|
||||
# 增补:英文问句先译中文再走 Text2SQL(2026-04)
|
||||
# Impact Analysis Report — 库探针追问与交付分支(追加)
|
||||
|
||||
## 1. 改动概览
|
||||
|
||||
- **目标**:缓解「同一意图中英文提问选表/SQL 不一致」——在无 CJK 的英文问句进入粗筛、选表、few-shot、SQL 生成前,先经 DeepSeek 译为中文。
|
||||
- **涉及模块**:`backend/utils/question_locale.py`(新建)、`backend/config/prompts.py`、`backend/llm/deepseek_client.py`、`backend/agents/orchestrator.py`、`backend/main.py`、`api_server.py`。
|
||||
- **目标**:对齐库探针语义:`0` 无行时返回 SQL + 问题分析 + 固定追问引导重生成;`1` 有行时由 LLM 生成简短交付说明并返回 SQL;`-1` 失败时明确文案并走既有重试。
|
||||
- **涉及模块**:`backend/agents/orchestrator.py`、`backend/llm/deepseek_client.py`、`backend/config/prompts.py`、`api_server.py`(`DataQueryResult` 字段)、`backend/utils/dialog_context.py`(摘要)。
|
||||
|
||||
## 2. 方法级改动
|
||||
## 2. 破坏性变更
|
||||
|
||||
| 符号 | 说明 |
|
||||
|------|------|
|
||||
| `looks_like_english_only` | 无中日韩/假名/韩文且拉丁字母≥3 时视为「可译英文」 |
|
||||
| `DeepSeekClient.translate_nl_question_to_zh` | 一次 `chat(temperature=0)`,返回单行中文问句 |
|
||||
| `Text2SQLOrchestrator.generate` | 开头若开启且命中启发式则译问句,后续全流程使用中文;`metadata` 含 `question_original`、`question_zh_normalized` |
|
||||
| `_nl_dict_from_generation` | 若有译句,响应增加 `query_normalization: { original, zh }` |
|
||||
- **否**(API 新增可选字段;未配置 `database_url` 时行为与原先一致)。
|
||||
|
||||
## 3. 调用方与破坏性变更
|
||||
## 3. 风险
|
||||
|
||||
- **调用方**:所有 `orchestrator.generate()`;API 层无签名变更。
|
||||
- **破坏性变更**:否。默认开启;关闭后行为与旧版一致。英文请求多一次 LLM 调用(延迟与费用略增)。
|
||||
- **低~中**:探针为 `1` 时增加一次 LLM 调用(延迟与 token);失败时降级为仅返回 SQL。
|
||||
|
||||
## 4. 配置变更
|
||||
## 4. 验证
|
||||
|
||||
| 变量 | 含义 | 默认 |
|
||||
|------|------|------|
|
||||
| `TRANSLATE_EN_TO_ZH` | `false`/`0`/`off` 关闭英译中 | 开启 |
|
||||
|
||||
CLI:`python backend/main.py --no-translate-en` 关闭。
|
||||
|
||||
## 5. 风险与回滚
|
||||
|
||||
- **风险**:翻译偏差导致表意偏移;专有名词若未保留可能被误译。
|
||||
- **回滚**:`TRANSLATE_EN_TO_ZH=false` 或 `--no-translate-en`;或回退相关提交。
|
||||
- **回滚方式是否简单**:是。
|
||||
- `python -m py_compile` 覆盖改动文件。
|
||||
|
||||
---
|
||||
|
||||
# 增补:库探针状态码 0 / 1 / -1 语义对齐(2026-04)
|
||||
# Impact Analysis Report — Few-shot 写入 Chroma(追加)
|
||||
|
||||
## 1. 改动概览
|
||||
|
||||
- **目标**:与业务约定一致——**1** 表示查询返回至少一行数据;**0** 表示执行成功但**行数为 0**(含「有列无行」的 SELECT);**-1** 表示执行失败并触发重新生成,且重试提示携带数据库错误摘要。
|
||||
- **涉及模块**:`backend/db/dbhub_tools.py`、`backend/agents/orchestrator.py`、`backend/llm/deepseek_client.py`(注释)、`backend/main.py`(CLI 展示无行说明)、`backend/db/__init__.py`、`tools/dbhub_tools.py`、`tools/__init__.py`。
|
||||
- **目标**:将 `all_samples.jsonl` 写入 Chroma 持久化向量库;`FEWSHOT_USE_CHROMA=true` 时 `FewShotSelector` 从 Chroma 检索,否则仍用内存 + `.npy` 缓存。
|
||||
- **新增**:`backend/utils/fewshot_chroma_store.py`、`scripts/build_fewshot_chroma_index.py`;`.env` 增加注释说明;`FewShotSelector` 扩展参数与分支逻辑。
|
||||
|
||||
## 2. 方法级改动
|
||||
## 2. 破坏性变更
|
||||
|
||||
| 符号 | 说明 |
|
||||
|------|------|
|
||||
| `probe_sql_execution_status_ex` | 新增;返回 `(status, error_message)`,`-1` 时第二项为异常字符串 |
|
||||
| `probe_sql_execution_status` | 仍返回 `int \| None`,内部委托 `_ex`,**语义变更**:由「有列或行即 1」改为「**至少一行数据**为 1」 |
|
||||
| `Text2SQLOrchestrator._validate_sql` | `-1` 错误信息附带库端详情;状态 `0` 时在 LLM 反馈外增加固定前缀,引导用户核对 SQL 并补充条件 |
|
||||
| `single_query` | 验证通过且存在 `db_empty_feedback` 时打印「探针 0」说明块 |
|
||||
- **否**(默认 `FEWSHOT_USE_CHROMA` 未开启时行为不变)。
|
||||
|
||||
## 3. 风险
|
||||
|
||||
- **中**:Chroma metadata 对单字段长度有限制,超长 SQL/说明在入库时截断;换 Embedding 模型后应 `--force` 重建索引。
|
||||
|
||||
## 4. 验证
|
||||
|
||||
- `python -m py_compile` 已通过相关文件。
|
||||
|
||||
**追加(Chroma 优先、JSONL 可选)**:`FEWSHOT_USE_CHROMA=true` 且未设置 `FEWSHOT_DATA_PATH` 时,编排器默认不再读 JSONL;`FewShotSelector` 支持无文件 + Chroma 检索;`get_stats` / `get_tagged_examples` 在无内存样本时从 Chroma 全量导出统计。
|
||||
|
||||
**追加(Embedding 默认远程)**:移除对 `data/models/Qwen3-Embedding-0.6B` 的默认依赖;`USE_LOCAL_EMBEDDING` 默认视为 `false`;`get_embedder` / `setup_environment` / `EMBEDDING_MODEL_PATH` 与文档对齐为「远程 OpenAI 兼容等优先,本地仅显式开启」。
|
||||
|
||||
---
|
||||
|
||||
# Impact Analysis Report — Workbuddy Markdown → JSONL(追加)
|
||||
|
||||
## 1. 改动概览
|
||||
|
||||
- **目标**:将 `data/常问问题对应SQL_50个问题知识库_Workbuddy生成.md` 转为与 `data/experiences/all_samples.jsonl` 同结构的 JSONL,并保证每条含 `question_en`(英文题干)。
|
||||
- **新增**:`scripts/md_workbuddy_to_jsonl.py`;产出 `data/experiences/workbuddy_50_questions.jsonl`(50 行)。
|
||||
- **改动类型**:数据与脚本(可重复生成)。
|
||||
|
||||
## 2. 方法级说明
|
||||
|
||||
- 解析 Markdown 中 `## Qn` 节:`### 问题`(中英分行)、全部 `` ```sql `` 块(去重拼接)、`### SQL执行结果` / 内联结果、`### SQL理由`、`### SQL准确度评分`。
|
||||
- 与 `all_samples.jsonl` 按 `qid` 合并 `schema_info`、`tags`、`difficulty`;正文覆盖 `question_zh`、`question_en`、`sql`、`explanation`、`rating`、`result_note`。
|
||||
- 写出 JSONL 时字段顺序固定为:`question_zh` 后紧跟 **`question_en`**(便于在极长单行里肉眼看到英文题干)。
|
||||
- **Q50**:Markdown 仅有中文问题;脚本补充 `question_en`:`List all client trade records for today.`
|
||||
|
||||
## 3. 调用方与破坏性变更
|
||||
|
||||
- **调用方**:仅编排器直接调用探针;对外 API 仍通过 `GenerationResult.metadata` 的 `db_execution_status` / `db_empty_feedback` 表达结果。
|
||||
- **破坏性变更**:是(**语义**)。此前「SELECT 返回 0 行但有列名」会被判为 **1**;现改为 **0**,会走无数据说明分支而非「直接可交付」。
|
||||
- **调用方**:无运行时自动引用;需手工执行 `python scripts/md_workbuddy_to_jsonl.py` 或下游自行读 JSONL。
|
||||
- **破坏性变更**:否。
|
||||
|
||||
## 4. 风险与回滚
|
||||
|
||||
- **风险**:低~中。更多查询会落入「无数据行」分支,多一次 `empty_result_user_feedback` LLM 调用;但更符合「无数据则请用户补充」的产品逻辑。
|
||||
- **回滚**:恢复 `probe_sql_execution_status` 内基于「列或行非空」判定 1 的旧实现,并回退编排器与 CLI 改动。
|
||||
- **回滚方式是否简单**:是。
|
||||
- **风险**:低(生成物可被版本管理;`schema_info` 与含多段 SQL 的题目可能不完全一致,仍以 `all_samples` 为基线)。
|
||||
- **回滚**:删除脚本与 JSONL,或从 Git 回退。
|
||||
|
||||
## 5. 配置变更
|
||||
**回滚方式是否简单**:是。
|
||||
|
||||
## 5. 验证
|
||||
|
||||
- 已执行:`python scripts/md_workbuddy_to_jsonl.py`;校验 50 行且 `question_en` 均非空。
|
||||
|
||||
## 6. 配置变更
|
||||
|
||||
- 无。
|
||||
|
||||
---
|
||||
|
||||
# Impact Analysis Report — 对话意图 hybrid + LLM(追加)
|
||||
|
||||
## 1. 改动概览
|
||||
|
||||
- **背景与目标**:纯规则在「上一轮为数据查询」时把「结果不对」等反馈误判为 TEXT2SQL;改为默认 **hybrid**:明显查数词/寒暄/元问题仍走规则,其余由 **LLM 输出 JSON** 判定 `text2sql` / `conversation`。
|
||||
- **涉及模块**:`backend/utils/dialog_classifier.py`、`backend/config/prompts.py`(`DIALOG_INTENT_CLASSIFIER_*`)、`api_server.py`、`backend/main.py`。
|
||||
- **改动类型**:功能调整(默认多一次小 LLM 调用;可配置关闭)。
|
||||
|
||||
## 2. 方法级改动
|
||||
|
||||
| 位置 | 变更 |
|
||||
|------|------|
|
||||
| `classify_dialog` | 新增可选参数 `dialog_context`、`llm_client`;引入 `_classify_dialog_rules`、`_classify_dialog_llm`;读环境变量 `DIALOG_INTENT_CLASSIFIER`。 |
|
||||
| `api_server` 流式/非流式 NL | 在分类前 `get_orchestrator()`,用 `asyncio.to_thread(classify_dialog, ..., llm_client=orch.deepseek)` 避免阻塞事件循环。 |
|
||||
| `single_query` | `classify_dialog(question, llm_client=orchestrator.deepseek)` 与 API 对齐。 |
|
||||
|
||||
## 3. 调用方与影响范围
|
||||
|
||||
- **调用方**:`/g3sb/api/nl/chat`、`/g3sb/api/nl/chat/stream`、`single_query`。
|
||||
- **破坏性变更**:否;`DIALOG_INTENT_CLASSIFIER=rules` 时与原先规则路径一致(无 LLM 意图调用)。
|
||||
|
||||
## 4. 风险与回滚
|
||||
|
||||
- **风险级别**:中(每轮非「快速命中」类输入增加一次短 LLM 调用:延迟与费用;JSON 异常时回退规则)。
|
||||
- **回滚**:设 `DIALOG_INTENT_CLASSIFIER=rules` 或回退代码提交。
|
||||
|
||||
**回滚方式是否简单**:是。
|
||||
|
||||
## 5. 验证与测试
|
||||
|
||||
- 建议手工:`hybrid` 下首轮查数 → 次轮「这个结果不正确呀」应判为 conversation 并返回引导文案,不跑选表/SQL 链路。
|
||||
|
||||
## 6. 配置变更
|
||||
|
||||
| 配置项 | 含义 | 默认 |
|
||||
|--------|------|------|
|
||||
| `DIALOG_INTENT_CLASSIFIER` | `hybrid`:规则快速路径 + LLM;`rules`:仅规则 | `hybrid`(未设置时按 hybrid 处理) |
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
## 🚀 核心特性
|
||||
|
||||
- **🤖 多Agent协作流水线**:Schema Linker → SQL Generator → Validator 三阶段协作
|
||||
- **🎯 高精度表检索**:向量检索(Qwen3-Embedding)+ LLM精筛,从 250+ 张表中精准定位相关表
|
||||
- **🎯 高精度表检索**:向量检索(OpenAI 兼容 / ModelScope 等远程 Embedding,或可选本地模型)+ LLM精筛,从 250+ 张表中精准定位相关表
|
||||
- **💡 经验数据集 Few-Shot**:基于 50 条高质量样例的语义检索,动态注入相似示例提升准确率
|
||||
- **🔒 双重验证机制**:程序语法验证 + LLM语义验证,确保 SQL 正确性
|
||||
- **🏦 金融领域深度优化**:针对证券经纪业务(账户、持仓、现金、结算)定制 Prompt 和推断规则
|
||||
@@ -24,7 +24,7 @@
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ 阶段1: Schema Linker Agent │
|
||||
│ ┌───────────────────────────────────────────────────────────┐ │
|
||||
│ │ 1.1 向量检索粗筛(ChromaDB + Qwen3-Embedding) │ │
|
||||
│ │ 1.1 向量检索粗筛(ChromaDB + Embedding 向量) │ │
|
||||
│ │ - 检索 Top 20 候选表(相似度阈值 0.1) │ │
|
||||
│ │ └─ 支持对手方/经纪商问题特殊处理(强制纳入 Broker 表) │ │
|
||||
│ │ │ │
|
||||
@@ -85,7 +85,7 @@
|
||||
|------|---------|-----------|
|
||||
| Agent 框架 | **CAMEL AI** | >= 0.2.0,角色扮演、消息通信 |
|
||||
| LLM 模型 | **DeepSeek-chat** | 国产大模型,代码生成能力强 |
|
||||
| Embedding | **Qwen3-Embedding-0.6B** | 阿里云 6 亿参数,本地免费部署 |
|
||||
| Embedding | **远程 API(默认)** | OpenAI 兼容 / ModelScope 等;可选本地 HF 目录 |
|
||||
| 向量数据库 | **ChromaDB** | 本地轻量,持久化 Schema 索引 |
|
||||
| SQL 解析 | **sqlglot** | >= 20.0.0,多方言 AST 转换与验证 |
|
||||
| 配置管理 | **Pydantic Settings** | 类型安全的环境变量管理 |
|
||||
@@ -115,7 +115,7 @@ text2sql_agent_camel/
|
||||
│ ├── llm/
|
||||
│ │ └── deepseek_client.py # DeepSeek API 客户端(chat / validate_sql / select_tables)
|
||||
│ └── utils/
|
||||
│ ├── embedding.py # Qwen3-Embedding 封装(本地 / 远程 API)
|
||||
│ ├── embedding.py # Embedding(远程 OpenAI 兼容 / 可选本地 HF)
|
||||
│ ├── sql_parser.py # sqlglot 工具(语法验证、方言转换、规范化)
|
||||
│ ├── validators.py # 验证逻辑(危险操作检测、完整验证流水线)
|
||||
│ └── fewshot_selector.py # Few-Shot 示例选择器(语义/关键词检索)
|
||||
@@ -186,15 +186,19 @@ cp .env .env.local # 或直接编辑 .env
|
||||
DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx
|
||||
DEEPSEEK_BASE_URL=https://api.deepseek.com
|
||||
|
||||
# 可选:使用本地 Embedding(无需网络,但需下载模型)
|
||||
USE_LOCAL_EMBEDDING=true
|
||||
EMBEDDING_MODEL_PATH=./data/models/Qwen3-Embedding-0.6B
|
||||
|
||||
# 或使用远程 Embedding API(无需本地模型)
|
||||
# 推荐:远程 Embedding(OpenAI 兼容网关或 ModelScope 等,无需本地模型目录)
|
||||
USE_LOCAL_EMBEDDING=false
|
||||
MODELSCOPE_API_KEY=ms-xxxxxxxx
|
||||
MODELSCOPE_BASE_URL=https://api-inference.modelscope.cn/v1
|
||||
MODELSCOPE_EMBEDDING_MODEL=Qwen/Qwen3-Embedding-8B
|
||||
OPENAI_BASE_URL=https://api.openai.com/v1
|
||||
OPENAI_API_KEY=sk-xxxxxxxx
|
||||
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
|
||||
|
||||
# 或使用 ModelScope
|
||||
# MODELSCOPE_API_KEY=ms-xxxxxxxx
|
||||
# MODELSCOPE_EMBEDDING_MODEL=Qwen/Qwen3-Embedding-8B
|
||||
|
||||
# 可选:本地 HuggingFace 模型目录(需 USE_LOCAL_EMBEDDING=true + EMBEDDING_MODEL_PATH)
|
||||
# USE_LOCAL_EMBEDDING=true
|
||||
# EMBEDDING_MODEL_PATH=/path/to/local/embedding-model
|
||||
```
|
||||
|
||||
### 3. 准备 Schema 文件
|
||||
@@ -350,15 +354,18 @@ MAX_RETRY=1 # 重试次数(1=仅首次,2=允许一次修正)
|
||||
FEWSHOT_ENABLED=true # 是否启用 Few-Shot
|
||||
FEWSHOT_TOP_K=3 # 每次注入的示例数量
|
||||
FEWSHOT_MIN_RATING=7 # 示例最低评分(1-10)
|
||||
# 推荐:Few-shot 走 Chroma(运行时可不配 FEWSHOT_DATA_PATH;灌库见 scripts/build_fewshot_chroma_index.py)
|
||||
FEWSHOT_USE_CHROMA=true
|
||||
FEWSHOT_CHROMA_PATH=./data/embeddings/chroma_fewshot
|
||||
# FEWSHOT_DATA_PATH=./data/experiences/all_samples.jsonl # 仅构建索引时需要
|
||||
|
||||
# ========== Embedding ==========
|
||||
USE_LOCAL_EMBEDDING=false # true=本地模型,false=远程API
|
||||
# 本地模型路径
|
||||
EMBEDDING_MODEL_PATH=./data/models/Qwen3-Embedding-0.6B
|
||||
# 远程 API(ModelScope)
|
||||
MODELSCOPE_API_KEY=ms-xxxx
|
||||
MODELSCOPE_BASE_URL=https://api-inference.modelscope.cn/v1
|
||||
MODELSCOPE_EMBEDDING_MODEL=Qwen/Qwen3-Embedding-8B
|
||||
USE_LOCAL_EMBEDDING=false # false=远程(默认);true 时需配置 EMBEDDING_MODEL_PATH
|
||||
# OPENAI_* 或 MODELSCOPE_* / DASHSCOPE_*(与代码内优先级一致)
|
||||
OPENAI_BASE_URL=https://api.openai.com/v1
|
||||
OPENAI_API_KEY=sk-xxxx
|
||||
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
|
||||
# EMBEDDING_MODEL_PATH= # 仅 USE_LOCAL_EMBEDDING=true 时填写本地目录
|
||||
|
||||
# ========== Schema ==========
|
||||
SCHEMA_DIR=./data/schemas
|
||||
@@ -710,7 +717,7 @@ LLM 更擅长模仿示例而非理解抽象规则。提供 5-7 个高质量示
|
||||
- 🎉 初始发布
|
||||
- 三 Agent 流水线(Schema Linker / SQL Generator / Validator)
|
||||
- 向量检索 + LLM 精筛表选择
|
||||
- ChromaDB + Qwen3-Embedding 本地索引
|
||||
- ChromaDB + Embedding 向量索引(默认远程 API 编码)
|
||||
- T-SQL / MySQL / PostgreSQL 多方言支持
|
||||
- 双重验证机制(程序 + LLM)
|
||||
- 自修正重试(最多 2 次)
|
||||
|
||||
Binary file not shown.
+85
-6
@@ -32,6 +32,10 @@ from main import setup_environment, load_schema, create_orchestrator, resolve_sq
|
||||
from agents.orchestrator import GenerationResult
|
||||
from nl_lite_store import lite_nl_store
|
||||
from utils.dialog_classifier import DialogIntent, classify_dialog
|
||||
from utils.dialog_context import (
|
||||
last_assistant_was_data_query,
|
||||
messages_to_text2sql_context,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -54,7 +58,12 @@ def get_orchestrator():
|
||||
return orchestrator
|
||||
|
||||
if not setup_environment():
|
||||
raise RuntimeError("环境检查失败,请检查配置")
|
||||
raise RuntimeError(
|
||||
"环境检查失败(请查看上方 WARNING/INFO,常见原因:"
|
||||
"USE_LOCAL_EMBEDDING=true 但未配置或找不到 EMBEDDING_MODEL_PATH;"
|
||||
"或 USE_LOCAL_EMBEDDING=false 但未配好 OPENAI_* / MODELSCOPE_* / DASHSCOPE_*;"
|
||||
"或 Schema 文件路径不对、DEEPSEEK_API_KEY 未设置)"
|
||||
)
|
||||
|
||||
schema_path = os.getenv("SCHEMA_PATH", "./data/schemas/G3SB_MCDataDictionary_table_structure.json")
|
||||
schema_meta_path = os.getenv("SCHEMA_META_PATH", None)
|
||||
@@ -111,6 +120,20 @@ class DataQueryResult(BaseModel):
|
||||
truncated: bool = Field(False, description="是否截断")
|
||||
sql_explain: Optional[str] = Field(None, description="SQL自然语言说明")
|
||||
can_export: Optional[bool] = Field(True, description="是否允许导出")
|
||||
db_execution_status: Optional[int] = Field(
|
||||
None,
|
||||
description="库探针:1=有数据行,0=无行需追问补充,-1=执行失败(重试),None=未探针",
|
||||
)
|
||||
db_empty_feedback: Optional[str] = Field(
|
||||
None, description="探针0时的无行说明与追问(含问题分析)"
|
||||
)
|
||||
follow_up_required: bool = Field(
|
||||
False,
|
||||
description="True 表示探针为0:需用户补充条件后重新提问以重新生成SQL",
|
||||
)
|
||||
sql_delivery_message: Optional[str] = Field(
|
||||
None, description="探针为1时LLM生成的面向用户SQL交付说明"
|
||||
)
|
||||
|
||||
|
||||
class NLChatSuccessData(BaseModel):
|
||||
@@ -185,6 +208,32 @@ def _conversation_nl_dict(reply: str) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
async def _load_session_text2sql_context(
|
||||
request: NLChatRequest,
|
||||
) -> tuple[str, bool]:
|
||||
"""
|
||||
在写入本轮之前读取会话历史,构造 Text2SQL 上文,并判断上一轮助手是否为数据查询。
|
||||
"""
|
||||
sid = (request.session_id or "").strip()
|
||||
if not sid:
|
||||
return "", False
|
||||
data = await lite_nl_store.get_messages(
|
||||
request.user_id,
|
||||
request.visitor_biz_id,
|
||||
sid,
|
||||
limit=200,
|
||||
offset=0,
|
||||
)
|
||||
if not data:
|
||||
return "", False
|
||||
items = data.get("items") or []
|
||||
if not items:
|
||||
return "", False
|
||||
last_data = last_assistant_was_data_query(items)
|
||||
block, _n = messages_to_text2sql_context(items)
|
||||
return block, last_data
|
||||
|
||||
|
||||
async def _append_session_if_needed(request: NLChatRequest, user_text: str, data: Dict[str, Any]) -> None:
|
||||
if not (request.session_id and request.session_id.strip()):
|
||||
return
|
||||
@@ -226,6 +275,10 @@ def _nl_dict_from_generation(result: GenerationResult) -> Dict[str, Any]:
|
||||
dbe = result.metadata.get("db_empty_feedback")
|
||||
if dbe:
|
||||
branch_result["db_empty_feedback"] = dbe
|
||||
branch_result["follow_up_required"] = bool(result.valid and dbs == 0)
|
||||
sdm = result.metadata.get("sql_delivery_message")
|
||||
if sdm:
|
||||
branch_result["sql_delivery_message"] = str(sdm)
|
||||
conf = 1.0 if result.valid else 0.0
|
||||
if result.valid:
|
||||
reason = f"使用了 {len(result.tables_used)} 张表"
|
||||
@@ -247,6 +300,10 @@ def _sql_gen_stream_html(result: GenerationResult) -> str:
|
||||
inner = json.dumps({"sql": sql}, ensure_ascii=False)
|
||||
parts = [f"<data>{inner}</data>"]
|
||||
explain = ""
|
||||
if result.metadata.get("sql_delivery_message"):
|
||||
parts.append(
|
||||
f'<div class="sql-delivery-body">{html_lib.escape(str(result.metadata["sql_delivery_message"]))}</div>'
|
||||
)
|
||||
if result.metadata.get("db_empty_feedback"):
|
||||
explain = str(result.metadata["db_empty_feedback"])
|
||||
elif result.warnings:
|
||||
@@ -258,15 +315,21 @@ def _sql_gen_stream_html(result: GenerationResult) -> str:
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
async def _run_generate(question: str, top_k: int = 20) -> GenerationResult:
|
||||
async def _run_generate(
|
||||
question: str,
|
||||
top_k: int = 20,
|
||||
dialog_context: Optional[str] = None,
|
||||
) -> GenerationResult:
|
||||
orch = get_orchestrator()
|
||||
dialect = resolve_sql_dialect(os.getenv("TEXT2SQL_DIALECT", "sqlserver"))
|
||||
dc = (dialog_context or "").strip() or None
|
||||
|
||||
def _call() -> GenerationResult:
|
||||
return orch.generate(
|
||||
question=question.strip(),
|
||||
dialect=dialect,
|
||||
top_k_candidates=top_k,
|
||||
dialog_context=dc,
|
||||
)
|
||||
|
||||
return await asyncio.to_thread(_call)
|
||||
@@ -277,7 +340,15 @@ async def _chat_stream_events(request: NLChatRequest) -> AsyncIterator[bytes]:
|
||||
yield _sse_data({"code": 400, "msg": "消息内容不能为空", "data": None})
|
||||
return
|
||||
text = request.message.strip()
|
||||
classified = classify_dialog(text)
|
||||
orch = get_orchestrator()
|
||||
dialog_block, last_data = await _load_session_text2sql_context(request)
|
||||
classified = await asyncio.to_thread(
|
||||
classify_dialog,
|
||||
text,
|
||||
last_turn_was_data_query=last_data,
|
||||
dialog_context=dialog_block or None,
|
||||
llm_client=orch.deepseek,
|
||||
)
|
||||
if classified.intent == DialogIntent.CONVERSATION:
|
||||
reply = classified.reply_suggestion or ""
|
||||
logger.info("[API/stream] 对话意图: conversation(跳过 Text2SQL,与 CLI single_query 一致)")
|
||||
@@ -290,7 +361,7 @@ async def _chat_stream_events(request: NLChatRequest) -> AsyncIterator[bytes]:
|
||||
|
||||
yield _sse_data({"stage": "orchestrator", "stream_kind": "content", "content": "DATA_QUERY"})
|
||||
try:
|
||||
result = await _run_generate(text)
|
||||
result = await _run_generate(text, dialog_context=dialog_block or None)
|
||||
except Exception as e:
|
||||
logger.error(f"[API/stream] 生成异常: {e}")
|
||||
yield _sse_data({"code": 500, "msg": str(e), "data": None})
|
||||
@@ -353,7 +424,15 @@ async def nl_chat(request: NLChatRequest):
|
||||
raise HTTPException(status_code=400, detail="消息内容不能为空")
|
||||
text = request.message.strip()
|
||||
logger.info(f"[API] 问题: {text[:100]}...")
|
||||
classified = classify_dialog(text)
|
||||
orch = get_orchestrator()
|
||||
dialog_block, last_data = await _load_session_text2sql_context(request)
|
||||
classified = await asyncio.to_thread(
|
||||
classify_dialog,
|
||||
text,
|
||||
last_turn_was_data_query=last_data,
|
||||
dialog_context=dialog_block or None,
|
||||
llm_client=orch.deepseek,
|
||||
)
|
||||
if classified.intent == DialogIntent.CONVERSATION:
|
||||
reply = classified.reply_suggestion or ""
|
||||
logger.info("[API/chat] 对话意图: conversation(跳过 Text2SQL)")
|
||||
@@ -361,7 +440,7 @@ async def nl_chat(request: NLChatRequest):
|
||||
await _append_session_if_needed(request, text, data_dict)
|
||||
return {"code": 200, "msg": "success", "data": data_dict}
|
||||
|
||||
result = await _run_generate(text)
|
||||
result = await _run_generate(text, dialog_context=dialog_block or None)
|
||||
data_dict = _nl_dict_from_generation(result)
|
||||
response_data = NLChatSuccessData.model_validate(data_dict)
|
||||
msg = "success" if result.valid else "partial"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
# Text-to-SQL Multi-Agent System
|
||||
# 基于 CAMEL AI + DeepSeek + Qwen3-Embedding 的智能SQL生成系统
|
||||
# 基于 CAMEL AI + DeepSeek + 向量 Embedding 的智能 SQL 生成系统
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__author__ = "Backman Team"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
+102
-19
@@ -64,7 +64,7 @@ class Text2SQLOrchestrator:
|
||||
schema_manager: Schema管理器实例
|
||||
deepseek_api_key: DeepSeek API密钥(也可通过环境变量DEEPSEEK_API_KEY)
|
||||
deepseek_config: DeepSeek配置对象(优先于api_key)
|
||||
embedding_model_path: Qwen3-Embedding模型路径
|
||||
embedding_model_path: 本地 Embedding 模型目录(仅 USE_LOCAL_EMBEDDING=true)
|
||||
vector_db_path: 向量数据库路径
|
||||
max_retry: 最大重试次数(包含首次生成)
|
||||
use_vector_search: 是否使用向量检索粗筛
|
||||
@@ -96,12 +96,22 @@ class Text2SQLOrchestrator:
|
||||
|
||||
if self.fewshot_enabled:
|
||||
try:
|
||||
path = fewshot_samples_path or os.getenv(
|
||||
"FEWSHOT_DATA_PATH",
|
||||
"./data/experiences/all_samples.jsonl"
|
||||
use_chroma = os.getenv("FEWSHOT_USE_CHROMA", "false").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
if fewshot_samples_path is not None:
|
||||
path = str(fewshot_samples_path).strip()
|
||||
else:
|
||||
env_p = os.getenv("FEWSHOT_DATA_PATH")
|
||||
if env_p is not None:
|
||||
path = env_p.strip()
|
||||
else:
|
||||
# Chroma 优先时默认不再依赖 JSONL;否则保留原默认路径
|
||||
path = "" if use_chroma else "./data/experiences/all_samples.jsonl"
|
||||
self.fewshot_selector = FewShotSelector(
|
||||
path,
|
||||
path or None,
|
||||
embedding_model_path=self._embedding_model_path,
|
||||
)
|
||||
logger.info(
|
||||
@@ -119,6 +129,23 @@ class Text2SQLOrchestrator:
|
||||
+ (", en→zh=on" if self.translate_english_to_zh else ", en→zh=off")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _merge_dialog_for_model(
|
||||
dialog_context: str, question: str, max_len: int
|
||||
) -> str:
|
||||
"""拼接上文与当前问句,控制总长,优先保留当前问句完整。"""
|
||||
dc = (dialog_context or "").strip()
|
||||
q = (question or "").strip()
|
||||
if not dc:
|
||||
return q
|
||||
tail = "\n\n【当前用户问题】\n" + q
|
||||
if len(dc) + len(tail) <= max_len:
|
||||
return dc + tail
|
||||
room = max_len - len(tail)
|
||||
if room < 80:
|
||||
return tail[-max_len:]
|
||||
return dc[:room].rstrip() + tail
|
||||
|
||||
def _get_vector_index(self) -> SchemaIndexer:
|
||||
"""获取或创建向量索引(懒加载)"""
|
||||
if self._vector_index is None:
|
||||
@@ -291,6 +318,7 @@ class Text2SQLOrchestrator:
|
||||
schema_str: str,
|
||||
dialect: str = "tsql",
|
||||
validation_feedback: Optional[str] = None,
|
||||
dialog_context: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
SQL生成(SQL Generator Agent)
|
||||
@@ -301,17 +329,24 @@ class Text2SQLOrchestrator:
|
||||
dialect: SQL方言
|
||||
validation_feedback: 非空时附加到用户提示(重试时传入上次校验错误)
|
||||
|
||||
dialog_context: 前几轮对话摘要;与 ``question`` 一并供指代消解与续问。
|
||||
|
||||
Returns:
|
||||
SQL语句
|
||||
"""
|
||||
from config.prompts import SQL_GENERATOR_SYSTEM, SQL_GENERATOR_USER
|
||||
from utils.sql_parser import normalize_sql_for_dialect
|
||||
|
||||
dc = (dialog_context or "").strip()
|
||||
fewshot_question = question
|
||||
if dc:
|
||||
fewshot_question = f"{dc}\n\n【当前问】{question}"
|
||||
|
||||
# Few-shot 增强
|
||||
if self.fewshot_enabled and self.fewshot_selector:
|
||||
try:
|
||||
examples = self.fewshot_selector.select(
|
||||
question=question,
|
||||
question=fewshot_question,
|
||||
top_k=self.fewshot_top_k,
|
||||
min_rating=self.fewshot_min_rating
|
||||
)
|
||||
@@ -329,7 +364,15 @@ class Text2SQLOrchestrator:
|
||||
if dialect == "tsql":
|
||||
dialect_label = "Microsoft SQL Server (T-SQL)"
|
||||
|
||||
user_content = SQL_GENERATOR_USER.format(
|
||||
prefix = ""
|
||||
if dc:
|
||||
prefix = (
|
||||
"【对话上文】(用于理解「这/那/同样/上面/刚才」等指代及续问条件;"
|
||||
"请结合下文「当前用户问题」生成 SQL。)\n"
|
||||
f"{dc}\n\n"
|
||||
)
|
||||
|
||||
user_content = prefix + SQL_GENERATOR_USER.format(
|
||||
schema=schema_str,
|
||||
question=question,
|
||||
dialect=dialect_label,
|
||||
@@ -380,6 +423,7 @@ class Text2SQLOrchestrator:
|
||||
schema_str: str,
|
||||
dialect: str = "tsql",
|
||||
question: str = "",
|
||||
dialog_context: Optional[str] = None,
|
||||
) -> Tuple[bool, List[str], List[str], Optional[int], Optional[str]]:
|
||||
"""
|
||||
SQL验证(程序验证 + 库探针 + 按探针分支的 LLM)
|
||||
@@ -389,6 +433,7 @@ class Text2SQLOrchestrator:
|
||||
schema_str: Schema描述
|
||||
dialect: 与生成一致的 SQL 方言(sqlglot 名,默认 tsql)
|
||||
question: 用户自然语言(探针为 0 时用于生成补充说明)
|
||||
dialog_context: 会话上文;探针 0 时与 question 一并传入说明模型
|
||||
|
||||
Returns:
|
||||
(是否通过, 错误列表, 警告列表, 库执行探针状态, 无数据时的用户说明)
|
||||
@@ -433,11 +478,11 @@ class Text2SQLOrchestrator:
|
||||
db_execution_status, db_probe_err = probe_sql_execution_status_ex(sql)
|
||||
if db_execution_status == -1:
|
||||
msg = (
|
||||
"数据库执行验证失败:SQL 在目标库执行报错(探针状态 -1),"
|
||||
"将据此重新生成 SQL。"
|
||||
"【库探针结果:-1 执行失败】SQL 在目标库执行报错,"
|
||||
"系统将依据下列错误**自动重新生成** SQL(请等待重试结果)。"
|
||||
)
|
||||
if db_probe_err:
|
||||
msg += f" 数据库返回:{db_probe_err}"
|
||||
msg += f"\n数据库返回:{db_probe_err}"
|
||||
errors.append(msg)
|
||||
elif db_execution_status is None:
|
||||
warnings.append(
|
||||
@@ -482,23 +527,35 @@ class Text2SQLOrchestrator:
|
||||
# === 阶段2b:探针 0 时生成用户可读补充说明(仍返回 SQL,由 API/CLI 一并展示) ===
|
||||
if db_execution_status == 0 and len(errors) == 0:
|
||||
prefix = (
|
||||
"该 SQL 已在数据库成功执行,但返回的数据行数为 0(未查到匹配记录)。"
|
||||
"请将下方 SQL 与说明一并核对;若不符合预期,请补充或调整条件后再次提问。"
|
||||
"【库探针结果:0 行】该 SQL 已在数据库成功执行,但**返回数据行数为 0**(未查到匹配记录)。"
|
||||
"下方已附带完整 SQL 与原因分析,请一并阅读。"
|
||||
)
|
||||
fb_q = question
|
||||
dc = (dialog_context or "").strip()
|
||||
if dc:
|
||||
fb_q = f"{dc}\n\n【当前用户问题】\n{question}"
|
||||
try:
|
||||
llm_fb = self.deepseek.empty_result_user_feedback(
|
||||
question=question,
|
||||
question=fb_q,
|
||||
sql=sql,
|
||||
schema=schema_str,
|
||||
)
|
||||
empty_feedback = f"{prefix}\n\n【分析与建议】\n{llm_fb}"
|
||||
empty_feedback = f"{prefix}\n\n【问题分析】\n{llm_fb}"
|
||||
except Exception as e:
|
||||
logger.warning(f"无数据说明生成失败: {e}")
|
||||
empty_feedback = (
|
||||
f"{prefix}\n\n【分析与建议】\n"
|
||||
f"{prefix}\n\n【问题分析】\n"
|
||||
"未能自动生成详细分析。请补充时间范围、筛选条件或业务对象后重新提问。"
|
||||
)
|
||||
|
||||
follow = (
|
||||
"\n\n【追问 — 请补充后再次提问以重新生成 SQL】\n"
|
||||
"1. 请根据上述分析,尽量具体地补充或修正:**时间范围**、**业务对象**(账户/合约/代码等)、"
|
||||
"**筛选口径** 或 **您认为 SQL 中不合理的条件**。\n"
|
||||
"2. 补充说明后请**重新发起一次自然语言提问**(无需粘贴 SQL),系统会结合您的新描述**重新生成**查询。"
|
||||
)
|
||||
empty_feedback = (empty_feedback or prefix) + follow
|
||||
|
||||
is_valid = len(errors) == 0
|
||||
return is_valid, errors, warnings, db_execution_status, empty_feedback
|
||||
|
||||
@@ -507,7 +564,8 @@ class Text2SQLOrchestrator:
|
||||
question: str,
|
||||
dialect: str = "tsql",
|
||||
top_k_candidates: int = 20,
|
||||
include_schema_in_result: bool = False
|
||||
include_schema_in_result: bool = False,
|
||||
dialog_context: Optional[str] = None,
|
||||
) -> GenerationResult:
|
||||
"""
|
||||
主生成流程
|
||||
@@ -517,6 +575,7 @@ class Text2SQLOrchestrator:
|
||||
dialect: SQL方言(默认 tsql;与 sqlglot 一致)
|
||||
top_k_candidates: 粗筛候选表数量
|
||||
include_schema_in_result: 结果中是否包含使用的Schema字符串
|
||||
dialog_context: 前几轮对话可读摘要;选表、向量粗筛、SQL 生成与无数据说明会参考
|
||||
|
||||
Returns:
|
||||
GenerationResult对象
|
||||
@@ -543,6 +602,9 @@ class Text2SQLOrchestrator:
|
||||
logger.warning("[GEN] 英译中失败,使用原文: %s", e)
|
||||
|
||||
question = work_question
|
||||
dc_raw = (dialog_context or "").strip()
|
||||
retrieval_question = self._merge_dialog_for_model(dc_raw, question, 4000)
|
||||
linker_question = self._merge_dialog_for_model(dc_raw, question, 6000)
|
||||
logger.info(f"[GEN] 开始生成SQL:{question[:50]}...")
|
||||
|
||||
attempt = 0
|
||||
@@ -558,14 +620,18 @@ class Text2SQLOrchestrator:
|
||||
# === Step 1: Schema筛选(仅首次) ===
|
||||
if attempt == 0:
|
||||
# 1.1 粗筛
|
||||
candidate_tables = self._coarse_filter(question, top_k=top_k_candidates)
|
||||
candidate_tables = self._coarse_filter(
|
||||
retrieval_question, top_k=top_k_candidates
|
||||
)
|
||||
|
||||
# 1.2 LLM精筛
|
||||
relevant_tables, reasoning = self._llm_select_tables(
|
||||
question,
|
||||
linker_question,
|
||||
candidate_tables,
|
||||
)
|
||||
relevant_tables = self._prioritize_broker_tables(question, relevant_tables)
|
||||
relevant_tables = self._prioritize_broker_tables(
|
||||
linker_question, relevant_tables
|
||||
)
|
||||
|
||||
# 1.3 外键扩展
|
||||
expanded_tables = self._expand_relations(relevant_tables)
|
||||
@@ -613,6 +679,7 @@ class Text2SQLOrchestrator:
|
||||
filtered_schema_str,
|
||||
dialect,
|
||||
validation_feedback=feedback,
|
||||
dialog_context=dc_raw or None,
|
||||
)
|
||||
last_sql = sql
|
||||
except Exception as e:
|
||||
@@ -626,6 +693,7 @@ class Text2SQLOrchestrator:
|
||||
filtered_schema_str,
|
||||
dialect=dialect,
|
||||
question=question,
|
||||
dialog_context=dc_raw or None,
|
||||
)
|
||||
if db_probe is not None:
|
||||
last_db_execution_status = db_probe
|
||||
@@ -643,6 +711,19 @@ class Text2SQLOrchestrator:
|
||||
meta["db_execution_status"] = db_probe
|
||||
if empty_feedback:
|
||||
meta["db_empty_feedback"] = empty_feedback
|
||||
if db_probe == 1:
|
||||
try:
|
||||
meta["sql_delivery_message"] = (
|
||||
self.deepseek.sql_probe_success_delivery_message(
|
||||
question=question,
|
||||
sql=sql,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("[GEN] 探针1交付说明生成失败: %s", e)
|
||||
meta["sql_delivery_message"] = None
|
||||
if dc_raw:
|
||||
meta["dialog_context_chars"] = len(dc_raw)
|
||||
|
||||
result = GenerationResult(
|
||||
sql=sql,
|
||||
@@ -663,6 +744,8 @@ class Text2SQLOrchestrator:
|
||||
fail_meta: Dict = dict(translation_meta)
|
||||
if last_db_execution_status is not None:
|
||||
fail_meta["db_execution_status"] = last_db_execution_status
|
||||
if dc_raw:
|
||||
fail_meta["dialog_context_chars"] = len(dc_raw)
|
||||
return GenerationResult(
|
||||
sql=last_sql or "",
|
||||
valid=False,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -283,6 +283,24 @@ EMPTY_RESULT_FEEDBACK_USER = """用户原始问题:
|
||||
|
||||
请直接输出给终端用户阅读的说明文字(纯文本)。"""
|
||||
|
||||
# 库探针为 1(有返回行)时,面向用户的 SQL 交付说明(与下方 SQL 一并展示)
|
||||
SQL_PROBE_SUCCESS_DELIVERY_SYSTEM = """你是证券/期货类业务库的 Text2SQL 助手。
|
||||
用户的自然语言问题已转为 SQL,且在目标库**试执行成功且至少返回一行数据**。
|
||||
|
||||
请用 1~3 句简洁中文向用户说明:
|
||||
- 该 SQL 大致在查询或统计什么(业务语义);
|
||||
- 可提示用户可在下方查看完整 SQL 并自行执行或导出。
|
||||
|
||||
不要编造具体数据值;不要逐列复述;不要输出 Markdown 代码块或 JSON。"""
|
||||
|
||||
SQL_PROBE_SUCCESS_DELIVERY_USER = """用户问题:
|
||||
{question}
|
||||
|
||||
已通过库探针(有数据行)的 SQL:
|
||||
{sql}
|
||||
|
||||
请输出面向终端用户的简短说明(纯文本)。"""
|
||||
|
||||
|
||||
# ========== Few-Shot 示例 ==========
|
||||
FEW_SHOT_EXAMPLES: Dict[str, str] = {
|
||||
@@ -350,3 +368,28 @@ TRANSLATE_NL_TO_ZH_USER = """原句:
|
||||
{question}
|
||||
|
||||
仅输出一句中文:"""
|
||||
|
||||
# ========== 对话意图分类(LLM,与规则分类配合)==========
|
||||
DIALOG_INTENT_CLASSIFIER_SYSTEM = """你是证券/期货类 Text2SQL 产品的「意图分类」模块。
|
||||
|
||||
只输出**一行**严格 JSON(不要 markdown、不要解释),格式:
|
||||
{"intent":"text2sql"|"conversation","reply_zh":"..."}
|
||||
|
||||
字段含义:
|
||||
- intent=text2sql:用户本轮在**提出新的或可执行的数据查询/统计需求**(含对上一轮的**具体补充条件**,如「再加上经纪商维度」「改成按日」),需要走 SQL 生成。
|
||||
- intent=conversation:用户在做**寒暄致谢**、**元问题**(你是谁)、**对结果的情绪反馈但缺少可执行信息**(如「不对呀」「结果错了」「重新算」却未说清要改什么)、**纯抱怨或否定而无新条件**——此时不应生成 SQL;reply_zh 用简短中文引导用户**具体说明**要查什么或错在哪里。
|
||||
- reply_zh:当 intent=conversation 时必填,为直接展示给用户的友好中文(1~4 句);intent=text2sql 时填空字符串 ""。
|
||||
|
||||
注意:若「上一轮助手刚返回过数据/SQL」而用户只说结果不对、未给出新的筛选/维度/时间,判为 conversation。"""
|
||||
|
||||
DIALOG_INTENT_CLASSIFIER_USER = """上一轮助手是否为「数据查询/SQL 结果」:{last_turn_label}
|
||||
|
||||
可选会话摘要(可能为空):
|
||||
---
|
||||
{context_snip}
|
||||
---
|
||||
|
||||
用户本轮输入:
|
||||
{user_message}
|
||||
|
||||
只输出 JSON:"""
|
||||
|
||||
@@ -17,7 +17,7 @@ class Settings(BaseSettings):
|
||||
max_tokens: int = 4096
|
||||
|
||||
# Embedding配置
|
||||
embedding_model_path: str = "./data/models/Qwen3-Embedding-0.6B"
|
||||
embedding_model_path: str = "" # 仅本地 Embedding 时使用;默认走远程 API
|
||||
vector_dim: int = 2048
|
||||
use_local_embedding: bool = True
|
||||
|
||||
|
||||
Binary file not shown.
@@ -253,6 +253,43 @@ class DeepSeekClient:
|
||||
text = (msg.content or "").strip()
|
||||
return text
|
||||
|
||||
def sql_probe_success_delivery_message(
|
||||
self,
|
||||
question: str,
|
||||
sql: str,
|
||||
*,
|
||||
max_sql_chars: int = 4000,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""
|
||||
库探针为 1(执行成功且至少一行数据)时,生成面向用户的简短交付说明。
|
||||
"""
|
||||
from config.prompts import (
|
||||
SQL_PROBE_SUCCESS_DELIVERY_SYSTEM,
|
||||
SQL_PROBE_SUCCESS_DELIVERY_USER,
|
||||
)
|
||||
|
||||
q = (question or "").strip() or "(无)"
|
||||
s = (sql or "").strip()
|
||||
if len(s) > max_sql_chars:
|
||||
s = s[: max_sql_chars - 20].rstrip() + "\n-- …(已截断)"
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": SQL_PROBE_SUCCESS_DELIVERY_SYSTEM},
|
||||
{
|
||||
"role": "user",
|
||||
"content": SQL_PROBE_SUCCESS_DELIVERY_USER.format(
|
||||
question=q,
|
||||
sql=s,
|
||||
),
|
||||
},
|
||||
]
|
||||
kwargs.setdefault("temperature", 0.2)
|
||||
kwargs.setdefault("top_p", 1.0)
|
||||
kwargs.setdefault("max_tokens", 320)
|
||||
msg = self.chat(messages, **kwargs)
|
||||
return (msg.content or "").strip()
|
||||
|
||||
def select_tables(
|
||||
self,
|
||||
question: str,
|
||||
|
||||
+16
-15
@@ -27,9 +27,6 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_EMBEDDING_PATH = "./data/models/Qwen3-Embedding-0.6B"
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
"""仓库根目录(含 data/、.env、api_server.py 的目录)。"""
|
||||
return Path(__file__).resolve().parent.parent
|
||||
@@ -41,7 +38,8 @@ def _load_project_env():
|
||||
|
||||
|
||||
def _embedding_model_path() -> str:
|
||||
return os.getenv("EMBEDDING_MODEL_PATH", _DEFAULT_EMBEDDING_PATH).strip()
|
||||
"""仅 ``USE_LOCAL_EMBEDDING=true`` 时需要;远程 Embedding 可为空。"""
|
||||
return os.getenv("EMBEDDING_MODEL_PATH", "").strip()
|
||||
|
||||
|
||||
def resolve_sql_dialect(name: str) -> str:
|
||||
@@ -55,20 +53,23 @@ def resolve_sql_dialect(name: str) -> str:
|
||||
def setup_environment():
|
||||
"""环境检查"""
|
||||
_load_project_env()
|
||||
use_local_emb = os.getenv("USE_LOCAL_EMBEDDING", "true").strip().lower() in (
|
||||
use_local_emb = os.getenv("USE_LOCAL_EMBEDDING", "false").strip().lower() in (
|
||||
"1", "true", "yes", "on",
|
||||
)
|
||||
if use_local_emb:
|
||||
# 与 .env 中 EMBEDDING_MODEL_PATH 及 utils.embedding 一致
|
||||
model_path = Path(_embedding_model_path())
|
||||
mp_str = _embedding_model_path()
|
||||
if not mp_str:
|
||||
logger.warning(
|
||||
"USE_LOCAL_EMBEDDING=true 但未设置 EMBEDDING_MODEL_PATH(本地模型目录)"
|
||||
)
|
||||
return False
|
||||
model_path = Path(mp_str)
|
||||
if not model_path.exists():
|
||||
logger.warning(f"Embedding模型不存在: {model_path}")
|
||||
logger.info("请先下载模型:")
|
||||
logger.info(" modelscope download --model 'Qwen/Qwen3-Embedding-0.6B' "
|
||||
f"--local_dir '{model_path}'")
|
||||
logger.info("或使用远程 Embedding API:USE_LOCAL_EMBEDDING=false,并配置 "
|
||||
"MODELSCOPE_API_KEY、或 OPENAI_API_KEY+OPENAI_EMBEDDING_MODEL"
|
||||
"(及可选 OPENAI_BASE_URL)、或 DASHSCOPE_*(百炼)")
|
||||
logger.warning("本地 Embedding 目录不存在: %s", model_path)
|
||||
logger.info(
|
||||
"请设置正确的 EMBEDDING_MODEL_PATH,或改用 USE_LOCAL_EMBEDDING=false,"
|
||||
"并配置 OPENAI_* / MODELSCOPE_* / DASHSCOPE_* 远程 Embedding"
|
||||
)
|
||||
return False
|
||||
else:
|
||||
ms_key = os.getenv("MODELSCOPE_API_KEY", "").strip()
|
||||
@@ -206,7 +207,7 @@ def single_query(orchestrator, question: str, dialect: str = "tsql"):
|
||||
|
||||
logger.info(f"[Q] 问题: {question}")
|
||||
|
||||
classified = classify_dialog(question)
|
||||
classified = classify_dialog(question, llm_client=orchestrator.deepseek)
|
||||
if classified.intent == DialogIntent.CONVERSATION:
|
||||
reply = classified.reply_suggestion or ""
|
||||
logger.info("[Q] 意图: conversation(跳过 SQL 生成)")
|
||||
|
||||
Binary file not shown.
@@ -40,6 +40,7 @@ class SchemaIndexer:
|
||||
self.embedder = embedder
|
||||
self.persist_dir = Path(persist_dir)
|
||||
self.persist_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.collection_name = collection_name
|
||||
|
||||
# 初始化ChromaDB客户端
|
||||
self.client = chromadb.PersistentClient(
|
||||
@@ -49,11 +50,11 @@ class SchemaIndexer:
|
||||
|
||||
# 获取或创建集合
|
||||
self.collection = self.client.get_or_create_collection(
|
||||
name=collection_name,
|
||||
name=self.collection_name,
|
||||
metadata={"hnsw:space": "cosine"}, # 使用余弦相似度
|
||||
)
|
||||
|
||||
logger.info(f"[OK] 初始化SchemaIndexer: collection={collection_name}")
|
||||
logger.info(f"[OK] 初始化SchemaIndexer: collection={self.collection_name}")
|
||||
|
||||
def build_index(
|
||||
self,
|
||||
@@ -80,7 +81,12 @@ class SchemaIndexer:
|
||||
|
||||
if force_rebuild and existing_ids:
|
||||
logger.info(f"强制重建索引,删除{len(existing_ids)}条旧记录")
|
||||
self.collection.delete()
|
||||
# Chroma 新版本要求 delete 必须带 ids/where;整库清空用删集合再建
|
||||
self.client.delete_collection(self.collection_name)
|
||||
self.collection = self.client.get_or_create_collection(
|
||||
name=self.collection_name,
|
||||
metadata={"hnsw:space": "cosine"},
|
||||
)
|
||||
|
||||
# 准备数据
|
||||
table_texts = []
|
||||
@@ -97,7 +103,9 @@ class SchemaIndexer:
|
||||
|
||||
# 批量计算embedding
|
||||
logger.info(f"计算{len(table_texts)}张表的embedding...")
|
||||
embeddings = self.embedder.encode(table_texts, batch_size=batch_size)
|
||||
embeddings = self.embedder.encode(
|
||||
table_texts, batch_size=batch_size, normalize=True
|
||||
)
|
||||
|
||||
# 存入ChromaDB
|
||||
self.collection.add(
|
||||
@@ -136,8 +144,8 @@ class SchemaIndexer:
|
||||
...
|
||||
]
|
||||
"""
|
||||
# 编码查询文本
|
||||
query_embedding = self.embedder.encode([query])
|
||||
# 编码查询文本(与建库时一致:L2 归一化 + 余弦空间)
|
||||
query_embedding = self.embedder.encode([query], normalize=True)
|
||||
|
||||
# 执行检索
|
||||
results = self.collection.query(
|
||||
@@ -205,7 +213,12 @@ class SchemaIndexer:
|
||||
|
||||
def clear(self):
|
||||
"""清空索引"""
|
||||
self.collection.delete()
|
||||
if self.collection.count() > 0:
|
||||
self.client.delete_collection(self.collection_name)
|
||||
self.collection = self.client.get_or_create_collection(
|
||||
name=self.collection_name,
|
||||
metadata={"hnsw:space": "cosine"},
|
||||
)
|
||||
logger.info("索引已清空")
|
||||
|
||||
def count(self) -> int:
|
||||
@@ -218,8 +231,18 @@ class SchemaIndexer:
|
||||
"""获取索引统计信息"""
|
||||
count = self.collection.count()
|
||||
result = self.collection.get(include=["metadatas"])
|
||||
metas = result.get("metadatas") or []
|
||||
|
||||
total_columns = sum(m.get("column_count", 0) for m in result["metadatas"])
|
||||
def _col_count(m: Optional[Dict]) -> int:
|
||||
if not m:
|
||||
return 0
|
||||
v = m.get("column_count", 0)
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
total_columns = sum(_col_count(m) for m in metas)
|
||||
|
||||
return {
|
||||
"indexed_tables": count,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,17 +1,27 @@
|
||||
"""
|
||||
用户输入意图分类:区分「自然语言查数 / Text2SQL」与「寒暄、致谢、元问题」等不适合直接生成 SQL 的对话。
|
||||
|
||||
支持环境变量 ``DIALOG_INTENT_CLASSIFIER``:
|
||||
- ``rules``:仅用关键词与短语规则(无 LLM 调用)。
|
||||
- ``hybrid``(默认):明显查数词/寒暄/元问题走规则;其余交 LLM 判断(需调用方传入 ``llm_client``)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import unicodedata
|
||||
from enum import Enum
|
||||
from typing import NamedTuple, Optional
|
||||
from typing import TYPE_CHECKING, NamedTuple, Optional
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from llm.deepseek_client import DeepSeekClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_INTENT_CLASSIFIER_ENV = "DIALOG_INTENT_CLASSIFIER"
|
||||
|
||||
|
||||
class DialogIntent(str, Enum):
|
||||
TEXT2SQL = "text2sql"
|
||||
@@ -100,12 +110,24 @@ def _strip_trailing_punct(t: str) -> str:
|
||||
return re.sub(r"[!!。.??,,;;:~~…、]+$", "", t).strip()
|
||||
|
||||
|
||||
def classify_dialog(user_text: str) -> DialogClassifyResult:
|
||||
"""
|
||||
对用户一轮输入做粗分类。
|
||||
def _intent_classifier_mode() -> str:
|
||||
m = (os.getenv(_INTENT_CLASSIFIER_ENV) or "hybrid").strip().lower()
|
||||
if m not in ("rules", "hybrid"):
|
||||
logger.warning(
|
||||
"[dialog] unknown DIALOG_INTENT_CLASSIFIER=%r, use hybrid", m
|
||||
)
|
||||
return "hybrid"
|
||||
return m
|
||||
|
||||
策略:优先用「查询/业务」关键词锁定 TEXT2SQL;否则对短寒暄、致谢、元问题判为 CONVERSATION;
|
||||
其余默认 TEXT2SQL,避免漏判真实查询。
|
||||
|
||||
def _classify_dialog_rules(
|
||||
user_text: str,
|
||||
*,
|
||||
last_turn_was_data_query: bool = False,
|
||||
) -> DialogClassifyResult:
|
||||
"""
|
||||
规则分类(与历史行为一致):优先查数关键词;寒暄/元问题为 conversation;
|
||||
若上一轮为数据查询且非寒暄/元问题,则倾向 text2sql。
|
||||
"""
|
||||
t = _normalize(user_text)
|
||||
if not t:
|
||||
@@ -131,5 +153,135 @@ def classify_dialog(user_text: str) -> DialogClassifyResult:
|
||||
reply_suggestion=DEFAULT_CONVERSATION_REPLY,
|
||||
)
|
||||
|
||||
if last_turn_was_data_query:
|
||||
logger.debug("[dialog] intent=text2sql (follow-up after data query)")
|
||||
return DialogClassifyResult(DialogIntent.TEXT2SQL, None)
|
||||
|
||||
logger.debug("[dialog] intent=text2sql (default)")
|
||||
return DialogClassifyResult(DialogIntent.TEXT2SQL, None)
|
||||
|
||||
|
||||
def _classify_dialog_llm(
|
||||
client: DeepSeekClient,
|
||||
user_text: str,
|
||||
*,
|
||||
last_turn_was_data_query: bool,
|
||||
dialog_context: Optional[str],
|
||||
) -> DialogClassifyResult:
|
||||
from config.prompts import (
|
||||
DIALOG_INTENT_CLASSIFIER_SYSTEM,
|
||||
DIALOG_INTENT_CLASSIFIER_USER,
|
||||
)
|
||||
|
||||
last_label = "是" if last_turn_was_data_query else "否"
|
||||
ctx = (dialog_context or "").strip()
|
||||
if len(ctx) > 2400:
|
||||
ctx = ctx[:2400].rstrip() + "\n…(已截断)"
|
||||
if not ctx:
|
||||
ctx = "(无)"
|
||||
|
||||
raw = client.chat_with_json(
|
||||
[
|
||||
{"role": "system", "content": DIALOG_INTENT_CLASSIFIER_SYSTEM},
|
||||
{
|
||||
"role": "user",
|
||||
"content": DIALOG_INTENT_CLASSIFIER_USER.format(
|
||||
last_turn_label=last_label,
|
||||
context_snip=ctx,
|
||||
user_message=_normalize(user_text),
|
||||
),
|
||||
},
|
||||
],
|
||||
temperature=0.0,
|
||||
max_tokens=256,
|
||||
top_p=1.0,
|
||||
)
|
||||
if raw.get("_json_decode_failed"):
|
||||
raise ValueError("intent JSON decode failed")
|
||||
|
||||
intent_s = (raw.get("intent") or "").strip().lower()
|
||||
reply = (raw.get("reply_zh") or "").strip()
|
||||
|
||||
if intent_s == "conversation":
|
||||
if not reply:
|
||||
reply = (
|
||||
"若上一版 SQL 或结果不符合预期,请具体说明:希望增加/修改哪些条件、"
|
||||
"时间范围或统计维度,以便重新生成。"
|
||||
)
|
||||
logger.info("[dialog] intent=conversation (LLM)")
|
||||
return DialogClassifyResult(DialogIntent.CONVERSATION, reply_suggestion=reply)
|
||||
|
||||
if intent_s == "text2sql":
|
||||
logger.info("[dialog] intent=text2sql (LLM)")
|
||||
return DialogClassifyResult(DialogIntent.TEXT2SQL, None)
|
||||
|
||||
raise ValueError(f"unexpected intent field: {intent_s!r}")
|
||||
|
||||
|
||||
def classify_dialog(
|
||||
user_text: str,
|
||||
*,
|
||||
last_turn_was_data_query: bool = False,
|
||||
dialog_context: Optional[str] = None,
|
||||
llm_client: Optional[DeepSeekClient] = None,
|
||||
) -> DialogClassifyResult:
|
||||
"""
|
||||
对用户一轮输入做分类。
|
||||
|
||||
``DIALOG_INTENT_CLASSIFIER``:
|
||||
- ``rules``:仅规则。
|
||||
- ``hybrid``:规则快速命中查数词/寒暄/元问题后返回;否则在有 ``llm_client`` 时用 LLM,
|
||||
失败或无客户端时回退规则。
|
||||
|
||||
Args:
|
||||
user_text: 用户输入。
|
||||
last_turn_was_data_query: 上一轮助手是否为数据查询(供规则与 LLM 参考)。
|
||||
dialog_context: 会话摘要,供 LLM 参考(可选)。
|
||||
llm_client: DeepSeek 客户端;hybrid 下 LLM 分支需要。
|
||||
"""
|
||||
mode = _intent_classifier_mode()
|
||||
|
||||
if mode == "rules":
|
||||
return _classify_dialog_rules(
|
||||
user_text, last_turn_was_data_query=last_turn_was_data_query
|
||||
)
|
||||
|
||||
# hybrid
|
||||
t = _normalize(user_text)
|
||||
if not t:
|
||||
return DialogClassifyResult(
|
||||
DialogIntent.CONVERSATION, reply_suggestion=_EMPTY_INPUT_REPLY
|
||||
)
|
||||
|
||||
if _SQL_OR_QUERY_HINT_RE.search(t):
|
||||
logger.debug("[dialog] intent=text2sql (query/business hint, hybrid fast)")
|
||||
return DialogClassifyResult(DialogIntent.TEXT2SQL, None)
|
||||
|
||||
core = _strip_trailing_punct(t)
|
||||
if core.casefold() in _CHITCHAT_KEYS:
|
||||
logger.debug("[dialog] intent=conversation (chitchat phrase, hybrid fast)")
|
||||
return DialogClassifyResult(
|
||||
DialogIntent.CONVERSATION, reply_suggestion=DEFAULT_CONVERSATION_REPLY
|
||||
)
|
||||
|
||||
if _META_QUESTION_RE.search(t):
|
||||
logger.debug("[dialog] intent=conversation (meta question, hybrid fast)")
|
||||
return DialogClassifyResult(
|
||||
DialogIntent.CONVERSATION,
|
||||
reply_suggestion=DEFAULT_CONVERSATION_REPLY,
|
||||
)
|
||||
|
||||
if llm_client is not None:
|
||||
try:
|
||||
return _classify_dialog_llm(
|
||||
llm_client,
|
||||
user_text,
|
||||
last_turn_was_data_query=last_turn_was_data_query,
|
||||
dialog_context=dialog_context,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("[dialog] LLM intent failed, fallback rules: %s", e)
|
||||
|
||||
return _classify_dialog_rules(
|
||||
user_text, last_turn_was_data_query=last_turn_was_data_query
|
||||
)
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
从 Lite NL 会话消息构造 Text2SQL 可用的上文摘要,并判断上一轮是否为数据查询(用于续问意图分类)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MAX_ASSISTANT_SQL_CHARS = 1400
|
||||
_MAX_ASSISTANT_TEXT_CHARS = 900
|
||||
_MAX_BLOCK_CHARS = 7500
|
||||
|
||||
|
||||
def _truncate(s: str, max_len: int) -> str:
|
||||
s = (s or "").strip()
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
return s[: max_len - 1].rstrip() + "…"
|
||||
|
||||
|
||||
def summarize_assistant_nl_payload(content: str) -> str:
|
||||
"""将落库的 assistant JSON 转为一小段可读摘要。"""
|
||||
raw = (content or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
try:
|
||||
data: Dict[str, Any] = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return _truncate(raw, _MAX_ASSISTANT_TEXT_CHARS)
|
||||
|
||||
br = data.get("branch_result") or {}
|
||||
if isinstance(br.get("answer"), str) and br["answer"].strip():
|
||||
return "[助手] " + _truncate(br["answer"].strip(), _MAX_ASSISTANT_TEXT_CHARS)
|
||||
|
||||
sql = (br.get("sql") or "").strip() if isinstance(br.get("sql"), str) else ""
|
||||
if sql:
|
||||
parts = ["[上轮 SQL] " + _truncate(sql, _MAX_ASSISTANT_SQL_CHARS)]
|
||||
if br.get("follow_up_required"):
|
||||
parts.append("[状态] 上轮为库探针0行,需补充条件后重问")
|
||||
for key in ("db_empty_feedback", "sql_explain"):
|
||||
v = br.get(key)
|
||||
if isinstance(v, str) and v.strip():
|
||||
parts.append("[说明] " + _truncate(v.strip(), 500))
|
||||
break
|
||||
return "\n".join(parts)
|
||||
|
||||
intent = (data.get("intent") or {}).get("intent")
|
||||
return _truncate(f"[助手] intent={intent}", _MAX_ASSISTANT_TEXT_CHARS)
|
||||
|
||||
|
||||
def last_assistant_was_data_query(items: List[Dict[str, Any]]) -> bool:
|
||||
"""最后一条 assistant 消息是否为数据查询分支(含 SQL 或 DATA_QUERY intent)。"""
|
||||
for m in reversed(items or []):
|
||||
if m.get("role") != "assistant":
|
||||
continue
|
||||
raw = (m.get("content") or "").strip()
|
||||
if not raw:
|
||||
return False
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return False
|
||||
intent = (data.get("intent") or {}).get("intent")
|
||||
if intent == "DATA_QUERY":
|
||||
return True
|
||||
br = data.get("branch_result") or {}
|
||||
sql = (br.get("sql") or "").strip() if isinstance(br.get("sql"), str) else ""
|
||||
return bool(sql)
|
||||
return False
|
||||
|
||||
|
||||
def messages_to_text2sql_context(
|
||||
items: List[Dict[str, Any]],
|
||||
*,
|
||||
max_chars: int = _MAX_BLOCK_CHARS,
|
||||
max_pairs: int = 8,
|
||||
) -> Tuple[str, int]:
|
||||
"""
|
||||
将会话消息列表转为供模型阅读的「上文」文本(不含本轮用户输入)。
|
||||
|
||||
Returns:
|
||||
(context_text, num_user_turns_included)
|
||||
"""
|
||||
if not items:
|
||||
return "", 0
|
||||
|
||||
pairs: List[Tuple[str, str]] = []
|
||||
i = 0
|
||||
n = len(items)
|
||||
while i < n:
|
||||
u = items[i]
|
||||
if u.get("role") != "user":
|
||||
i += 1
|
||||
continue
|
||||
user_text = (u.get("content") or "").strip()
|
||||
asst_text = ""
|
||||
if i + 1 < n and items[i + 1].get("role") == "assistant":
|
||||
asst_text = summarize_assistant_nl_payload(str(items[i + 1].get("content") or ""))
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
if user_text or asst_text:
|
||||
pairs.append((user_text, asst_text))
|
||||
|
||||
if not pairs:
|
||||
return "", 0
|
||||
|
||||
pairs = pairs[-max_pairs:]
|
||||
lines: List[str] = []
|
||||
total = 0
|
||||
user_count = 0
|
||||
for idx, (uq, aq) in enumerate(pairs, start=1):
|
||||
chunk_parts = [f"--- 第{idx}轮 ---"]
|
||||
if uq:
|
||||
chunk_parts.append(f"用户:{uq}")
|
||||
if aq:
|
||||
chunk_parts.append(f"{aq}")
|
||||
chunk = "\n".join(chunk_parts)
|
||||
if total + len(chunk) + 2 > max_chars:
|
||||
break
|
||||
lines.append(chunk)
|
||||
total += len(chunk) + 2
|
||||
if uq:
|
||||
user_count += 1
|
||||
|
||||
return "\n\n".join(lines).strip(), user_count
|
||||
+19
-22
@@ -1,6 +1,6 @@
|
||||
"""
|
||||
Embedding 封装:本地 Qwen3-Embedding,或兼容 OpenAI /v1/embeddings 的远程 API
|
||||
(ModelScope 推理、阿里云 DashScope 等)。
|
||||
Embedding 封装:兼容 OpenAI /v1/embeddings 的远程 API(默认),
|
||||
或可选本地 HuggingFace 目录(USE_LOCAL_EMBEDDING=true + EMBEDDING_MODEL_PATH)。
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -112,10 +112,10 @@ def _remote_embedding_from_env() -> _RemoteEmbeddingEnv:
|
||||
|
||||
class Qwen3Embedding:
|
||||
"""
|
||||
Qwen3-Embedding-0.6B 向量化封装
|
||||
本地 HuggingFace 格式 Embedding 模型(Mean Pooling + L2,用于向量检索)。
|
||||
|
||||
使用 Mean Pooling 将token embeddings聚合为句子向量,
|
||||
并进行L2归一化以支持余弦相似度计算。
|
||||
仅在 ``USE_LOCAL_EMBEDDING=true`` 时使用;路径由 ``model_path`` 或环境变量
|
||||
``EMBEDDING_MODEL_PATH`` 指定,**不再内置默认目录**。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -128,7 +128,7 @@ class Qwen3Embedding:
|
||||
初始化 embedding 模型
|
||||
|
||||
Args:
|
||||
model_path: 本地模型路径,若为None则从环境变量或默认路径加载
|
||||
model_path: 本地模型目录;None 或空字符串时读 ``EMBEDDING_MODEL_PATH``
|
||||
device: 推理设备('cpu', 'cuda', 'cuda:0'等),None则自动选择
|
||||
use_fp16: 是否使用FP16混合精度(GPU可用时建议开启,速度更快)
|
||||
"""
|
||||
@@ -138,22 +138,19 @@ class Qwen3Embedding:
|
||||
"pip install transformers torch sentencepiece accelerate"
|
||||
)
|
||||
|
||||
# 确定模型路径
|
||||
if model_path is None:
|
||||
model_path = os.getenv(
|
||||
"EMBEDDING_MODEL_PATH",
|
||||
"./data/models/Qwen3-Embedding-0.6B"
|
||||
resolved = (model_path or "").strip() or os.getenv("EMBEDDING_MODEL_PATH", "").strip()
|
||||
if not resolved:
|
||||
raise ValueError(
|
||||
"已启用本地 Embedding(USE_LOCAL_EMBEDDING=true),但未设置有效模型路径。"
|
||||
"请在 .env 中设置 EMBEDDING_MODEL_PATH 指向本地模型目录,"
|
||||
"或设置 USE_LOCAL_EMBEDDING=false 使用 OPENAI_* / MODELSCOPE_* / DASHSCOPE_* 远程接口。"
|
||||
)
|
||||
|
||||
model_path = Path(model_path)
|
||||
model_path = Path(resolved)
|
||||
if not model_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"模型目录不存在:{model_path}\n"
|
||||
"请先下载模型:\n"
|
||||
" modelscope download --model 'Qwen/Qwen3-Embedding-0.6B' "
|
||||
f"--local_dir '{model_path}'\n"
|
||||
"或从Hugging Face下载:git lfs install && git clone "
|
||||
f"https://huggingface.co/Qwen/Qwen3-Embedding-0.6B {model_path}"
|
||||
f"本地 Embedding 模型目录不存在:{model_path}\n"
|
||||
"请修正 EMBEDDING_MODEL_PATH,或改用 USE_LOCAL_EMBEDDING=false。"
|
||||
)
|
||||
|
||||
# 确定设备
|
||||
@@ -161,7 +158,7 @@ class Qwen3Embedding:
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
self.device = device
|
||||
logger.info(f"加载Qwen3-Embedding模型:{model_path},设备:{device}")
|
||||
logger.info("加载本地 Embedding 模型:%s,设备:%s", model_path, device)
|
||||
|
||||
# 加载 tokenizer:fast(Rust) 解析 tokenizer.json 需较新 tokenizers;
|
||||
# 旧版本会报 ModelWrapper / untagged enum,回退到慢速 tokenizer 可恢复。
|
||||
@@ -499,13 +496,13 @@ def get_embedder(
|
||||
force_reload: bool = False,
|
||||
) -> Any:
|
||||
"""
|
||||
获取 Embedding 单例:USE_LOCAL_EMBEDDING=true 时用本地 Qwen3,否则用远程
|
||||
OpenAI 兼容 API(优先级见 OpenAICompatibleRemoteEmbedding)。
|
||||
获取 Embedding 单例:默认 ``USE_LOCAL_EMBEDDING=false``,使用远程
|
||||
OpenAI 兼容 / ModelScope / DashScope;为 true 时用本地目录(EMBEDDING_MODEL_PATH)。
|
||||
"""
|
||||
global _embedding_instance
|
||||
|
||||
if force_reload or _embedding_instance is None:
|
||||
if _env_flag("USE_LOCAL_EMBEDDING", "true"):
|
||||
if _env_flag("USE_LOCAL_EMBEDDING", "false"):
|
||||
_embedding_instance = Qwen3Embedding(
|
||||
model_path=model_path,
|
||||
device=device,
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
Few-shot 经验样本的 Chroma 向量库存储与检索。
|
||||
|
||||
与 SchemaIndexer 一致:使用项目统一 ``get_embedder()``,持久化目录默认
|
||||
``./data/embeddings/chroma_fewshot``,集合名 ``fewshot_samples``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import chromadb
|
||||
from chromadb.config import Settings as ChromaSettings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_FEWSHOT_CHROMA_DIR = "./data/embeddings/chroma_fewshot"
|
||||
COLLECTION_NAME = "fewshot_samples"
|
||||
# Chroma metadata 单值不宜过大,SQL/说明超长时截断
|
||||
_MAX_SQL_META = 16000
|
||||
_MAX_EXPLAIN_META = 6000
|
||||
_MAX_QEN_META = 2000
|
||||
|
||||
|
||||
class FewShotChromaStore:
|
||||
"""Few-shot JSONL → Chroma 写入与按向量检索。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embedder: Any,
|
||||
persist_dir: Optional[str] = None,
|
||||
collection_name: Optional[str] = None,
|
||||
):
|
||||
self.embedder = embedder
|
||||
# Chroma 的 collection 名;显式参数优先,否则读 FEWSHOT_CHROMA_COLLECTION,再回退默认
|
||||
explicit = (collection_name or "").strip()
|
||||
from_env = (os.getenv("FEWSHOT_CHROMA_COLLECTION") or "").strip()
|
||||
self.collection_name = explicit or from_env or COLLECTION_NAME
|
||||
self.persist_dir = Path(
|
||||
(persist_dir or os.getenv("FEWSHOT_CHROMA_PATH") or DEFAULT_FEWSHOT_CHROMA_DIR).strip()
|
||||
)
|
||||
self.persist_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.client = chromadb.PersistentClient(
|
||||
path=str(self.persist_dir),
|
||||
settings=ChromaSettings(anonymized_telemetry=False),
|
||||
)
|
||||
self.collection = self.client.get_or_create_collection(
|
||||
name=self.collection_name,
|
||||
metadata={"hnsw:space": "cosine"},
|
||||
)
|
||||
logger.info(
|
||||
"[OK] FewShotChromaStore: path=%s collection=%s count=%s",
|
||||
self.persist_dir,
|
||||
self.collection_name,
|
||||
self.collection.count(),
|
||||
)
|
||||
|
||||
def count(self) -> int:
|
||||
return int(self.collection.count())
|
||||
|
||||
def clear(self) -> None:
|
||||
"""删除集合内全部文档(用于 force rebuild)。"""
|
||||
if self.collection.count() > 0:
|
||||
self.client.delete_collection(self.collection_name)
|
||||
self.collection = self.client.get_or_create_collection(
|
||||
name=self.collection_name,
|
||||
metadata={"hnsw:space": "cosine"},
|
||||
)
|
||||
logger.info("[OK] Few-shot Chroma 集合已清空并重建")
|
||||
|
||||
def build_from_samples(
|
||||
self,
|
||||
samples: List["ExperienceSample"],
|
||||
*,
|
||||
force_rebuild: bool = False,
|
||||
batch_size: int = 32,
|
||||
) -> int:
|
||||
"""
|
||||
将已解析的样本列表写入 Chroma(向量由 question_zh 编码)。
|
||||
|
||||
Returns:
|
||||
写入条数
|
||||
"""
|
||||
if not samples:
|
||||
logger.warning("Few-shot Chroma: 无样本,跳过构建")
|
||||
return 0
|
||||
|
||||
if force_rebuild and self.count() > 0:
|
||||
self.clear()
|
||||
|
||||
if not force_rebuild and self.count() > 0:
|
||||
logger.info("Few-shot Chroma 已有 %s 条,跳过构建(加 --force 可重建)", self.count())
|
||||
return self.count()
|
||||
|
||||
texts = [(s.question_zh or "").strip() or " " for s in samples]
|
||||
# Chroma 要求 ids 为唯一字符串
|
||||
ids = [str(s.qid) for s in samples]
|
||||
metadatas: List[Dict[str, Any]] = []
|
||||
for s in samples:
|
||||
metadatas.append(
|
||||
{
|
||||
"qid": str(s.qid),
|
||||
"question_en": ((s.question_en or "")[:_MAX_QEN_META]),
|
||||
"sql": (s.sql or "")[:_MAX_SQL_META],
|
||||
"explanation": (s.explanation or "")[:_MAX_EXPLAIN_META],
|
||||
"rating": int(s.rating) if s.rating is not None else -1,
|
||||
"difficulty": (s.difficulty or "medium")[:32],
|
||||
"tags_json": json.dumps(s.tags or [], ensure_ascii=False)[:4000],
|
||||
}
|
||||
)
|
||||
|
||||
logger.info("Few-shot Chroma: 计算 %s 条 embedding...", len(texts))
|
||||
embeddings = self.embedder.encode(
|
||||
texts,
|
||||
batch_size=min(batch_size, len(texts)),
|
||||
normalize=True,
|
||||
show_progress=True,
|
||||
)
|
||||
|
||||
self.collection.add(
|
||||
embeddings=embeddings.tolist(),
|
||||
documents=texts,
|
||||
metadatas=metadatas,
|
||||
ids=ids,
|
||||
)
|
||||
logger.info("[OK] Few-shot Chroma 索引完成: %s 条", len(ids))
|
||||
return len(ids)
|
||||
|
||||
def search_raw(
|
||||
self,
|
||||
query: str,
|
||||
top_k: int = 20,
|
||||
) -> List[Tuple[float, Dict[str, Any], str]]:
|
||||
"""
|
||||
Returns:
|
||||
(score, metadata_dict, document) 列表,score 同 SchemaIndexer 为 1-distance
|
||||
"""
|
||||
n = self.count()
|
||||
if n == 0:
|
||||
return []
|
||||
q_emb = self.embedder.encode(
|
||||
[(query or "").strip() or " "],
|
||||
batch_size=1,
|
||||
normalize=True,
|
||||
show_progress=False,
|
||||
)
|
||||
k = min(max(top_k, 1), n)
|
||||
results = self.collection.query(
|
||||
query_embeddings=q_emb.tolist(),
|
||||
n_results=k,
|
||||
)
|
||||
out: List[Tuple[float, Dict[str, Any], str]] = []
|
||||
if not results["ids"] or not results["ids"][0]:
|
||||
return out
|
||||
for tid, dist, meta, doc in zip(
|
||||
results["ids"][0],
|
||||
results["distances"][0],
|
||||
results["metadatas"][0],
|
||||
results["documents"][0],
|
||||
):
|
||||
score = 1.0 - float(dist)
|
||||
m = dict(meta or {})
|
||||
m["qid"] = tid
|
||||
out.append((score, m, doc or ""))
|
||||
return out
|
||||
|
||||
def get_all_as_samples(self) -> List[Any]:
|
||||
"""导出集合中全部样本(用于统计/按标签列举;条数大时慎用)。"""
|
||||
if self.count() == 0:
|
||||
return []
|
||||
data = self.collection.get(include=["metadatas", "documents"])
|
||||
ids = data.get("ids") or []
|
||||
metas = data.get("metadatas") or []
|
||||
docs = data.get("documents") or []
|
||||
out: List[Any] = []
|
||||
for i, qid in enumerate(ids):
|
||||
meta = dict(metas[i] or {}) if i < len(metas) else {}
|
||||
meta["qid"] = qid
|
||||
doc = docs[i] if i < len(docs) else ""
|
||||
out.append(sample_from_chroma_metadata(meta, doc))
|
||||
return out
|
||||
|
||||
|
||||
def sample_from_chroma_metadata(meta: Dict[str, Any], document: str) -> "ExperienceSample":
|
||||
from utils.fewshot_selector import ExperienceSample
|
||||
|
||||
tags_raw = meta.get("tags_json") or "[]"
|
||||
try:
|
||||
tags = json.loads(tags_raw) if isinstance(tags_raw, str) else []
|
||||
except json.JSONDecodeError:
|
||||
tags = []
|
||||
if not isinstance(tags, list):
|
||||
tags = []
|
||||
r = meta.get("rating")
|
||||
try:
|
||||
ri = int(r) if r is not None else -1
|
||||
except (TypeError, ValueError):
|
||||
ri = -1
|
||||
rating = ri if ri >= 0 else None
|
||||
qen = meta.get("question_en")
|
||||
return ExperienceSample(
|
||||
qid=str(meta.get("qid", "")),
|
||||
question_zh=document or str(meta.get("question_zh", "")),
|
||||
question_en=qen if qen else None,
|
||||
sql=str(meta.get("sql", "")),
|
||||
explanation=str(meta.get("explanation", "")),
|
||||
rating=rating,
|
||||
tags=tags,
|
||||
difficulty=str(meta.get("difficulty", "medium") or "medium"),
|
||||
)
|
||||
@@ -7,7 +7,9 @@ Few-shot示例选择器 - 基于经验数据集动态选择相关示例
|
||||
用法:
|
||||
from utils.fewshot_selector import FewShotSelector
|
||||
|
||||
selector = FewShotSelector("data/experiences/all_samples.jsonl")
|
||||
# Chroma 模式(FEWSHOT_USE_CHROMA=true):可不传 JSONL,路径传 None 或 ""
|
||||
selector = FewShotSelector(None)
|
||||
# 或传统:FewShotSelector("data/experiences/all_samples.jsonl")
|
||||
examples = selector.select(question="查询2024年1月的销售额", top_k=3)
|
||||
|
||||
# 在Prompt中使用
|
||||
@@ -24,7 +26,8 @@ import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_LOCAL_EMBED_PATH = "./data/models/Qwen3-Embedding-0.6B"
|
||||
# 仅 USE_LOCAL_EMBEDDING=true 时通过 EMBEDDING_MODEL_PATH 使用;远程模式留空即可
|
||||
_DEFAULT_LOCAL_EMBED_PATH = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -80,50 +83,128 @@ class FewShotSelector:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
samples_path: str,
|
||||
samples_path: Optional[str] = None,
|
||||
embedding_model_path: Optional[str] = None,
|
||||
use_cache: bool = True,
|
||||
use_chroma: Optional[bool] = None,
|
||||
chroma_persist_dir: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
samples_path: 样本JSONL文件路径
|
||||
samples_path: 样本 JSONL 路径;**空字符串**表示不读文件(仅当 ``FEWSHOT_USE_CHROMA=true``
|
||||
且 Chroma 中已有数据时可用)。构建索引仍请用 ``scripts/build_fewshot_chroma_index.py --samples``。
|
||||
embedding_model_path: 本地 Embedding 模型目录;None 时用环境变量
|
||||
EMBEDDING_MODEL_PATH(仅 USE_LOCAL_EMBEDDING=true 时有效)
|
||||
use_cache: 是否缓存样本向量(按向量维度分文件,换模型会自动重建)
|
||||
use_chroma: 是否使用 Chroma 持久化向量库;None 时读环境变量 FEWSHOT_USE_CHROMA
|
||||
chroma_persist_dir: Chroma 目录;None 时用 FEWSHOT_CHROMA_PATH 或默认 chroma_fewshot
|
||||
"""
|
||||
self.samples_path = Path(samples_path)
|
||||
sp = (samples_path or "").strip()
|
||||
self.samples_path: Optional[Path] = Path(sp) if sp else None
|
||||
self.samples: List[ExperienceSample] = []
|
||||
self._embedder = None
|
||||
self.embeddings: Optional[np.ndarray] = None
|
||||
self.use_cache = use_cache
|
||||
self.cache_path: Optional[Path] = None
|
||||
self._chroma_store = None
|
||||
self.use_chroma = (
|
||||
use_chroma
|
||||
if use_chroma is not None
|
||||
else os.getenv("FEWSHOT_USE_CHROMA", "false").lower() in ("1", "true", "yes")
|
||||
)
|
||||
self._chroma_persist_dir = chroma_persist_dir
|
||||
self._embedding_model_path = (
|
||||
embedding_model_path
|
||||
if embedding_model_path is not None
|
||||
else os.getenv("EMBEDDING_MODEL_PATH", _DEFAULT_LOCAL_EMBED_PATH).strip()
|
||||
)
|
||||
|
||||
if self.use_chroma:
|
||||
self._init_chroma_mode()
|
||||
else:
|
||||
self._load_samples()
|
||||
self._build_index()
|
||||
self._init_embedder_and_vector_index()
|
||||
|
||||
def _init_chroma_mode(self) -> None:
|
||||
"""Chroma 模式:先连向量库;库非空则不再读 JSONL。"""
|
||||
from utils.embedding import get_embedder
|
||||
from utils.fewshot_chroma_store import FewShotChromaStore
|
||||
|
||||
self._embedder = get_embedder(self._embedding_model_path)
|
||||
self._chroma_store = FewShotChromaStore(
|
||||
self._embedder,
|
||||
persist_dir=self._chroma_persist_dir,
|
||||
)
|
||||
n = self._chroma_store.count()
|
||||
if n > 0:
|
||||
logger.info(
|
||||
"[Few-shot] 已从向量库加载(Chroma %s 条,%s)",
|
||||
n,
|
||||
self._chroma_store.persist_dir,
|
||||
)
|
||||
else:
|
||||
self._load_samples()
|
||||
if self.samples:
|
||||
logger.info(
|
||||
"Few-shot Chroma 库为空,正从 JSONL 写入向量索引: %s",
|
||||
self.samples_path,
|
||||
)
|
||||
self._chroma_store.build_from_samples(self.samples, force_rebuild=False)
|
||||
elif self.samples_path is None:
|
||||
logger.warning(
|
||||
"[Few-shot] Chroma 库为空且未配置 JSONL;请运行 "
|
||||
"scripts/build_fewshot_chroma_index.py 或设置 FEWSHOT_DATA_PATH"
|
||||
)
|
||||
elif not self.samples_path.exists():
|
||||
logger.warning(
|
||||
"[Few-shot] Chroma 库为空且 JSONL 不存在: %s;请先灌库",
|
||||
self.samples_path,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"[Few-shot] Chroma 库为空且 JSONL 无有效样本: %s",
|
||||
self.samples_path,
|
||||
)
|
||||
|
||||
self.embeddings = None
|
||||
self.cache_path = None
|
||||
logger.info("[OK] Few-shot 使用 Chroma(%s 条)", self._chroma_store.count())
|
||||
|
||||
def _load_samples(self):
|
||||
"""加载样本数据"""
|
||||
"""从 JSONL 加载样本到内存(非 Chroma 模式必需;Chroma 空库时用于首次灌库)。"""
|
||||
if self.samples_path is None:
|
||||
if self.use_chroma:
|
||||
logger.info("[Few-shot] 未配置 JSONL 路径,运行时仅从 Chroma 检索")
|
||||
return
|
||||
raise ValueError("未指定样本 JSONL 路径且未启用 Chroma(FEWSHOT_USE_CHROMA)")
|
||||
|
||||
if not self.samples_path.exists():
|
||||
if self.use_chroma:
|
||||
logger.warning(
|
||||
"[Few-shot] JSONL 不存在 %s,跳过文件加载,仅从 Chroma 检索",
|
||||
self.samples_path,
|
||||
)
|
||||
return
|
||||
raise FileNotFoundError(f"样本文件不存在: {self.samples_path}")
|
||||
|
||||
logger.info(f"加载样本: {self.samples_path}")
|
||||
with self.samples_path.open('r', encoding='utf-8') as f:
|
||||
logger.info("从 JSONL 加载样本: %s", self.samples_path)
|
||||
with self.samples_path.open("r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
data = json.loads(line.strip())
|
||||
self.samples.append(ExperienceSample.from_dict(data))
|
||||
|
||||
logger.info(f"[OK] 加载 {len(self.samples)} 个样本")
|
||||
logger.info("[OK] 自 JSONL 加载 %s 个样本", len(self.samples))
|
||||
|
||||
def _build_index(self):
|
||||
"""用项目统一 Embedder 构建语义索引"""
|
||||
def _init_embedder_and_vector_index(self) -> None:
|
||||
"""非 Chroma:初始化 Embedder 与内存 numpy 索引。"""
|
||||
from utils.embedding import get_embedder
|
||||
|
||||
self._embedder = get_embedder(self._embedding_model_path)
|
||||
self._build_numpy_index()
|
||||
|
||||
def _build_numpy_index(self) -> None:
|
||||
"""内存向量 + 可选 .npy 缓存(与历史行为一致)。"""
|
||||
assert self._embedder is not None
|
||||
probe = self._embedder.encode(
|
||||
[" "],
|
||||
batch_size=1,
|
||||
@@ -168,6 +249,43 @@ class FewShotSelector:
|
||||
np.save(self.cache_path, self.embeddings)
|
||||
logger.info(f"[OK] Few-shot 向量已缓存: {self.cache_path}")
|
||||
|
||||
def _select_chroma(
|
||||
self,
|
||||
question: str,
|
||||
top_k: int,
|
||||
min_rating: Optional[int],
|
||||
required_tags: Optional[List[str]],
|
||||
max_difficulty: str,
|
||||
exclude_qids: Optional[List[str]],
|
||||
) -> List[ExperienceSample]:
|
||||
from utils.fewshot_chroma_store import sample_from_chroma_metadata
|
||||
|
||||
assert self._chroma_store is not None
|
||||
over_fetch = max(top_k * 12, 48)
|
||||
rows = self._chroma_store.search_raw(question, top_k=over_fetch)
|
||||
candidates: List[tuple[float, ExperienceSample]] = []
|
||||
for score, meta, doc in rows:
|
||||
s = sample_from_chroma_metadata(meta, doc)
|
||||
if exclude_qids and s.qid in exclude_qids:
|
||||
continue
|
||||
if min_rating and s.rating is not None and s.rating < min_rating:
|
||||
continue
|
||||
if max_difficulty == "easy" and s.difficulty != "easy":
|
||||
continue
|
||||
if max_difficulty == "medium" and s.difficulty == "hard":
|
||||
continue
|
||||
if required_tags and not all(tag in s.tags for tag in required_tags):
|
||||
continue
|
||||
candidates.append((score, s))
|
||||
|
||||
candidates.sort(key=lambda x: -x[0])
|
||||
selected = [s for _, s in candidates[:top_k]]
|
||||
logger.info(
|
||||
f"Few-shot(Chroma)选择: 问题='{question[:30]}...' → 选中{len(selected)}个示例 "
|
||||
f"(top_k={top_k}, min_rating={min_rating})"
|
||||
)
|
||||
return selected
|
||||
|
||||
def select(
|
||||
self,
|
||||
question: str,
|
||||
@@ -191,6 +309,16 @@ class FewShotSelector:
|
||||
Returns:
|
||||
排序后的示例列表(最相关优先)
|
||||
"""
|
||||
if self._chroma_store is not None:
|
||||
return self._select_chroma(
|
||||
question,
|
||||
top_k,
|
||||
min_rating,
|
||||
required_tags,
|
||||
max_difficulty,
|
||||
exclude_qids,
|
||||
)
|
||||
|
||||
if self._embedder is None or self.embeddings is None:
|
||||
logger.error("Few-shot 索引未初始化")
|
||||
return []
|
||||
@@ -266,10 +394,18 @@ class FewShotSelector:
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def _all_samples_for_aggregation(self) -> List[ExperienceSample]:
|
||||
"""内存中的 JSONL 样本,或 Chroma 全量导出(用于统计/按标签列举)。"""
|
||||
if self.samples:
|
||||
return self.samples
|
||||
if self._chroma_store is not None and self._chroma_store.count() > 0:
|
||||
return self._chroma_store.get_all_as_samples()
|
||||
return []
|
||||
|
||||
def get_tagged_examples(self, tags: List[str], top_k_per_tag: int = 2) -> str:
|
||||
"""获取特定标签的示例"""
|
||||
tagged_samples = []
|
||||
for sample in self.samples:
|
||||
for sample in self._all_samples_for_aggregation():
|
||||
if any(tag in sample.tags for tag in tags):
|
||||
tagged_samples.append(sample)
|
||||
|
||||
@@ -287,27 +423,33 @@ class FewShotSelector:
|
||||
|
||||
def get_stats(self) -> Dict:
|
||||
"""获取数据集统计"""
|
||||
src = self._all_samples_for_aggregation()
|
||||
stats = {
|
||||
"total": len(self.samples),
|
||||
"total": len(src),
|
||||
"by_rating": {},
|
||||
"by_difficulty": {},
|
||||
"by_tag": {},
|
||||
"avg_rating": 0.0
|
||||
"avg_rating": 0.0,
|
||||
"source": (
|
||||
"chroma"
|
||||
if (not self.samples and self._chroma_store and self._chroma_store.count() > 0)
|
||||
else ("jsonl" if self.samples else "empty")
|
||||
),
|
||||
}
|
||||
|
||||
ratings = [s.rating for s in self.samples if s.rating]
|
||||
ratings = [s.rating for s in src if s.rating]
|
||||
if ratings:
|
||||
stats["avg_rating"] = sum(ratings) / len(ratings)
|
||||
for r in range(1, 11):
|
||||
stats["by_rating"][r] = sum(1 for s in self.samples if s.rating == r)
|
||||
stats["by_rating"][r] = sum(1 for s in src if s.rating == r)
|
||||
|
||||
for diff in ["easy", "medium", "hard"]:
|
||||
stats["by_difficulty"][diff] = sum(
|
||||
1 for s in self.samples if s.difficulty == diff
|
||||
1 for s in src if s.difficulty == diff
|
||||
)
|
||||
|
||||
tag_counts = {}
|
||||
for s in self.samples:
|
||||
for s in src:
|
||||
for tag in s.tags:
|
||||
tag_counts[tag] = tag_counts.get(tag, 0) + 1
|
||||
stats["by_tag"] = tag_counts
|
||||
|
||||
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,20 +0,0 @@
|
||||
# Text2SQL 经验数据集
|
||||
|
||||
**来源**: `Example_text2sql.md`
|
||||
**样本数**: 50
|
||||
**生成时间**: 2026-04-10 14:51:56
|
||||
|
||||
## 文件说明
|
||||
|
||||
- `all_samples.jsonl` - 所有样本(JSONL格式)
|
||||
- `difficulty_*.jsonl` - 按难度分类
|
||||
- `by_tag/` - 按标签分类(每个标签一个文件)
|
||||
- `fewshot_examples.md` - Few-shot示例(Markdown格式)
|
||||
- `high_rating_samples.jsonl` - 高评分样本(rating≥8)
|
||||
|
||||
## 使用建议
|
||||
|
||||
1. **Few-shot prompting**: 使用 `fewshot_examples.md` 中的示例
|
||||
2. **训练数据**: 使用 `all_samples.jsonl` 进行模型微调
|
||||
3. **评估测试**: 使用 `high_rating_samples.jsonl` 作为测试集
|
||||
4. **领域适应**: 按标签选择相关示例(如broker相关查询)
|
||||
Binary file not shown.
@@ -1,50 +1,50 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "question_en": "What are the currency exchange rates used for today's settlement?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "question_en": "Which brokers have outstanding delivery obligations to us?", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q5", "question_zh": "列出今日发出的所有追收保证金通知及其回复状态。", "sql": "-- 查询今日追缴保证金记录 (参考日期: 2026-04-02)\n-- 使用 MCAccount 的账户级追缴字段(CallForDepositDate = 追缴通知发出日期)\n-- 注意:HCAccountMarginCallForDeposit 是追缴每日快照表,不含\"通知发出日\"字段\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.CallForDeposit AS CallAmount,\n a.CallForDepositDate AS IssueDate,\n a.CallForDepositDays AS OverdueDays\nFROM MCAccount a\nWHERE a.CallForDepositDate = '2026-04-02'\nORDER BY a.CallForDeposit DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.CallForDepositDate` = 追缴通知发出日期,`CallForDeposit` = 追缴金额\n- `CallForDeposit < 0` 表示已结清;如查活跃追缴,应筛选 `CallForDeposit > 0`\n- `HCAccountMarginCallForDeposit` 是追缴每日历史快照,不适合查询\"今日发出的通知\"\n- `CallStatus` 字段在 `HCAccountMarginCallForDeposit` 中不存在", "question_en": "Show all margin calls issued today and their response status.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果(测试环境中 MCAccount 的 `CallForDepositDate` 最新到 2025-10-31,2026-04-02 无追缴通知记录)\n\n> 注:`MCAccount.CallForDeposit` 当前所有值均为负数(已结清的追缴金额),无活跃追缴记录。", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "question_en": "Which instruments have corporate actions effective tomorrow?", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "question_en": "What dividends are expected to be received today?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "question_en": "Which clients have not yet paid their IPO subscription money?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q12", "question_zh": "本月累计的结算失败罚金是多少?", "sql": "-- 查询本月结算失败罚金 (2026年4月)\n-- 注意:BCAccountInstrument 无 FailedTradePenalty 字段,需另找结算罚金存储位置\n-- 目前未找到结算失败罚金字段,建议通过 TSBBrokerContract 或 BCBrokerCash 进一步排查\nSELECT \n COUNT(*) AS FailedTradeCount,\n MarketID\nFROM BCAccountInstrument\nWHERE YEAR(LastTransactionDate) = 2026\n AND MONTH(LastTransactionDate) = 4\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 无 `FailedTradePenalty` 字段,原始 SQL 会报错\n- `TSBBrokerContract` 或 `BCBrokerCash` 中可能存储结算相关费用,需进一步确认", "question_en": "What is the total failed trade penalty incurred this month?", "rating": 3, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 表无 FailedTradePenalty 字段,无法统计结算罚金)", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q13", "question_zh": "列出今日到期的所有股票借贷交易。", "sql": "-- 查询今日到期的股票借贷 (参考日期: 2026-04-02)\n-- MCMarket 表仅包含 HKEX/OSL/SETW,无独立借贷市场标识\n-- 股票借贷可能在持仓变动类型 HoldType 中标识,或在专门的 StockBorrowing 表中\n-- 此 SQL 按 DueBuy/DueSell 显示当前待交收证券,作为借贷合约的近似替代\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.DueBuy AS BorrowQuantity,\n bi.DueSell AS LoanQuantity,\n bi.DueBuy - bi.DueSell AS NetBorrow\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE bi.DueBuy > 0 OR bi.DueSell > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `DueBuy/DueSell` 表示待交收数量(借款买入/借出卖出),反映股票借贷待到期情况\n- `MCMarket` 表无 `MarketType='BORROW'` 标识,现有市场仅为 HKEX/OSL/SETW\n- 股票借贷详情可能存储在 `TSBAccountLoanContract` 或其他借贷专用表中,需业务确认", "question_en": "List all stock borrow/loan transactions due to settle today.", "rating": 5, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 中 DueBuy/DueSell 均为 0,无待交收证券)", "tags": ["join", "trade", "filter"], "difficulty": "medium"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "question_en": "Show all client withdrawals requested but not yet processed.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "question_en": "Which clients have exceeded their credit limit?", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q18", "question_zh": "今日收到的未清算支票总额是多少?", "sql": "-- 查询未清算支票 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.UnderdueCheque AS OverdueCheque,\n c.NextDayDueCheque AS PendingCheque,\n c.UnderdueCheque + c.NextDayDueCheque AS TotalUncleared\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.UnderdueCheque > 0 OR c.NextDayDueCheque > 0) -- 注意:BCAccountCash 无这两个字段,需确认实际表\nORDER BY TotalUncleared DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 无 `UnderdueCheque` / `NextDayDueCheque` 字段,需业务确认支票数据存储位置", "question_en": "What is the total amount of uncleared cheques received today?", "rating": 4, "execution_result": null, "result_note": "当前查询无未清算支票", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q19", "question_zh": "列出今日起保证金比例发生变动的所有证券。", "sql": "-- 查询保证金比例变动的证券 (固定日期: 2026-04-02)\nSELECT \n i.InstrumentID,\n i.Name AS InstrumentName,\n i.MarginPercentage AS CurrentMarginRatio,\n i.MarginChangeDate\nFROM MCInstrument i\nWHERE i.MarginChangeDate = '2026-04-02'\nORDER BY i.MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument.MarginPercentage` 当前保证金比例\n- `MarginChangeDate` 变动日期", "question_en": "List all instruments with margin ratio changes effective today.", "rating": 7, "execution_result": null, "result_note": "当前查询无保证金比例变动记录", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "question_en": "Which corporate action elections are due by end of day?", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "question_en": "How many client statements were successfully generated but not yet delivered?", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
{"qid": "Q25", "question_zh": "列出所有待批准的股票转移请求。", "sql": "-- 查询待批准的股票转移\nSELECT \n AccountID,\n InstrumentID,\n MovementType,\n MovementQuantity,\n FromAccountID,\n ToAccountID,\n RequestDate,\n ApprovalStatus,\n RequestedBy\nFROM BCAccountInstrumentMovement\nWHERE ApprovalStatus = 'P'\nORDER BY RequestDate DESC;", "schema_info": {"tables": {"BCAccountInstrumentMovement": {"alias": "BCAccountInstrumentMovement", "columns": []}}, "joins": []}, "explanation": "- 股票转移请求存储在专用表中\n- `ApprovalStatus = 'P'` 待批准状态", "question_en": "Show all pending stock movement requests that require approval.", "rating": 6, "execution_result": null, "result_note": "当前查询无待批准请求", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "question_en": "Which clients have requested a change in settlement currency?", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q31", "question_zh": "指定日期或日期范围内收到的交易量(如成交金额)及相应佣金是多少?", "sql": "-- 交易量和佣金统计\nSELECT \n SUM(TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(TotalBoughtFee) AS TotalBuyCommission,\n SUM(TotalSoldConsideration) AS TotalSellConsideration,\n SUM(TotalSoldFee) AS TotalSellCommission,\n SUM(TotalBoughtConsideration) + SUM(TotalSoldConsideration) AS TotalConsideration,\n SUM(TotalBoughtFee) + SUM(TotalSoldFee) AS TotalCommission\nFROM BCAccountInstrument;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录了账户所有历史买卖交易\n- `TotalBoughtConsideration / TotalSoldConsideration`: 买卖成交金额", "question_en": "What is the trading volume (e.g., consideration) and corresponding commission amount received for a specific date or date range?", "rating": 9, "execution_result": null, "result_note": "| TotalBuyConsideration | TotalBuyCommission | TotalSellConsideration | TotalSellCommission | TotalConsideration | TotalCommission |\n|---------------------|-------------------|----------------------|--------------------|-------------------|-----------------|\n| 945,480,833.78 | 793,149.07 | 278,693,891.64 | 809,248.89 | 1,224,174,725.42 | 1,602,397.96 |", "tags": ["trade", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "question_en": "Have there been any margin calls today?", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q36", "question_zh": "各市场(如港股T+1和T+2、美股T+1)的待结算金额是多少?", "sql": "-- 按市场统计待结算金额\nSELECT \n MarketID,\n SUM(DueBuy + DueSell) AS TotalPendingQty,\n SUM(NextDayDueBuy + NextDayDueSell) AS T2TotalPendingQty\nFROM BCAccountInstrument\nWHERE DueBuy > 0 OR DueSell > 0 OR NextDayDueBuy > 0 OR NextDayDueSell > 0\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录各市场的待交收数量\n- `DueBuy/DueSell` 对应T+1交收", "question_en": "What is the pending settlement amount for each market (e.g., HK T+1 & T+2, US T+1)?", "rating": 7, "execution_result": null, "result_note": "| MarketID | TotalPendingQty | T2TotalPendingQty |\n|----------|----------------|------------------|\n| HKEX | 0 | 0 |\n| SETW | 0 | 0 |", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q40", "question_zh": "列出今日执行的所有股票转移/移动。", "sql": "-- 今日股票转入/转出 (固定日期: 2026-04-02)\nSELECT \n AccountID,\n MarketID,\n InstrumentID,\n TodayIn AS QuantityIn,\n TodayOut AS QuantityOut,\n HoldForDeposit AS PendingDeposit,\n HoldForWithdrawal AS PendingWithdrawal\nFROM BCAccountInstrument\nWHERE TodayIn > 0 OR TodayOut > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录股票持仓变动\n- `TodayIn` 今日转入数量", "question_en": "List all stock movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["filter"], "difficulty": "easy"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "question_en": "List all cash movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
{"qid": "Q42", "question_zh": "列出后台系统中的活跃用户。", "sql": "-- 查询后台系统活跃用户\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n u.DepartmentID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储系统用户信息\n- `State = 'A'` 用户状态正常", "question_en": "List active users in the back office.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | AEType |\n|--------|----------|--------|-----------------|---------------|--------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-03 18:53:04 | 个人 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 16:47:11 | 个人 |", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q44", "question_zh": "本月收到/支付的利息金额是多少(如客户借款利息和存款利息)?", "sql": "-- 本月利息收支汇总 (2026年4月)\nSELECT \n SUM(AccruedCreditInterest) AS CreditInterest,\n SUM(AccruedDebitInterest) AS DebitInterest,\n SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetInterest\nFROM BCAccountCash;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金和利息信息\n- `AccruedCreditInterest` 应计存款利息", "question_en": "What is the interest amount received/paid this month (e.g., client debit interest and credit interest)?", "rating": 7, "execution_result": null, "result_note": "| CreditInterest | DebitInterest | NetInterest |\n|----------------|---------------|-------------|\n| 464.15 | 2,022.70 | -1,558.55 |", "tags": ["account", "aggregation", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q50", "question_zh": "", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "question_en": "列出今天所有客戶的交易記錄", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---\n\n## 附录:关键表说明\n\n| 表名 | 说明 | 关键字段 |\n|------|------|---------|\n| MCAccount | 账户主表 | AccountID, Name, MarketValue, MarginFacilityFlag |\n| MCUser | 用户表 | UserID, Name, Status, LogonEnableFlag |\n| BCAccountInstrument | 账户持仓 | AccountID, MarketID, Settled, DueBuy, DueSell |\n| BCAccountCash | 账户现金 | AccountID, TodayIn, TodayOut, AccruedInterest |\n| HCAccountMarginCallForDeposit | 追缴保证金 | AccountID, CallForDeposit, CallForDepositDate |\n| MCInstrument | 证券表 | InstrumentID, Name, MarginPercentage |\n| MCInstrumentIPODetail | IPO详情 | InstrumentID, Quantity, SubscriptionAmount |\n| MSBEntitlement | 权益分派 | EntitlementID, BalanceDate, BalanceExDate |\n| MCBroker | 经纪商 | BrokerID, Name |\n| MCLocation | 托管位置 | LocationID, Name, CCASSFlag |\n| HCExchangeRate | 汇率 | ExchangeRateID, ValueDate |\n| HCAccountCashRecord | 现金记录 | AccountID, ValueDate, LedgerBalance |\n\n---\n\n**文档结束**", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "question_en": "List all stock transfers between client accounts performed today.", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "question_en": "What are the currency exchange rates used for today's settlement?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;\n\n-- 查询具体汇率值 (固定日期: 2026-04-02)\nSELECT \n d.ExchangeRateID,\n r.Name AS ExchangeRateName,\n d.FromCurrencyID,\n d.ToCurrencyID,\n d.ExchangeRateDirection,\n d.ExchangeRate,\n d.ExchangeRateBid,\n d.ExchangeRateAsk\nFROM HCExchangeRateDetail d\nINNER JOIN HCExchangeRate r \n ON d.ExchangeRateID = r.ExchangeRateID \n AND d.ValueDate = r.ValueDate\nWHERE d.ValueDate = '2026-04-02'\nORDER BY d.ExchangeRateID, d.FromCurrencyID, d.ToCurrencyID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "rating": 9, "execution_result": null, "result_note": "**执行结果2:**\n\n| ExchangeRateID | ExchangeRateName | FromCurrencyID | ToCurrencyID | ExchangeRate |\n|----------------|------------------|---------------|--------------|-------------:|\n| HKEX | 港交所汇率 | USD | HKD | 7.754 |\n| HKEX | 港交所汇率 | CNY | HKD | 1.0805 |\n| HKEX | 港交所汇率 | GBP | HKD | 12.8 |\n| HKEX | 港交所汇率 | HKD | USD | 0.128966 |\n| HKEX | 港交所汇率 | HKD | CNY | 0.925497 |\n| HKEX | 港交所汇率 | JPY | HKD | 0.095 |\n| HKEX | 港交所汇率 | SGD | HKD | 6.1 |\n| LEDGER | 账本汇率 | USD | HKD | 7.8 |\n| LEDGER | 账本汇率 | CNY | HKD | 1.081 |\n| LEDGER | 账本汇率 | GBP | HKD | 12.8 |\n| LEDGER | 账本汇率 | HKD | USD | 0.128205 |\n| EVALUATION | 估值汇率 | USD | HKD | 7.8 |\n| EVALUATION | 估值汇率 | CNY | HKD | 1.081 |\n| EVALUATION | 估值汇率 | GBP | HKD | 12.8 |\n| EVALUATION | 估值汇率 | HKD | USD | 0.128205 |", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "question_en": "Which brokers have outstanding delivery obligations to us?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q5", "question_zh": "列出今日发出的所有追收保证金通知及其回复状态。", "question_en": "Show all margin calls issued today and their response status.", "sql": "-- 查询今日追缴保证金记录 (参考日期: 2026-04-02)\n-- 使用 MCAccount 的账户级追缴字段(CallForDepositDate = 追缴通知发出日期)\n-- 注意:HCAccountMarginCallForDeposit 是追缴每日快照表,不含\"通知发出日\"字段\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.CallForDeposit AS CallAmount,\n a.CallForDepositDate AS IssueDate,\n a.CallForDepositDays AS OverdueDays\nFROM MCAccount a\nWHERE a.CallForDepositDate = '2026-04-02'\nORDER BY a.CallForDeposit DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.CallForDepositDate` = 追缴通知发出日期,`CallForDeposit` = 追缴金额\n- `CallForDeposit < 0` 表示已结清;如查活跃追缴,应筛选 `CallForDeposit > 0`\n- `HCAccountMarginCallForDeposit` 是追缴每日历史快照,不适合查询\"今日发出的通知\"\n- `CallStatus` 字段在 `HCAccountMarginCallForDeposit` 中不存在", "rating": 7, "execution_result": null, "result_note": "当前查询无结果(测试环境中 MCAccount 的 `CallForDepositDate` 最新到 2025-10-31,2026-04-02 无追缴通知记录)\n\n> 注:`MCAccount.CallForDeposit` 当前所有值均为负数(已结清的追缴金额),无活跃追缴记录。", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "question_en": "What is the total client cash balance across all currencies?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "question_en": "List accounts with negative cash balance after today's settlement.", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "question_en": "Which instruments have corporate actions effective tomorrow?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "question_en": "What dividends are expected to be received today?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;\n\n-- 汇总今日股息数量和涉及证券数\nSELECT \n COUNT(DISTINCT InstrumentID) AS DividendCount,\n COUNT(*) AS TotalEntitlements\nFROM MSBEntitlement\nWHERE BalanceDate = '2026-04-02'\n AND BalanceType = 'C'\n AND State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "rating": 8, "execution_result": null, "result_note": "**执行结果2:**\n\n| DividendCount | TotalEntitlements |\n|---------------|-------------------|\n| 0 | 0 |", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "question_en": "Which clients have not yet paid their IPO subscription money?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q12", "question_zh": "本月累计的结算失败罚金是多少?", "question_en": "What is the total failed trade penalty incurred this month?", "sql": "-- 查询本月结算失败罚金 (2026年4月)\n-- 注意:BCAccountInstrument 无 FailedTradePenalty 字段,需另找结算罚金存储位置\n-- 目前未找到结算失败罚金字段,建议通过 TSBBrokerContract 或 BCBrokerCash 进一步排查\nSELECT \n COUNT(*) AS FailedTradeCount,\n MarketID\nFROM BCAccountInstrument\nWHERE YEAR(LastTransactionDate) = 2026\n AND MONTH(LastTransactionDate) = 4\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 无 `FailedTradePenalty` 字段,原始 SQL 会报错\n- `TSBBrokerContract` 或 `BCBrokerCash` 中可能存储结算相关费用,需进一步确认", "rating": 3, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 表无 FailedTradePenalty 字段,无法统计结算罚金)", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q13", "question_zh": "列出今日到期的所有股票借贷交易。", "question_en": "List all stock borrow/loan transactions due to settle today.", "sql": "-- 查询今日到期的股票借贷 (参考日期: 2026-04-02)\n-- MCMarket 表仅包含 HKEX/OSL/SETW,无独立借贷市场标识\n-- 股票借贷可能在持仓变动类型 HoldType 中标识,或在专门的 StockBorrowing 表中\n-- 此 SQL 按 DueBuy/DueSell 显示当前待交收证券,作为借贷合约的近似替代\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.DueBuy AS BorrowQuantity,\n bi.DueSell AS LoanQuantity,\n bi.DueBuy - bi.DueSell AS NetBorrow\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE bi.DueBuy > 0 OR bi.DueSell > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `DueBuy/DueSell` 表示待交收数量(借款买入/借出卖出),反映股票借贷待到期情况\n- `MCMarket` 表无 `MarketType='BORROW'` 标识,现有市场仅为 HKEX/OSL/SETW\n- 股票借贷详情可能存储在 `TSBAccountLoanContract` 或其他借贷专用表中,需业务确认", "rating": 5, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 中 DueBuy/DueSell 均为 0,无待交收证券)", "tags": ["join", "trade", "filter"], "difficulty": "medium"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "question_en": "Show all client withdrawals requested but not yet processed.", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;\n\n-- 查询返佣规则表\n-- SELECT * FROM MCRebateScheme WHERE State = 'A';\n-- 需关联获取实际返佣比例", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "question_en": "Which clients have exceeded their credit limit?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q18", "question_zh": "今日收到的未清算支票总额是多少?", "question_en": "What is the total amount of uncleared cheques received today?", "sql": "-- 查询未清算支票 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.UnderdueCheque AS OverdueCheque,\n c.NextDayDueCheque AS PendingCheque,\n c.UnderdueCheque + c.NextDayDueCheque AS TotalUncleared\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.UnderdueCheque > 0 OR c.NextDayDueCheque > 0) -- 注意:BCAccountCash 无这两个字段,需确认实际表\nORDER BY TotalUncleared DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 无 `UnderdueCheque` / `NextDayDueCheque` 字段,需业务确认支票数据存储位置", "rating": 4, "execution_result": null, "result_note": "当前查询无未清算支票", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q19", "question_zh": "列出今日起保证金比例发生变动的所有证券。", "question_en": "List all instruments with margin ratio changes effective today.", "sql": "-- 查询保证金比例变动的证券 (固定日期: 2026-04-02)\nSELECT \n i.InstrumentID,\n i.Name AS InstrumentName,\n i.MarginPercentage AS CurrentMarginRatio,\n i.MarginChangeDate\nFROM MCInstrument i\nWHERE i.MarginChangeDate = '2026-04-02'\nORDER BY i.MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument.MarginPercentage` 当前保证金比例\n- `MarginChangeDate` 变动日期", "rating": 7, "execution_result": null, "result_note": "当前查询无保证金比例变动记录", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "question_en": "Which corporate action elections are due by end of day?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "question_en": "List all cash movements between house and client accounts today.", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "question_en": "Show all accounts with overdue margin interest payments.", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "question_en": "How many client statements were successfully generated but not yet delivered?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
{"qid": "Q25", "question_zh": "列出所有待批准的股票转移请求。", "question_en": "Show all pending stock movement requests that require approval.", "sql": "-- 查询待批准的股票转移\nSELECT \n AccountID,\n InstrumentID,\n MovementType,\n MovementQuantity,\n FromAccountID,\n ToAccountID,\n RequestDate,\n ApprovalStatus,\n RequestedBy\nFROM BCAccountInstrumentMovement\nWHERE ApprovalStatus = 'P'\nORDER BY RequestDate DESC;", "schema_info": {"tables": {"BCAccountInstrumentMovement": {"alias": "BCAccountInstrumentMovement", "columns": []}}, "joins": []}, "explanation": "- 股票转移请求存储在专用表中\n- `ApprovalStatus = 'P'` 待批准状态", "rating": 6, "execution_result": null, "result_note": "当前查询无待批准请求", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;\n\n-- 本月结算费用汇总 (2026年4月)\nSELECT \n SUM(TotalBoughtFee) AS TotalBuyFee,\n SUM(TotalSellFee) AS TotalSellFee,\n SUM(TotalBoughtFee + TotalSellFee) AS GrandTotal\nFROM BCAccountInstrument\nWHERE LastTransactionDate >= '2026-04-01' AND LastTransactionDate < '2026-05-01';", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "rating": 8, "execution_result": null, "result_note": "**执行结果2:**\n\n| TotalBuyFee | TotalSellFee | GrandTotal |\n|------------|--------------|------------|\n| 906.77 | 539.05 | 1,445.82 |", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "question_en": "List all suspense account entries older than 3 days.", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "question_en": "Which clients have requested a change in settlement currency?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "question_en": "List all active user accounts in the back office system with last login date.", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "question_en": "What is the total exposure from unsettled trades by settlement date?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q31", "question_zh": "指定日期或日期范围内收到的交易量(如成交金额)及相应佣金是多少?", "question_en": "What is the trading volume (e.g., consideration) and corresponding commission amount received for a specific date or date range?", "sql": "-- 交易量和佣金统计\nSELECT \n SUM(TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(TotalBoughtFee) AS TotalBuyCommission,\n SUM(TotalSoldConsideration) AS TotalSellConsideration,\n SUM(TotalSoldFee) AS TotalSellCommission,\n SUM(TotalBoughtConsideration) + SUM(TotalSoldConsideration) AS TotalConsideration,\n SUM(TotalBoughtFee) + SUM(TotalSoldFee) AS TotalCommission\nFROM BCAccountInstrument;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录了账户所有历史买卖交易\n- `TotalBoughtConsideration / TotalSoldConsideration`: 买卖成交金额", "rating": 9, "execution_result": null, "result_note": "| TotalBuyConsideration | TotalBuyCommission | TotalSellConsideration | TotalSellCommission | TotalConsideration | TotalCommission |\n|---------------------|-------------------|----------------------|--------------------|-------------------|-----------------|\n| 945,480,833.78 | 793,149.07 | 278,693,891.64 | 809,248.89 | 1,224,174,725.42 | 1,602,397.96 |", "tags": ["trade", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "question_en": "Have there been any margin calls today?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q36", "question_zh": "各市场(如港股T+1和T+2、美股T+1)的待结算金额是多少?", "question_en": "What is the pending settlement amount for each market (e.g., HK T+1 & T+2, US T+1)?", "sql": "-- 按市场统计待结算金额\nSELECT \n MarketID,\n SUM(DueBuy + DueSell) AS TotalPendingQty,\n SUM(NextDayDueBuy + NextDayDueSell) AS T2TotalPendingQty\nFROM BCAccountInstrument\nWHERE DueBuy > 0 OR DueSell > 0 OR NextDayDueBuy > 0 OR NextDayDueSell > 0\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录各市场的待交收数量\n- `DueBuy/DueSell` 对应T+1交收", "rating": 7, "execution_result": null, "result_note": "| MarketID | TotalPendingQty | T2TotalPendingQty |\n|----------|----------------|------------------|\n| HKEX | 0 | 0 |\n| SETW | 0 | 0 |", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;\n\n-- 查询所有进行中的IPO\nSELECT \n COUNT(*) AS IPOCount,\n SUM(SubscriptionAmount) AS TotalSubscriptionAmount\nFROM MCInstrumentIPODetail\nWHERE State = 'A';", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q40", "question_zh": "列出今日执行的所有股票转移/移动。", "question_en": "List all stock movements performed today.", "sql": "-- 今日股票转入/转出 (固定日期: 2026-04-02)\nSELECT \n AccountID,\n MarketID,\n InstrumentID,\n TodayIn AS QuantityIn,\n TodayOut AS QuantityOut,\n HoldForDeposit AS PendingDeposit,\n HoldForWithdrawal AS PendingWithdrawal\nFROM BCAccountInstrument\nWHERE TodayIn > 0 OR TodayOut > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录股票持仓变动\n- `TodayIn` 今日转入数量", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["filter"], "difficulty": "easy"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "question_en": "List all cash movements performed today.", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
{"qid": "Q42", "question_zh": "列出后台系统中的活跃用户。", "question_en": "List active users in the back office.", "sql": "-- 查询后台系统活跃用户\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n u.DepartmentID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储系统用户信息\n- `State = 'A'` 用户状态正常", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | AEType |\n|--------|----------|--------|-----------------|---------------|--------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-03 18:53:04 | 个人 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 16:47:11 | 个人 |", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "question_en": "List accounts with overdrawn positions.", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q44", "question_zh": "本月收到/支付的利息金额是多少(如客户借款利息和存款利息)?", "question_en": "What is the interest amount received/paid this month (e.g., client debit interest and credit interest)?", "sql": "-- 本月利息收支汇总 (2026年4月)\nSELECT \n SUM(AccruedCreditInterest) AS CreditInterest,\n SUM(AccruedDebitInterest) AS DebitInterest,\n SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetInterest\nFROM BCAccountCash;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金和利息信息\n- `AccruedCreditInterest` 应计存款利息", "rating": 7, "execution_result": null, "result_note": "| CreditInterest | DebitInterest | NetInterest |\n|----------------|---------------|-------------|\n| 464.15 | 2,022.70 | -1,558.55 |", "tags": ["account", "aggregation", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "question_en": "How much commission has been paid to other brokers?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';\n\n-- 查询具体发放报表的账户\nSELECT \n AccountID,\n Name AS AccountName,\n LastDailyStatementDate,\n LastMonthlyStatementDate\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\n OR LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "question_en": "How many accounts were opened this month, this quarter, and this year?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q50", "question_zh": "列出今天所有客戶的交易記錄", "question_en": "List all client trade records for today.", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "question_en": "Which clients have not yet paid their IPO subscription money?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "question_en": "Show all client withdrawals requested but not yet processed.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "question_en": "Which clients have exceeded their credit limit?", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "question_en": "How many client statements were successfully generated but not yet delivered?", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "question_en": "Which clients have requested a change in settlement currency?", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q44", "question_zh": "本月收到/支付的利息金额是多少(如客户借款利息和存款利息)?", "sql": "-- 本月利息收支汇总 (2026年4月)\nSELECT \n SUM(AccruedCreditInterest) AS CreditInterest,\n SUM(AccruedDebitInterest) AS DebitInterest,\n SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetInterest\nFROM BCAccountCash;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金和利息信息\n- `AccruedCreditInterest` 应计存款利息", "question_en": "What is the interest amount received/paid this month (e.g., client debit interest and credit interest)?", "rating": 7, "execution_result": null, "result_note": "| CreditInterest | DebitInterest | NetInterest |\n|----------------|---------------|-------------|\n| 464.15 | 2,022.70 | -1,558.55 |", "tags": ["account", "aggregation", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
@@ -1,17 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q12", "question_zh": "本月累计的结算失败罚金是多少?", "sql": "-- 查询本月结算失败罚金 (2026年4月)\n-- 注意:BCAccountInstrument 无 FailedTradePenalty 字段,需另找结算罚金存储位置\n-- 目前未找到结算失败罚金字段,建议通过 TSBBrokerContract 或 BCBrokerCash 进一步排查\nSELECT \n COUNT(*) AS FailedTradeCount,\n MarketID\nFROM BCAccountInstrument\nWHERE YEAR(LastTransactionDate) = 2026\n AND MONTH(LastTransactionDate) = 4\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 无 `FailedTradePenalty` 字段,原始 SQL 会报错\n- `TSBBrokerContract` 或 `BCBrokerCash` 中可能存储结算相关费用,需进一步确认", "question_en": "What is the total failed trade penalty incurred this month?", "rating": 3, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 表无 FailedTradePenalty 字段,无法统计结算罚金)", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q31", "question_zh": "指定日期或日期范围内收到的交易量(如成交金额)及相应佣金是多少?", "sql": "-- 交易量和佣金统计\nSELECT \n SUM(TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(TotalBoughtFee) AS TotalBuyCommission,\n SUM(TotalSoldConsideration) AS TotalSellConsideration,\n SUM(TotalSoldFee) AS TotalSellCommission,\n SUM(TotalBoughtConsideration) + SUM(TotalSoldConsideration) AS TotalConsideration,\n SUM(TotalBoughtFee) + SUM(TotalSoldFee) AS TotalCommission\nFROM BCAccountInstrument;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录了账户所有历史买卖交易\n- `TotalBoughtConsideration / TotalSoldConsideration`: 买卖成交金额", "question_en": "What is the trading volume (e.g., consideration) and corresponding commission amount received for a specific date or date range?", "rating": 9, "execution_result": null, "result_note": "| TotalBuyConsideration | TotalBuyCommission | TotalSellConsideration | TotalSellCommission | TotalConsideration | TotalCommission |\n|---------------------|-------------------|----------------------|--------------------|-------------------|-----------------|\n| 945,480,833.78 | 793,149.07 | 278,693,891.64 | 809,248.89 | 1,224,174,725.42 | 1,602,397.96 |", "tags": ["trade", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q36", "question_zh": "各市场(如港股T+1和T+2、美股T+1)的待结算金额是多少?", "sql": "-- 按市场统计待结算金额\nSELECT \n MarketID,\n SUM(DueBuy + DueSell) AS TotalPendingQty,\n SUM(NextDayDueBuy + NextDayDueSell) AS T2TotalPendingQty\nFROM BCAccountInstrument\nWHERE DueBuy > 0 OR DueSell > 0 OR NextDayDueBuy > 0 OR NextDayDueSell > 0\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录各市场的待交收数量\n- `DueBuy/DueSell` 对应T+1交收", "question_en": "What is the pending settlement amount for each market (e.g., HK T+1 & T+2, US T+1)?", "rating": 7, "execution_result": null, "result_note": "| MarketID | TotalPendingQty | T2TotalPendingQty |\n|----------|----------------|------------------|\n| HKEX | 0 | 0 |\n| SETW | 0 | 0 |", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q44", "question_zh": "本月收到/支付的利息金额是多少(如客户借款利息和存款利息)?", "sql": "-- 本月利息收支汇总 (2026年4月)\nSELECT \n SUM(AccruedCreditInterest) AS CreditInterest,\n SUM(AccruedDebitInterest) AS DebitInterest,\n SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetInterest\nFROM BCAccountCash;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金和利息信息\n- `AccruedCreditInterest` 应计存款利息", "question_en": "What is the interest amount received/paid this month (e.g., client debit interest and credit interest)?", "rating": 7, "execution_result": null, "result_note": "| CreditInterest | DebitInterest | NetInterest |\n|----------------|---------------|-------------|\n| 464.15 | 2,022.70 | -1,558.55 |", "tags": ["account", "aggregation", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
@@ -1,3 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
@@ -1,5 +0,0 @@
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "question_en": "List all cash movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
@@ -1,3 +0,0 @@
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "question_en": "Which instruments have corporate actions effective tomorrow?", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "question_en": "Which corporate action elections are due by end of day?", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
@@ -1,2 +0,0 @@
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1 +0,0 @@
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
@@ -1 +0,0 @@
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "question_en": "What are the currency exchange rates used for today's settlement?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,45 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "question_en": "What are the currency exchange rates used for today's settlement?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "question_en": "Which brokers have outstanding delivery obligations to us?", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q5", "question_zh": "列出今日发出的所有追收保证金通知及其回复状态。", "sql": "-- 查询今日追缴保证金记录 (参考日期: 2026-04-02)\n-- 使用 MCAccount 的账户级追缴字段(CallForDepositDate = 追缴通知发出日期)\n-- 注意:HCAccountMarginCallForDeposit 是追缴每日快照表,不含\"通知发出日\"字段\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.CallForDeposit AS CallAmount,\n a.CallForDepositDate AS IssueDate,\n a.CallForDepositDays AS OverdueDays\nFROM MCAccount a\nWHERE a.CallForDepositDate = '2026-04-02'\nORDER BY a.CallForDeposit DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.CallForDepositDate` = 追缴通知发出日期,`CallForDeposit` = 追缴金额\n- `CallForDeposit < 0` 表示已结清;如查活跃追缴,应筛选 `CallForDeposit > 0`\n- `HCAccountMarginCallForDeposit` 是追缴每日历史快照,不适合查询\"今日发出的通知\"\n- `CallStatus` 字段在 `HCAccountMarginCallForDeposit` 中不存在", "question_en": "Show all margin calls issued today and their response status.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果(测试环境中 MCAccount 的 `CallForDepositDate` 最新到 2025-10-31,2026-04-02 无追缴通知记录)\n\n> 注:`MCAccount.CallForDeposit` 当前所有值均为负数(已结清的追缴金额),无活跃追缴记录。", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "question_en": "Which instruments have corporate actions effective tomorrow?", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "question_en": "What dividends are expected to be received today?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "question_en": "Which clients have not yet paid their IPO subscription money?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q12", "question_zh": "本月累计的结算失败罚金是多少?", "sql": "-- 查询本月结算失败罚金 (2026年4月)\n-- 注意:BCAccountInstrument 无 FailedTradePenalty 字段,需另找结算罚金存储位置\n-- 目前未找到结算失败罚金字段,建议通过 TSBBrokerContract 或 BCBrokerCash 进一步排查\nSELECT \n COUNT(*) AS FailedTradeCount,\n MarketID\nFROM BCAccountInstrument\nWHERE YEAR(LastTransactionDate) = 2026\n AND MONTH(LastTransactionDate) = 4\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 无 `FailedTradePenalty` 字段,原始 SQL 会报错\n- `TSBBrokerContract` 或 `BCBrokerCash` 中可能存储结算相关费用,需进一步确认", "question_en": "What is the total failed trade penalty incurred this month?", "rating": 3, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 表无 FailedTradePenalty 字段,无法统计结算罚金)", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q13", "question_zh": "列出今日到期的所有股票借贷交易。", "sql": "-- 查询今日到期的股票借贷 (参考日期: 2026-04-02)\n-- MCMarket 表仅包含 HKEX/OSL/SETW,无独立借贷市场标识\n-- 股票借贷可能在持仓变动类型 HoldType 中标识,或在专门的 StockBorrowing 表中\n-- 此 SQL 按 DueBuy/DueSell 显示当前待交收证券,作为借贷合约的近似替代\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.DueBuy AS BorrowQuantity,\n bi.DueSell AS LoanQuantity,\n bi.DueBuy - bi.DueSell AS NetBorrow\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE bi.DueBuy > 0 OR bi.DueSell > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `DueBuy/DueSell` 表示待交收数量(借款买入/借出卖出),反映股票借贷待到期情况\n- `MCMarket` 表无 `MarketType='BORROW'` 标识,现有市场仅为 HKEX/OSL/SETW\n- 股票借贷详情可能存储在 `TSBAccountLoanContract` 或其他借贷专用表中,需业务确认", "question_en": "List all stock borrow/loan transactions due to settle today.", "rating": 5, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 中 DueBuy/DueSell 均为 0,无待交收证券)", "tags": ["join", "trade", "filter"], "difficulty": "medium"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "question_en": "Show all client withdrawals requested but not yet processed.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "question_en": "Which clients have exceeded their credit limit?", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q18", "question_zh": "今日收到的未清算支票总额是多少?", "sql": "-- 查询未清算支票 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.UnderdueCheque AS OverdueCheque,\n c.NextDayDueCheque AS PendingCheque,\n c.UnderdueCheque + c.NextDayDueCheque AS TotalUncleared\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.UnderdueCheque > 0 OR c.NextDayDueCheque > 0) -- 注意:BCAccountCash 无这两个字段,需确认实际表\nORDER BY TotalUncleared DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 无 `UnderdueCheque` / `NextDayDueCheque` 字段,需业务确认支票数据存储位置", "question_en": "What is the total amount of uncleared cheques received today?", "rating": 4, "execution_result": null, "result_note": "当前查询无未清算支票", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q19", "question_zh": "列出今日起保证金比例发生变动的所有证券。", "sql": "-- 查询保证金比例变动的证券 (固定日期: 2026-04-02)\nSELECT \n i.InstrumentID,\n i.Name AS InstrumentName,\n i.MarginPercentage AS CurrentMarginRatio,\n i.MarginChangeDate\nFROM MCInstrument i\nWHERE i.MarginChangeDate = '2026-04-02'\nORDER BY i.MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument.MarginPercentage` 当前保证金比例\n- `MarginChangeDate` 变动日期", "question_en": "List all instruments with margin ratio changes effective today.", "rating": 7, "execution_result": null, "result_note": "当前查询无保证金比例变动记录", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "question_en": "Which corporate action elections are due by end of day?", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "question_en": "How many client statements were successfully generated but not yet delivered?", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
{"qid": "Q25", "question_zh": "列出所有待批准的股票转移请求。", "sql": "-- 查询待批准的股票转移\nSELECT \n AccountID,\n InstrumentID,\n MovementType,\n MovementQuantity,\n FromAccountID,\n ToAccountID,\n RequestDate,\n ApprovalStatus,\n RequestedBy\nFROM BCAccountInstrumentMovement\nWHERE ApprovalStatus = 'P'\nORDER BY RequestDate DESC;", "schema_info": {"tables": {"BCAccountInstrumentMovement": {"alias": "BCAccountInstrumentMovement", "columns": []}}, "joins": []}, "explanation": "- 股票转移请求存储在专用表中\n- `ApprovalStatus = 'P'` 待批准状态", "question_en": "Show all pending stock movement requests that require approval.", "rating": 6, "execution_result": null, "result_note": "当前查询无待批准请求", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "question_en": "Which clients have requested a change in settlement currency?", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "question_en": "Have there been any margin calls today?", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q36", "question_zh": "各市场(如港股T+1和T+2、美股T+1)的待结算金额是多少?", "sql": "-- 按市场统计待结算金额\nSELECT \n MarketID,\n SUM(DueBuy + DueSell) AS TotalPendingQty,\n SUM(NextDayDueBuy + NextDayDueSell) AS T2TotalPendingQty\nFROM BCAccountInstrument\nWHERE DueBuy > 0 OR DueSell > 0 OR NextDayDueBuy > 0 OR NextDayDueSell > 0\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录各市场的待交收数量\n- `DueBuy/DueSell` 对应T+1交收", "question_en": "What is the pending settlement amount for each market (e.g., HK T+1 & T+2, US T+1)?", "rating": 7, "execution_result": null, "result_note": "| MarketID | TotalPendingQty | T2TotalPendingQty |\n|----------|----------------|------------------|\n| HKEX | 0 | 0 |\n| SETW | 0 | 0 |", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q40", "question_zh": "列出今日执行的所有股票转移/移动。", "sql": "-- 今日股票转入/转出 (固定日期: 2026-04-02)\nSELECT \n AccountID,\n MarketID,\n InstrumentID,\n TodayIn AS QuantityIn,\n TodayOut AS QuantityOut,\n HoldForDeposit AS PendingDeposit,\n HoldForWithdrawal AS PendingWithdrawal\nFROM BCAccountInstrument\nWHERE TodayIn > 0 OR TodayOut > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录股票持仓变动\n- `TodayIn` 今日转入数量", "question_en": "List all stock movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["filter"], "difficulty": "easy"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "question_en": "List all cash movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
{"qid": "Q42", "question_zh": "列出后台系统中的活跃用户。", "sql": "-- 查询后台系统活跃用户\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n u.DepartmentID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储系统用户信息\n- `State = 'A'` 用户状态正常", "question_en": "List active users in the back office.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | AEType |\n|--------|----------|--------|-----------------|---------------|--------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-03 18:53:04 | 个人 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 16:47:11 | 个人 |", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q50", "question_zh": "", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "question_en": "列出今天所有客戶的交易記錄", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---\n\n## 附录:关键表说明\n\n| 表名 | 说明 | 关键字段 |\n|------|------|---------|\n| MCAccount | 账户主表 | AccountID, Name, MarketValue, MarginFacilityFlag |\n| MCUser | 用户表 | UserID, Name, Status, LogonEnableFlag |\n| BCAccountInstrument | 账户持仓 | AccountID, MarketID, Settled, DueBuy, DueSell |\n| BCAccountCash | 账户现金 | AccountID, TodayIn, TodayOut, AccruedInterest |\n| HCAccountMarginCallForDeposit | 追缴保证金 | AccountID, CallForDeposit, CallForDepositDate |\n| MCInstrument | 证券表 | InstrumentID, Name, MarginPercentage |\n| MCInstrumentIPODetail | IPO详情 | InstrumentID, Quantity, SubscriptionAmount |\n| MSBEntitlement | 权益分派 | EntitlementID, BalanceDate, BalanceExDate |\n| MCBroker | 经纪商 | BrokerID, Name |\n| MCLocation | 托管位置 | LocationID, Name, CCASSFlag |\n| HCExchangeRate | 汇率 | ExchangeRateID, ValueDate |\n| HCAccountCashRecord | 现金记录 | AccountID, ValueDate, LedgerBalance |\n\n---\n\n**文档结束**", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,4 +0,0 @@
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
@@ -1,4 +0,0 @@
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q44", "question_zh": "本月收到/支付的利息金额是多少(如客户借款利息和存款利息)?", "sql": "-- 本月利息收支汇总 (2026年4月)\nSELECT \n SUM(AccruedCreditInterest) AS CreditInterest,\n SUM(AccruedDebitInterest) AS DebitInterest,\n SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetInterest\nFROM BCAccountCash;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金和利息信息\n- `AccruedCreditInterest` 应计存款利息", "question_en": "What is the interest amount received/paid this month (e.g., client debit interest and credit interest)?", "rating": 7, "execution_result": null, "result_note": "| CreditInterest | DebitInterest | NetInterest |\n|----------------|---------------|-------------|\n| 464.15 | 2,022.70 | -1,558.55 |", "tags": ["account", "aggregation", "interest"], "difficulty": "easy"}
|
||||
@@ -1 +0,0 @@
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,26 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "question_en": "Which brokers have outstanding delivery obligations to us?", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "question_en": "Which instruments have corporate actions effective tomorrow?", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "question_en": "What dividends are expected to be received today?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "question_en": "Which clients have not yet paid their IPO subscription money?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q13", "question_zh": "列出今日到期的所有股票借贷交易。", "sql": "-- 查询今日到期的股票借贷 (参考日期: 2026-04-02)\n-- MCMarket 表仅包含 HKEX/OSL/SETW,无独立借贷市场标识\n-- 股票借贷可能在持仓变动类型 HoldType 中标识,或在专门的 StockBorrowing 表中\n-- 此 SQL 按 DueBuy/DueSell 显示当前待交收证券,作为借贷合约的近似替代\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.DueBuy AS BorrowQuantity,\n bi.DueSell AS LoanQuantity,\n bi.DueBuy - bi.DueSell AS NetBorrow\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE bi.DueBuy > 0 OR bi.DueSell > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `DueBuy/DueSell` 表示待交收数量(借款买入/借出卖出),反映股票借贷待到期情况\n- `MCMarket` 表无 `MarketType='BORROW'` 标识,现有市场仅为 HKEX/OSL/SETW\n- 股票借贷详情可能存储在 `TSBAccountLoanContract` 或其他借贷专用表中,需业务确认", "question_en": "List all stock borrow/loan transactions due to settle today.", "rating": 5, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 中 DueBuy/DueSell 均为 0,无待交收证券)", "tags": ["join", "trade", "filter"], "difficulty": "medium"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "question_en": "Show all client withdrawals requested but not yet processed.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q18", "question_zh": "今日收到的未清算支票总额是多少?", "sql": "-- 查询未清算支票 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.UnderdueCheque AS OverdueCheque,\n c.NextDayDueCheque AS PendingCheque,\n c.UnderdueCheque + c.NextDayDueCheque AS TotalUncleared\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.UnderdueCheque > 0 OR c.NextDayDueCheque > 0) -- 注意:BCAccountCash 无这两个字段,需确认实际表\nORDER BY TotalUncleared DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 无 `UnderdueCheque` / `NextDayDueCheque` 字段,需业务确认支票数据存储位置", "question_en": "What is the total amount of uncleared cheques received today?", "rating": 4, "execution_result": null, "result_note": "当前查询无未清算支票", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "question_en": "Which corporate action elections are due by end of day?", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "question_en": "Which clients have requested a change in settlement currency?", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "question_en": "Have there been any margin calls today?", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "question_en": "List all cash movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q50", "question_zh": "", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "question_en": "列出今天所有客戶的交易記錄", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---\n\n## 附录:关键表说明\n\n| 表名 | 说明 | 关键字段 |\n|------|------|---------|\n| MCAccount | 账户主表 | AccountID, Name, MarketValue, MarginFacilityFlag |\n| MCUser | 用户表 | UserID, Name, Status, LogonEnableFlag |\n| BCAccountInstrument | 账户持仓 | AccountID, MarketID, Settled, DueBuy, DueSell |\n| BCAccountCash | 账户现金 | AccountID, TodayIn, TodayOut, AccruedInterest |\n| HCAccountMarginCallForDeposit | 追缴保证金 | AccountID, CallForDeposit, CallForDepositDate |\n| MCInstrument | 证券表 | InstrumentID, Name, MarginPercentage |\n| MCInstrumentIPODetail | IPO详情 | InstrumentID, Quantity, SubscriptionAmount |\n| MSBEntitlement | 权益分派 | EntitlementID, BalanceDate, BalanceExDate |\n| MCBroker | 经纪商 | BrokerID, Name |\n| MCLocation | 托管位置 | LocationID, Name, CCASSFlag |\n| HCExchangeRate | 汇率 | ExchangeRateID, ValueDate |\n| HCAccountCashRecord | 现金记录 | AccountID, ValueDate, LedgerBalance |\n\n---\n\n**文档结束**", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,4 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
@@ -1,5 +0,0 @@
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "question_en": "Which clients have exceeded their credit limit?", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q50", "question_zh": "", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "question_en": "列出今天所有客戶的交易記錄", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---\n\n## 附录:关键表说明\n\n| 表名 | 说明 | 关键字段 |\n|------|------|---------|\n| MCAccount | 账户主表 | AccountID, Name, MarketValue, MarginFacilityFlag |\n| MCUser | 用户表 | UserID, Name, Status, LogonEnableFlag |\n| BCAccountInstrument | 账户持仓 | AccountID, MarketID, Settled, DueBuy, DueSell |\n| BCAccountCash | 账户现金 | AccountID, TodayIn, TodayOut, AccruedInterest |\n| HCAccountMarginCallForDeposit | 追缴保证金 | AccountID, CallForDeposit, CallForDepositDate |\n| MCInstrument | 证券表 | InstrumentID, Name, MarginPercentage |\n| MCInstrumentIPODetail | IPO详情 | InstrumentID, Quantity, SubscriptionAmount |\n| MSBEntitlement | 权益分派 | EntitlementID, BalanceDate, BalanceExDate |\n| MCBroker | 经纪商 | BrokerID, Name |\n| MCLocation | 托管位置 | LocationID, Name, CCASSFlag |\n| HCExchangeRate | 汇率 | ExchangeRateID, ValueDate |\n| HCAccountCashRecord | 现金记录 | AccountID, ValueDate, LedgerBalance |\n\n---\n\n**文档结束**", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,7 +0,0 @@
|
||||
{"qid": "Q5", "question_zh": "列出今日发出的所有追收保证金通知及其回复状态。", "sql": "-- 查询今日追缴保证金记录 (参考日期: 2026-04-02)\n-- 使用 MCAccount 的账户级追缴字段(CallForDepositDate = 追缴通知发出日期)\n-- 注意:HCAccountMarginCallForDeposit 是追缴每日快照表,不含\"通知发出日\"字段\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.CallForDeposit AS CallAmount,\n a.CallForDepositDate AS IssueDate,\n a.CallForDepositDays AS OverdueDays\nFROM MCAccount a\nWHERE a.CallForDepositDate = '2026-04-02'\nORDER BY a.CallForDeposit DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.CallForDepositDate` = 追缴通知发出日期,`CallForDeposit` = 追缴金额\n- `CallForDeposit < 0` 表示已结清;如查活跃追缴,应筛选 `CallForDeposit > 0`\n- `HCAccountMarginCallForDeposit` 是追缴每日历史快照,不适合查询\"今日发出的通知\"\n- `CallStatus` 字段在 `HCAccountMarginCallForDeposit` 中不存在", "question_en": "Show all margin calls issued today and their response status.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果(测试环境中 MCAccount 的 `CallForDepositDate` 最新到 2025-10-31,2026-04-02 无追缴通知记录)\n\n> 注:`MCAccount.CallForDeposit` 当前所有值均为负数(已结清的追缴金额),无活跃追缴记录。", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q19", "question_zh": "列出今日起保证金比例发生变动的所有证券。", "sql": "-- 查询保证金比例变动的证券 (固定日期: 2026-04-02)\nSELECT \n i.InstrumentID,\n i.Name AS InstrumentName,\n i.MarginPercentage AS CurrentMarginRatio,\n i.MarginChangeDate\nFROM MCInstrument i\nWHERE i.MarginChangeDate = '2026-04-02'\nORDER BY i.MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument.MarginPercentage` 当前保证金比例\n- `MarginChangeDate` 变动日期", "question_en": "List all instruments with margin ratio changes effective today.", "rating": 7, "execution_result": null, "result_note": "当前查询无保证金比例变动记录", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "question_en": "Have there been any margin calls today?", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,34 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "question_en": "What are the currency exchange rates used for today's settlement?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "question_en": "Which brokers have outstanding delivery obligations to us?", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q5", "question_zh": "列出今日发出的所有追收保证金通知及其回复状态。", "sql": "-- 查询今日追缴保证金记录 (参考日期: 2026-04-02)\n-- 使用 MCAccount 的账户级追缴字段(CallForDepositDate = 追缴通知发出日期)\n-- 注意:HCAccountMarginCallForDeposit 是追缴每日快照表,不含\"通知发出日\"字段\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.CallForDeposit AS CallAmount,\n a.CallForDepositDate AS IssueDate,\n a.CallForDepositDays AS OverdueDays\nFROM MCAccount a\nWHERE a.CallForDepositDate = '2026-04-02'\nORDER BY a.CallForDeposit DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.CallForDepositDate` = 追缴通知发出日期,`CallForDeposit` = 追缴金额\n- `CallForDeposit < 0` 表示已结清;如查活跃追缴,应筛选 `CallForDeposit > 0`\n- `HCAccountMarginCallForDeposit` 是追缴每日历史快照,不适合查询\"今日发出的通知\"\n- `CallStatus` 字段在 `HCAccountMarginCallForDeposit` 中不存在", "question_en": "Show all margin calls issued today and their response status.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果(测试环境中 MCAccount 的 `CallForDepositDate` 最新到 2025-10-31,2026-04-02 无追缴通知记录)\n\n> 注:`MCAccount.CallForDeposit` 当前所有值均为负数(已结清的追缴金额),无活跃追缴记录。", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "question_en": "What dividends are expected to be received today?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "question_en": "Which clients have not yet paid their IPO subscription money?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "question_en": "Show all client withdrawals requested but not yet processed.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "question_en": "Which clients have exceeded their credit limit?", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q18", "question_zh": "今日收到的未清算支票总额是多少?", "sql": "-- 查询未清算支票 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.UnderdueCheque AS OverdueCheque,\n c.NextDayDueCheque AS PendingCheque,\n c.UnderdueCheque + c.NextDayDueCheque AS TotalUncleared\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.UnderdueCheque > 0 OR c.NextDayDueCheque > 0) -- 注意:BCAccountCash 无这两个字段,需确认实际表\nORDER BY TotalUncleared DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 无 `UnderdueCheque` / `NextDayDueCheque` 字段,需业务确认支票数据存储位置", "question_en": "What is the total amount of uncleared cheques received today?", "rating": 4, "execution_result": null, "result_note": "当前查询无未清算支票", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q19", "question_zh": "列出今日起保证金比例发生变动的所有证券。", "sql": "-- 查询保证金比例变动的证券 (固定日期: 2026-04-02)\nSELECT \n i.InstrumentID,\n i.Name AS InstrumentName,\n i.MarginPercentage AS CurrentMarginRatio,\n i.MarginChangeDate\nFROM MCInstrument i\nWHERE i.MarginChangeDate = '2026-04-02'\nORDER BY i.MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument.MarginPercentage` 当前保证金比例\n- `MarginChangeDate` 变动日期", "question_en": "List all instruments with margin ratio changes effective today.", "rating": 7, "execution_result": null, "result_note": "当前查询无保证金比例变动记录", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "question_en": "How many client statements were successfully generated but not yet delivered?", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
{"qid": "Q25", "question_zh": "列出所有待批准的股票转移请求。", "sql": "-- 查询待批准的股票转移\nSELECT \n AccountID,\n InstrumentID,\n MovementType,\n MovementQuantity,\n FromAccountID,\n ToAccountID,\n RequestDate,\n ApprovalStatus,\n RequestedBy\nFROM BCAccountInstrumentMovement\nWHERE ApprovalStatus = 'P'\nORDER BY RequestDate DESC;", "schema_info": {"tables": {"BCAccountInstrumentMovement": {"alias": "BCAccountInstrumentMovement", "columns": []}}, "joins": []}, "explanation": "- 股票转移请求存储在专用表中\n- `ApprovalStatus = 'P'` 待批准状态", "question_en": "Show all pending stock movement requests that require approval.", "rating": 6, "execution_result": null, "result_note": "当前查询无待批准请求", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "question_en": "Which clients have requested a change in settlement currency?", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q42", "question_zh": "列出后台系统中的活跃用户。", "sql": "-- 查询后台系统活跃用户\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n u.DepartmentID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储系统用户信息\n- `State = 'A'` 用户状态正常", "question_en": "List active users in the back office.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | AEType |\n|--------|----------|--------|-----------------|---------------|--------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-03 18:53:04 | 个人 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 16:47:11 | 个人 |", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q50", "question_zh": "", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "question_en": "列出今天所有客戶的交易記錄", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---\n\n## 附录:关键表说明\n\n| 表名 | 说明 | 关键字段 |\n|------|------|---------|\n| MCAccount | 账户主表 | AccountID, Name, MarketValue, MarginFacilityFlag |\n| MCUser | 用户表 | UserID, Name, Status, LogonEnableFlag |\n| BCAccountInstrument | 账户持仓 | AccountID, MarketID, Settled, DueBuy, DueSell |\n| BCAccountCash | 账户现金 | AccountID, TodayIn, TodayOut, AccruedInterest |\n| HCAccountMarginCallForDeposit | 追缴保证金 | AccountID, CallForDeposit, CallForDepositDate |\n| MCInstrument | 证券表 | InstrumentID, Name, MarginPercentage |\n| MCInstrumentIPODetail | IPO详情 | InstrumentID, Quantity, SubscriptionAmount |\n| MSBEntitlement | 权益分派 | EntitlementID, BalanceDate, BalanceExDate |\n| MCBroker | 经纪商 | BrokerID, Name |\n| MCLocation | 托管位置 | LocationID, Name, CCASSFlag |\n| HCExchangeRate | 汇率 | ExchangeRateID, ValueDate |\n| HCAccountCashRecord | 现金记录 | AccountID, ValueDate, LedgerBalance |\n\n---\n\n**文档结束**", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1 +0,0 @@
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "question_en": "How many client statements were successfully generated but not yet delivered?", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
@@ -1,6 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q13", "question_zh": "列出今日到期的所有股票借贷交易。", "sql": "-- 查询今日到期的股票借贷 (参考日期: 2026-04-02)\n-- MCMarket 表仅包含 HKEX/OSL/SETW,无独立借贷市场标识\n-- 股票借贷可能在持仓变动类型 HoldType 中标识,或在专门的 StockBorrowing 表中\n-- 此 SQL 按 DueBuy/DueSell 显示当前待交收证券,作为借贷合约的近似替代\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.DueBuy AS BorrowQuantity,\n bi.DueSell AS LoanQuantity,\n bi.DueBuy - bi.DueSell AS NetBorrow\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE bi.DueBuy > 0 OR bi.DueSell > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `DueBuy/DueSell` 表示待交收数量(借款买入/借出卖出),反映股票借贷待到期情况\n- `MCMarket` 表无 `MarketType='BORROW'` 标识,现有市场仅为 HKEX/OSL/SETW\n- 股票借贷详情可能存储在 `TSBAccountLoanContract` 或其他借贷专用表中,需业务确认", "question_en": "List all stock borrow/loan transactions due to settle today.", "rating": 5, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 中 DueBuy/DueSell 均为 0,无待交收证券)", "tags": ["join", "trade", "filter"], "difficulty": "medium"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q31", "question_zh": "指定日期或日期范围内收到的交易量(如成交金额)及相应佣金是多少?", "sql": "-- 交易量和佣金统计\nSELECT \n SUM(TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(TotalBoughtFee) AS TotalBuyCommission,\n SUM(TotalSoldConsideration) AS TotalSellConsideration,\n SUM(TotalSoldFee) AS TotalSellCommission,\n SUM(TotalBoughtConsideration) + SUM(TotalSoldConsideration) AS TotalConsideration,\n SUM(TotalBoughtFee) + SUM(TotalSoldFee) AS TotalCommission\nFROM BCAccountInstrument;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录了账户所有历史买卖交易\n- `TotalBoughtConsideration / TotalSoldConsideration`: 买卖成交金额", "question_en": "What is the trading volume (e.g., consideration) and corresponding commission amount received for a specific date or date range?", "rating": 9, "execution_result": null, "result_note": "| TotalBuyConsideration | TotalBuyCommission | TotalSellConsideration | TotalSellCommission | TotalConsideration | TotalCommission |\n|---------------------|-------------------|----------------------|--------------------|-------------------|-----------------|\n| 945,480,833.78 | 793,149.07 | 278,693,891.64 | 809,248.89 | 1,224,174,725.42 | 1,602,397.96 |", "tags": ["trade", "aggregation"], "difficulty": "easy"}
|
||||
@@ -1,2 +0,0 @@
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
@@ -1,29 +0,0 @@
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "question_en": "What are the currency exchange rates used for today's settlement?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "question_en": "Which brokers have outstanding delivery obligations to us?", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q5", "question_zh": "列出今日发出的所有追收保证金通知及其回复状态。", "sql": "-- 查询今日追缴保证金记录 (参考日期: 2026-04-02)\n-- 使用 MCAccount 的账户级追缴字段(CallForDepositDate = 追缴通知发出日期)\n-- 注意:HCAccountMarginCallForDeposit 是追缴每日快照表,不含\"通知发出日\"字段\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.CallForDeposit AS CallAmount,\n a.CallForDepositDate AS IssueDate,\n a.CallForDepositDays AS OverdueDays\nFROM MCAccount a\nWHERE a.CallForDepositDate = '2026-04-02'\nORDER BY a.CallForDeposit DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.CallForDepositDate` = 追缴通知发出日期,`CallForDeposit` = 追缴金额\n- `CallForDeposit < 0` 表示已结清;如查活跃追缴,应筛选 `CallForDeposit > 0`\n- `HCAccountMarginCallForDeposit` 是追缴每日历史快照,不适合查询\"今日发出的通知\"\n- `CallStatus` 字段在 `HCAccountMarginCallForDeposit` 中不存在", "question_en": "Show all margin calls issued today and their response status.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果(测试环境中 MCAccount 的 `CallForDepositDate` 最新到 2025-10-31,2026-04-02 无追缴通知记录)\n\n> 注:`MCAccount.CallForDeposit` 当前所有值均为负数(已结清的追缴金额),无活跃追缴记录。", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "question_en": "Which instruments have corporate actions effective tomorrow?", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "question_en": "What dividends are expected to be received today?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q14", "question_zh": "列出已申请但尚未处理的客户提款请求。", "sql": "-- 查询待处理提款申请 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.TodayOut AS WithdrawalAmount,\n c.BankAvailableBalance AS AvailableBalance,\n c.State AS RecordStatus\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.TodayOut > 0\nORDER BY c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `TodayOut` 今日计划支出\n- 待处理提款申请应体现在此字段", "question_en": "Show all client withdrawals requested but not yet processed.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q17", "question_zh": "哪些客户已超过其信用额度?", "sql": "-- 查询超信用额度客户(使用 MarginLimit)\n-- 注意:MCAccount 无 CreditLimit 字段,应用 MarginLimit\nSELECT \n AccountID,\n Name AS AccountName,\n MarginLimit,\n MarketValue,\n MarginLimit - MarketValue AS AvailableCredit,\n CASE \n WHEN MarketValue > MarginLimit THEN '超额'\n WHEN MarketValue > MarginLimit * 0.8 THEN '接近限额'\n ELSE '正常'\n END AS Status\nFROM MCAccount\nWHERE MarginLimit > 0\n AND MarketValue > MarginLimit * 0.8\nORDER BY (MarketValue - MarginLimit) DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.MarginLimit` 保证金/信用限额(注意:无 `CreditLimit` 字段)\n- `MCAccount.MarketValue` 持仓市值\n- `MarginBLimit` 是单独借款限额,注意区分", "question_en": "Which clients have exceeded their credit limit?", "rating": 7, "execution_result": null, "result_note": "当前查询无超限客户", "tags": ["account", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q18", "question_zh": "今日收到的未清算支票总额是多少?", "sql": "-- 查询未清算支票 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.UnderdueCheque AS OverdueCheque,\n c.NextDayDueCheque AS PendingCheque,\n c.UnderdueCheque + c.NextDayDueCheque AS TotalUncleared\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.UnderdueCheque > 0 OR c.NextDayDueCheque > 0) -- 注意:BCAccountCash 无这两个字段,需确认实际表\nORDER BY TotalUncleared DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 无 `UnderdueCheque` / `NextDayDueCheque` 字段,需业务确认支票数据存储位置", "question_en": "What is the total amount of uncleared cheques received today?", "rating": 4, "execution_result": null, "result_note": "当前查询无未清算支票", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q19", "question_zh": "列出今日起保证金比例发生变动的所有证券。", "sql": "-- 查询保证金比例变动的证券 (固定日期: 2026-04-02)\nSELECT \n i.InstrumentID,\n i.Name AS InstrumentName,\n i.MarginPercentage AS CurrentMarginRatio,\n i.MarginChangeDate\nFROM MCInstrument i\nWHERE i.MarginChangeDate = '2026-04-02'\nORDER BY i.MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument.MarginPercentage` 当前保证金比例\n- `MarginChangeDate` 变动日期", "question_en": "List all instruments with margin ratio changes effective today.", "rating": 7, "execution_result": null, "result_note": "当前查询无保证金比例变动记录", "tags": ["margin", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "question_en": "Which corporate action elections are due by end of day?", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q24", "question_zh": "有多少客户报表已生成成功但尚未发送?", "sql": "-- 查询已生成但未发送的报表\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n a.LastDailyStatementDate,\n a.LastMonthlyStatementDate,\n a.LastStatementGenerateTime,\n a.LastStatementSendTime,\n CASE \n WHEN a.LastStatementGenerateTime > a.LastStatementSendTime THEN '未发送'\n ELSE '已发送'\n END AS DeliveryStatus\nFROM MCAccount a\nWHERE a.LastStatementGenerateTime IS NOT NULL\n AND (a.LastStatementSendTime IS NULL \n OR a.LastStatementGenerateTime > a.LastStatementSendTime)\nORDER BY a.LastStatementGenerateTime DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `LastStatementGenerateTime` 报表生成时间\n- `LastStatementSendTime` 报表发送时间", "question_en": "How many client statements were successfully generated but not yet delivered?", "rating": 7, "execution_result": null, "result_note": "当前查询无未发送报表", "tags": ["ordering", "account", "filter", "statement"], "difficulty": "easy"}
|
||||
{"qid": "Q25", "question_zh": "列出所有待批准的股票转移请求。", "sql": "-- 查询待批准的股票转移\nSELECT \n AccountID,\n InstrumentID,\n MovementType,\n MovementQuantity,\n FromAccountID,\n ToAccountID,\n RequestDate,\n ApprovalStatus,\n RequestedBy\nFROM BCAccountInstrumentMovement\nWHERE ApprovalStatus = 'P'\nORDER BY RequestDate DESC;", "schema_info": {"tables": {"BCAccountInstrumentMovement": {"alias": "BCAccountInstrumentMovement", "columns": []}}, "joins": []}, "explanation": "- 股票转移请求存储在专用表中\n- `ApprovalStatus = 'P'` 待批准状态", "question_en": "Show all pending stock movement requests that require approval.", "rating": 6, "execution_result": null, "result_note": "当前查询无待批准请求", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q28", "question_zh": "哪些客户已请求更改结算货币?", "sql": "-- 查询请求更改结算货币的客户\n-- 说明:经查 MCAccountCurrency 表无 CurrencyChangeStatus/RequestedCurrencyID 等字段\n-- 数据库中没有专门的货币变更请求表\n-- 此查询基于账户货币历史时间表(HCAccountCurrencyTimetable)展示货币生效安排\nSELECT \n act.AccountID,\n mca.Name AS AccountName,\n act.CurrencyID AS Currency,\n act.EffectiveDateFrom,\n act.EffectiveDateTo,\n act.AccountTypeID\nFROM HCAccountCurrencyTimetable act\nINNER JOIN MCAccount mca ON act.AccountID = mca.AccountID\nWHERE act.EffectiveDateTo IS NULL\nORDER BY act.EffectiveDateFrom DESC;", "schema_info": {"tables": {"HCAccountCurrencyTimetable": {"alias": "act", "columns": []}, "MCAccount": {"alias": "mca", "columns": []}}, "joins": [{"type": "INNER", "on": "act.AccountID = mca.AccountID"}]}, "explanation": "- `HCAccountCurrencyTimetable` 记录账户货币生效时间表\n- `EffectiveDateTo IS NULL` 表示当前生效的货币配置\n- 如需货币变更请求功能,建议在系统中扩展相关表结构", "question_en": "Which clients have requested a change in settlement currency?", "rating": 4, "execution_result": null, "result_note": "**说明:** 数据库中没有专门的货币变更请求表。`MCAccountCurrency` 表仅记录账户当前货币配置,无变更请求字段。", "tags": ["join", "account", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q31", "question_zh": "指定日期或日期范围内收到的交易量(如成交金额)及相应佣金是多少?", "sql": "-- 交易量和佣金统计\nSELECT \n SUM(TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(TotalBoughtFee) AS TotalBuyCommission,\n SUM(TotalSoldConsideration) AS TotalSellConsideration,\n SUM(TotalSoldFee) AS TotalSellCommission,\n SUM(TotalBoughtConsideration) + SUM(TotalSoldConsideration) AS TotalConsideration,\n SUM(TotalBoughtFee) + SUM(TotalSoldFee) AS TotalCommission\nFROM BCAccountInstrument;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录了账户所有历史买卖交易\n- `TotalBoughtConsideration / TotalSoldConsideration`: 买卖成交金额", "question_en": "What is the trading volume (e.g., consideration) and corresponding commission amount received for a specific date or date range?", "rating": 9, "execution_result": null, "result_note": "| TotalBuyConsideration | TotalBuyCommission | TotalSellConsideration | TotalSellCommission | TotalConsideration | TotalCommission |\n|---------------------|-------------------|----------------------|--------------------|-------------------|-----------------|\n| 945,480,833.78 | 793,149.07 | 278,693,891.64 | 809,248.89 | 1,224,174,725.42 | 1,602,397.96 |", "tags": ["trade", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "question_en": "Have there been any margin calls today?", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q38", "question_zh": "本月IPO事件的总佣金、手续费和保证金利息是多少?", "sql": "-- IPO相关费用汇总 (2026年4月)\nSELECT \n 'IPO Commission' AS FeeType,\n SUM(ip.SubscriptionAmount * 0.001) AS EstimatedFee\nFROM MCInstrumentIPODetail ip\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": []}, "explanation": "- IPO相关费用分散在多个表中\n- 需要关联 `BCAccountInstrument` 获取IPO交易费用", "question_en": "What are the total commission, handling fees, and margin interest for IPO events this month?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["margin", "aggregation", "filter", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q40", "question_zh": "列出今日执行的所有股票转移/移动。", "sql": "-- 今日股票转入/转出 (固定日期: 2026-04-02)\nSELECT \n AccountID,\n MarketID,\n InstrumentID,\n TodayIn AS QuantityIn,\n TodayOut AS QuantityOut,\n HoldForDeposit AS PendingDeposit,\n HoldForWithdrawal AS PendingWithdrawal\nFROM BCAccountInstrument\nWHERE TodayIn > 0 OR TodayOut > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录股票持仓变动\n- `TodayIn` 今日转入数量", "question_en": "List all stock movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["filter"], "difficulty": "easy"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "question_en": "List all cash movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
{"qid": "Q42", "question_zh": "列出后台系统中的活跃用户。", "sql": "-- 查询后台系统活跃用户\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n u.DepartmentID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储系统用户信息\n- `State = 'A'` 用户状态正常", "question_en": "List active users in the back office.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | AEType |\n|--------|----------|--------|-----------------|---------------|--------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-03 18:53:04 | 个人 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 16:47:11 | 个人 |", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q44", "question_zh": "本月收到/支付的利息金额是多少(如客户借款利息和存款利息)?", "sql": "-- 本月利息收支汇总 (2026年4月)\nSELECT \n SUM(AccruedCreditInterest) AS CreditInterest,\n SUM(AccruedDebitInterest) AS DebitInterest,\n SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetInterest\nFROM BCAccountCash;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金和利息信息\n- `AccruedCreditInterest` 应计存款利息", "question_en": "What is the interest amount received/paid this month (e.g., client debit interest and credit interest)?", "rating": 7, "execution_result": null, "result_note": "| CreditInterest | DebitInterest | NetInterest |\n|----------------|---------------|-------------|\n| 464.15 | 2,022.70 | -1,558.55 |", "tags": ["account", "aggregation", "interest"], "difficulty": "easy"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q50", "question_zh": "", "sql": "SELECT TOP\n\t15 c.ContractID,\n\tc.TradeDate,\n\tLTRIM( RTRIM( c.AccountID ) ) AS AccountID,\n\tLTRIM( RTRIM( c.MarketID ) ) AS MarketID,\n\tc.InstrumentID,\n\tc.BuySell,\n\tc.Quantity,\n\tc.Consideration,\n\tLTRIM( RTRIM( c.CurrencyID ) ) AS CurrencyID \nFROM\n\tdbo.TSBAccountContract c\n\tINNER JOIN dbo.MCAccount a ON c.AccountID = a.AccountID \nWHERE\n\tCAST ( c.TradeDate AS DATE ) = '2026-04-02' \n\tAND LTRIM( RTRIM( a.HouseAccountFlag ) ) = 'N' \nORDER BY\n\tc.ContractID;", "schema_info": {"tables": {"TSBAccountContract": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "", "question_en": "列出今天所有客戶的交易記錄", "rating": null, "execution_result": null, "result_note": "| ContractID | TradeDate | AccountID | MarketID | InstrumentID | BuySell | Quantity | Consideration | CurrencyID |\n| :--------- | :--------- | :-------- | :------- | :----------- | :------ | :------- | :------------ | :--------- |\n| B02403846 | 2026-04-02 | P011206 | HKEX | 01810 | B | 600 | 18360 | HKD |\n| B02403847 | 2026-04-02 | P011202 | HKEX | 01810 | B | 200 | 6120 | HKD |\n\n\n\n\n\n---\n\n## 附录:关键表说明\n\n| 表名 | 说明 | 关键字段 |\n|------|------|---------|\n| MCAccount | 账户主表 | AccountID, Name, MarketValue, MarginFacilityFlag |\n| MCUser | 用户表 | UserID, Name, Status, LogonEnableFlag |\n| BCAccountInstrument | 账户持仓 | AccountID, MarketID, Settled, DueBuy, DueSell |\n| BCAccountCash | 账户现金 | AccountID, TodayIn, TodayOut, AccruedInterest |\n| HCAccountMarginCallForDeposit | 追缴保证金 | AccountID, CallForDeposit, CallForDepositDate |\n| MCInstrument | 证券表 | InstrumentID, Name, MarginPercentage |\n| MCInstrumentIPODetail | IPO详情 | InstrumentID, Quantity, SubscriptionAmount |\n| MSBEntitlement | 权益分派 | EntitlementID, BalanceDate, BalanceExDate |\n| MCBroker | 经纪商 | BrokerID, Name |\n| MCLocation | 托管位置 | LocationID, Name, CCASSFlag |\n| HCExchangeRate | 汇率 | ExchangeRateID, ValueDate |\n| HCAccountCashRecord | 现金记录 | AccountID, ValueDate, LedgerBalance |\n\n---\n\n**文档结束**", "tags": ["join", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
@@ -1,15 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q11", "question_zh": "哪些客户尚未缴纳IPO申购款?", "sql": "-- 查询未缴纳IPO申购款的账户\nSELECT \n a.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.TotalBoughtQuantity AS SubscriptionLot,\n bi.TotalBoughtConsideration AS SubscriptionAmount\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nINNER JOIN MCInstrumentIPODetail ip ON bi.InstrumentID = ip.InstrumentID\nWHERE ip.State = 'A'\n AND bi.TotalBoughtConsideration > 0\n AND bi.TotalBoughtFee = 0\nORDER BY bi.TotalBoughtConsideration DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}, {"type": "INNER", "on": "bi.InstrumentID = ip.InstrumentID"}]}, "explanation": "- 通过比对买卖数量和手续费判断是否缴款\n- `TotalBoughtConsideration > 0` 有认购\n- `TotalBoughtFee = 0` 未支付手续费", "question_en": "Which clients have not yet paid their IPO subscription money?", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "ordering"], "difficulty": "hard"}
|
||||
{"qid": "Q15", "question_zh": "本月应付给介绍经纪人的佣金返佣总额是多少?", "sql": "-- 查询本月应付返佣 (2026年4月)\n-- 注意:BCAccountInstrument 无 UpdatedAt 字段,用 LastTransactionDate 过滤本月有交易的账户\n-- 说明:TotalBoughtFee/TotalSoldFee 为历史累计字段,此处统计近期活跃账户的累计佣金供参考\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE YEAR(bi.LastTransactionDate) = 2026\n AND MONTH(bi.LastTransactionDate) = 4\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee + bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCRebateScheme` 可能存储返佣规则\n- 按AE汇总佣金", "question_en": "What is the total commission rebate payable to introducing brokers this month?", "rating": 6, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q22", "question_zh": "列出今日所有公司账户与客户账户之间的现金划转。", "sql": "-- 查询公司账户与客户账户现金划转 (固定日期: 2026-04-02)\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n a.AccountType,\n c.CurrencyID,\n c.TodayIn AS CashInflow,\n c.TodayOut AS CashOutflow,\n c.Settled AS CurrentBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE (c.TodayIn > 0 OR c.TodayOut > 0)\nORDER BY c.TodayIn + c.TodayOut DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- 公司账户与客户账户通过 `AccountType` 区分\n- `TodayIn/TodayOut` 记录现金流动", "question_en": "List all cash movements between house and client accounts today.", "rating": 7, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q45", "question_zh": "不同经纪商(如非中央结算系统持仓)的客户总持仓是多少?", "sql": "-- 按托管位置统计持仓(非CCASS)\nSELECT \n loc.LocationID,\n loc.Name AS LocationName,\n COUNT(DISTINCT bi.AccountID) AS AccountCount,\n SUM(bi.Settled) AS TotalQuantity,\n SUM(bi.CostAmount) AS TotalCostAmount\nFROM BCAccountLocationInstrument bi\nINNER JOIN MCLocation loc ON bi.LocationID = loc.LocationID\nWHERE loc.CCASSFlag = 'N'\nGROUP BY loc.LocationID, loc.Name\nORDER BY TotalQuantity DESC;", "schema_info": {"tables": {"BCAccountLocationInstrument": {"alias": "bi", "columns": []}, "MCLocation": {"alias": "loc", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.LocationID = loc.LocationID"}]}, "explanation": "- `BCAccountLocationInstrument` 记录按托管位置分类的持仓\n- `MCLocation` 存储托管位置信息", "question_en": "What is the total client holding at different broker firms (e.g., non-CCASS locations)?", "rating": 7, "execution_result": null, "result_note": "当前查询需要验证 Location 表关联", "tags": ["join", "ordering", "holding", "broker", "filter", "account", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q46", "question_zh": "支付给其他经纪商的佣金是多少?", "sql": "-- 查询支付给其他经纪商的佣金\nSELECT \n b.BrokerID,\n b.Name AS BrokerName,\n SUM(bc.Commission) AS TotalCommission,\n SUM(bc.Consideration) AS TotalConsideration\nFROM MCBroker b\nINNER JOIN BCBrokerCash bc ON b.BrokerID = bc.BrokerID\nWHERE bc.Commission > 0\nGROUP BY b.BrokerID, b.Name\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCBroker": {"alias": "b", "columns": []}, "BCBrokerCash": {"alias": "bc", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = bc.BrokerID"}]}, "explanation": "- `MCBroker` 存储经纪商信息\n- `BCBrokerCash` 可能包含经纪商现金和佣金数据", "question_en": "How much commission has been paid to other brokers?", "rating": 6, "execution_result": null, "result_note": "当前查询需要验证经纪商佣金表关联", "tags": ["join", "ordering", "broker", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
@@ -1,6 +0,0 @@
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q12", "question_zh": "本月累计的结算失败罚金是多少?", "sql": "-- 查询本月结算失败罚金 (2026年4月)\n-- 注意:BCAccountInstrument 无 FailedTradePenalty 字段,需另找结算罚金存储位置\n-- 目前未找到结算失败罚金字段,建议通过 TSBBrokerContract 或 BCBrokerCash 进一步排查\nSELECT \n COUNT(*) AS FailedTradeCount,\n MarketID\nFROM BCAccountInstrument\nWHERE YEAR(LastTransactionDate) = 2026\n AND MONTH(LastTransactionDate) = 4\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 无 `FailedTradePenalty` 字段,原始 SQL 会报错\n- `TSBBrokerContract` 或 `BCBrokerCash` 中可能存储结算相关费用,需进一步确认", "question_en": "What is the total failed trade penalty incurred this month?", "rating": 3, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 表无 FailedTradePenalty 字段,无法统计结算罚金)", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q13", "question_zh": "列出今日到期的所有股票借贷交易。", "sql": "-- 查询今日到期的股票借贷 (参考日期: 2026-04-02)\n-- MCMarket 表仅包含 HKEX/OSL/SETW,无独立借贷市场标识\n-- 股票借贷可能在持仓变动类型 HoldType 中标识,或在专门的 StockBorrowing 表中\n-- 此 SQL 按 DueBuy/DueSell 显示当前待交收证券,作为借贷合约的近似替代\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.DueBuy AS BorrowQuantity,\n bi.DueSell AS LoanQuantity,\n bi.DueBuy - bi.DueSell AS NetBorrow\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE bi.DueBuy > 0 OR bi.DueSell > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `DueBuy/DueSell` 表示待交收数量(借款买入/借出卖出),反映股票借贷待到期情况\n- `MCMarket` 表无 `MarketType='BORROW'` 标识,现有市场仅为 HKEX/OSL/SETW\n- 股票借贷详情可能存储在 `TSBAccountLoanContract` 或其他借贷专用表中,需业务确认", "question_en": "List all stock borrow/loan transactions due to settle today.", "rating": 5, "execution_result": null, "result_note": "当前查询无结果(BCAccountInstrument 中 DueBuy/DueSell 均为 0,无待交收证券)", "tags": ["join", "trade", "filter"], "difficulty": "medium"}
|
||||
{"qid": "Q16", "question_zh": "列出T+2交易缺少结算指令的账户。", "sql": "-- 查询T+2待交收但缺少指令的账户\n-- 注意:BCAccountInstrumentInstruction 表不存在,需改用 TSBSettlementInstruction\nSELECT \n bi.AccountID,\n a.Name AS AccountName,\n bi.InstrumentID,\n i.Name AS InstrumentName,\n bi.NextDayDueBuy AS T2DueBuy,\n bi.NextDayDueSell AS T2DueSell\nFROM BCAccountInstrument bi\nINNER JOIN MCAccount a ON bi.AccountID = a.AccountID\nINNER JOIN MCInstrument i ON bi.InstrumentID = i.InstrumentID\nWHERE (bi.NextDayDueBuy > 0 OR bi.NextDayDueSell > 0)\n AND NOT EXISTS (\n SELECT 1 FROM TSBSettlementInstruction si\n WHERE si.AccountOrBrokerID = bi.AccountID\n AND si.InstrumentID = bi.InstrumentID\n AND si.State IN ('P','A')\n );", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCAccount": {"alias": "a", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}, "TSBSettlementInstruction": {"alias": "si", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.AccountID = a.AccountID"}, {"type": "INNER", "on": "bi.InstrumentID = i.InstrumentID"}]}, "explanation": "- `NextDayDueBuy/NextDayDueSell` T+2交收数量(次日到期)\n- `TSBSettlementInstruction` 是结算指令表,通过 `NOT EXISTS` 排除已有指令的记录\n- `BCAccountInstrumentInstruction` 表不存在,不能使用", "question_en": "Show accounts where settlement instruction is missing for T+2 trades.", "rating": 6, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "account", "filter", "trade"], "difficulty": "medium"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q36", "question_zh": "各市场(如港股T+1和T+2、美股T+1)的待结算金额是多少?", "sql": "-- 按市场统计待结算金额\nSELECT \n MarketID,\n SUM(DueBuy + DueSell) AS TotalPendingQty,\n SUM(NextDayDueBuy + NextDayDueSell) AS T2TotalPendingQty\nFROM BCAccountInstrument\nWHERE DueBuy > 0 OR DueSell > 0 OR NextDayDueBuy > 0 OR NextDayDueSell > 0\nGROUP BY MarketID;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录各市场的待交收数量\n- `DueBuy/DueSell` 对应T+1交收", "question_en": "What is the pending settlement amount for each market (e.g., HK T+1 & T+2, US T+1)?", "rating": 7, "execution_result": null, "result_note": "| MarketID | TotalPendingQty | T2TotalPendingQty |\n|----------|----------------|------------------|\n| HKEX | 0 | 0 |\n| SETW | 0 | 0 |", "tags": ["filter", "aggregation"], "difficulty": "medium"}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,30 +0,0 @@
|
||||
{"qid": "Q1", "question_zh": "按对手方列出截至[日期]的所有未结算交易。", "sql": "-- 按对手方统计截至 2026-04-02 的未结算交易\n-- 使用 TSBBrokerContract(经纪商合约表),按 BrokerID(对手方经纪商)分组\n-- SettleStatus='U' 表示未结算;CashSettleDate <= '2026-04-02' 筛选截至日\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n COUNT(*) AS UnsettledTradeCount,\n SUM(b.SettleQuantity) AS TotalUnsettledQty,\n SUM(b.SettleAmount) AS TotalUnsettledAmount,\n MIN(b.BuySell) + '~' + MAX(b.BuySell) AS BuySellRange,\n MIN(b.CashSettleDate) AS EarliestSettleDate,\n MAX(b.CashSettleDate) AS LatestSettleDate\nFROM TSBBrokerContract b\nLEFT JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.SettleStatus = 'U'\n AND b.CashSettleDate <= '2026-04-02'\nGROUP BY b.BrokerID, m.Name\nORDER BY TotalUnsettledAmount DESC;", "schema_info": {"tables": {"TSBBrokerContract": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "LEFT", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `TSBBrokerContract` 是经纪商/对手方合约表,记录与外部对手方的交易合约,`BrokerID` 即对手方标识\n- `SettleStatus = 'U'` 表示未结算;`CashSettleDate <= '2026-04-02'` 筛选截至日未结清的合约\n- 关联 `MCBroker` 获取对手方经纪商名称\n- 按 `BrokerID` 分组汇总未结算数量和金额", "question_en": "Show all unsettled trades as of [date] grouped by counterparty.", "rating": 9, "execution_result": null, "result_note": "| BrokerID | BrokerName | UnsettledTradeCount | TotalUnsettledQty | TotalUnsettledAmount | BuySellRange | EarliestSettleDate | LatestSettleDate |\n|----------|-----------|---------------------|-------------------|---------------------|--------------|---------------------|-------------------|\n| CCASS | CCASS | 622 | 40,459,253 | 44,173,571.06 | B~S | 2025-07-30 | 2026-04-02 |\n\n> **注**:CCASS(Hong Kong Securities Clearing Company Limited)是香港交易所的中央结算机构,作为交易所交易的核心对手方。622笔未结算合约均为 HKEX 市场。", "tags": ["join", "ordering", "broker", "filter", "trade", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q2", "question_zh": "列出今日所有客户账户之间的股票转移记录。", "sql": "-- 查询今日客户账户间股票转移(参考日期:2026-04-02)\n-- 使用 TSBAccountInstrumentMovement,MovementType='T' 表示账户间转移\n-- ValueDate 为转移生效日期,关联 MCInstrument 获取证券名称\nSELECT \n m.MovementID,\n m.AccountID AS FromAccountID,\n m.TransferToAccountID,\n m.InstrumentID,\n i.Name AS InstrumentSymbol,\n m.MovementType,\n m.Quantity AS TransferQuantity,\n m.ValueDate AS TransferDate\nFROM TSBAccountInstrumentMovement m\nLEFT JOIN MCInstrument i ON m.InstrumentID = i.InstrumentID\nWHERE m.MovementType = 'T'\n AND m.ValueDate = '2026-04-02'\nORDER BY m.ValueDate;", "schema_info": {"tables": {"TSBAccountInstrumentMovement": {"alias": "m", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "LEFT", "on": "m.InstrumentID = i.InstrumentID"}]}, "explanation": "- `TSBAccountInstrumentMovement` 是持仓变动流水表,记录所有证券变动事件\n- `MovementType = 'T'`(Transfer)特指**账户间股票转移**,对应 `TransferToAccountID` 记录目标账户\n- `ValueDate` 是转移生效日期,可按日期过滤\n- 关联 `MCInstrument` 获取证券代码/名称\n- 注意:`BCAccountInstrument` 的 `TodayIn/TodayOut` 是**实时快照**,不带历史日期维度,不能用于查历史转移", "question_en": "List all stock transfers between client accounts performed today.", "rating": 9, "execution_result": null, "result_note": "当前查询无结果(测试环境中 `TSBAccountInstrumentMovement` 的 `MovementType='T'` 最新记录为 2025-10-21,无 2026-04-02 的账户间转移数据)", "tags": ["join", "ordering", "filter", "account", "left_join"], "difficulty": "hard"}
|
||||
{"qid": "Q3", "question_zh": "今日结算使用的汇率是多少?", "sql": "-- 查询汇率类型列表 (固定日期: 2026-04-02)\nSELECT \n ExchangeRateID, \n Name, \n NameEx\nFROM HCExchangeRate\nWHERE ValueDate = '2026-04-02'\nORDER BY ExchangeRateID;", "schema_info": {"tables": {"HCExchangeRate": {"alias": "HCExchangeRate", "columns": []}}, "joins": []}, "explanation": "- `HCExchangeRate` 存储汇率类型定义\n- `HCExchangeRateDetail` 存储各货币对的汇率值\n- 两个表通过 `ExchangeRateID` + `ValueDate` 关联\n- `ExchangeRateDirection` = 'D' 表示直接汇率", "question_en": "What are the currency exchange rates used for today's settlement?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["exchange_rate", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q4", "question_zh": "哪些券商尚有未履行的交收义务?", "sql": "-- 查询有未履行交收义务的经纪商(截至 2026-04-02)\n-- Settled < 0 表示经纪商欠我们的现金(未履行交收义务)\n-- 注意:BCBrokerCash.Settled 是经纪商在我们账户的已结算现金余额,负数=经纪商欠款\nSELECT \n b.BrokerID,\n m.Name AS BrokerName,\n b.CurrencyID,\n b.Settled AS OwedToUsAmount,\n ABS(b.Settled) AS OutstandingAmount\nFROM BCBrokerCash b\nINNER JOIN MCBroker m ON b.BrokerID = m.BrokerID\nWHERE b.Settled < 0\nORDER BY ABS(b.Settled) DESC;", "schema_info": {"tables": {"BCBrokerCash": {"alias": "b", "columns": []}, "MCBroker": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "b.BrokerID = m.BrokerID"}]}, "explanation": "- `BCBrokerCash` 记录经纪商在我们账户的结算现金,`Settled < 0` = 经纪商欠我们(未履行交收义务)\n- 关联 `MCBroker` 获取经纪商名称\n- 按欠款金额降序排列,优先处理大额欠款", "question_en": "Which brokers have outstanding delivery obligations to us?", "rating": 8, "execution_result": null, "result_note": "| BrokerID | BrokerName | CurrencyID | OwedToUsAmount | OutstandingAmount |\n|----------|-----------|------------|-----------------|-------------------|\n| CCASS | CCASS | CNY | -52,680.00 | 52,680.00 |\n| CCASS | CCASS | USD | -90.00 | 90.00 |\n\n> 注:CCASS 欠我们的结算现金(CNY 52,680 + USD 90)。HKD 余额为正(+4,202,811.87)表示我们欠 CCASS,不属于\"未履行交收义务\"范畴。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q6", "question_zh": "所有货币的客户现金总余额是多少?", "sql": "-- 按货币统计客户现金余额\nSELECT \n CurrencyID,\n COUNT(DISTINCT AccountID) AS AccountCount,\n SUM(Settled) AS TotalSettledBalance,\n SUM(AccruedCreditInterest) AS TotalCreditInterest,\n SUM(AccruedDebitInterest) AS TotalDebitInterest,\n SUM(Settled) + SUM(AccruedCreditInterest) - SUM(AccruedDebitInterest) AS NetBalance\nFROM BCAccountCash\nGROUP BY CurrencyID\nORDER BY NetBalance DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `BCAccountCash` 记录账户现金余额\n- `Settled` 已结算余额\n- `AccruedCreditInterest` 应计存款利息\n- `AccruedDebitInterest` 应计借款利息", "question_en": "What is the total client cash balance across all currencies?", "rating": 9, "execution_result": null, "result_note": "| CurrencyID | AccountCount | TotalSettledBalance | NetBalance |\n|------------|-------------|--------------------|------------|\n| HKD | 2,906 | 52,195,305.77 | 52,195,305.77 |\n| TWD | 2 | -27,676.60 | -27,676.60 |\n| USD | 175 | 0 | 0 |\n| CNY | 95 | 0 | 0 |\n| GBP | 1 | 0 | 0 |", "tags": ["ordering", "account", "cash", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q7", "question_zh": "今日结算后现金余额为负的账户列表。", "sql": "-- 查询现金余额为负的账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.CurrencyID,\n c.Settled AS CashBalance,\n c.UnderdueCheque,\n c.BankAvailableBalance\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.Settled < 0\nORDER BY c.Settled ASC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash.Settled` 表示已结算现金余额\n- 负数表示账户透支\n- 关联 `MCAccount` 获取账户名称", "question_en": "List accounts with negative cash balance after today's settlement.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | CurrencyID | CashBalance |\n|-----------|------------|------------|-------------|\n| M050009 | NG SUN SHU*** | HKD | -4,678,978.42 |\n| P050667 | WONG YIM HUNG | HKD | -780,196.94 |\n| M050521 | LO CHUN YIP | HKD | -290,487.54 |\n\n(共55个账户现金余额为负)", "tags": ["join", "ordering", "filter", "account", "cash"], "difficulty": "hard"}
|
||||
{"qid": "Q8", "question_zh": "明天生效的公司行动涉及哪些证券?", "sql": "-- 查询明日生效的公司行动 (固定日期: 2026-04-03)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate AS EffectiveDate,\n e.BalanceExDate AS ExDate,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE (e.BalanceDate = '2026-04-03' OR e.BalanceExDate = '2026-04-03')\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录权益分派信息\n- `BalanceDate` 权益登记日期\n- `BalanceExDate` 除权日期", "question_en": "Which instruments have corporate actions effective tomorrow?", "rating": 8, "execution_result": null, "result_note": "当前查询无结果(2026-04-03无公司行动)", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q9", "question_zh": "今日预计收到哪些股息?", "sql": "-- 查询今日预计收到的股息 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceDate AS PaymentDate,\n e.BalanceType,\n e.Remark AS DividendDetails\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.BalanceDate = '2026-04-02'\n AND e.BalanceType = 'C'\n AND e.State = 'A'\nORDER BY i.Name;", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派\n- `BalanceType = 'C'` 表示现金股息\n- `BalanceDate` 股息支付日期", "question_en": "What dividends are expected to be received today?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q10", "question_zh": "列出所有进行中IPO的待缴申购金额。", "sql": "-- 查询进行中IPO的待缴金额\nSELECT \n ip.InstrumentID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.SubscriptionAmount,\n ip.SubscriptionPrice,\n ip.Quantity AS SubscriptionLot,\n ip.CreatedOn AS SubscriptionDate,\n ip.State AS SubscriptionStatus\nFROM MCInstrumentIPODetail ip\nINNER JOIN MCInstrument i ON ip.InstrumentID = i.InstrumentID\nWHERE ip.State = 'A'\n AND i.State = 'A'\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrumentIPODetail": {"alias": "ip", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "ip.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MCInstrumentIPODetail` 记录IPO认购详情\n- `SubscriptionAmount` 申购金额\n- `State = 'A'` 表示进行中", "question_en": "Show all pending subscription amounts for ongoing IPOs.", "rating": 8, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | SubscriptionAmount | SubscriptionPrice | Quantity |\n|--------------|----------------|-------------------|-------------------|----------|\n| 02259 | HKEX | 7,231.19 | 36.16 | 100 |\n| 02259 | HKEX | 14,462.40 | 36.16 | 200 |\n\n> 注:MCInstrumentIPODetail 共 586 条进行中 IPO 记录(State='A'),以上为示例行。", "tags": ["join", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q20", "question_zh": "哪些公司行动的选择指令需在今日结束前提交?", "sql": "-- 查询今日截止的公司行动选择 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.ElectionPeriodTo AS Deadline,\n e.ElectionOptionFlag,\n e.Remark AS Description\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.ElectionPeriodTo = '2026-04-02'\n AND e.ElectionOptionFlag = 'Y'\n AND e.State = 'A';", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `ElectionPeriodTo` 选择截止日期\n- `ElectionOptionFlag = 'Y'` 需要选择", "question_en": "Which corporate action elections are due by end of day?", "rating": 8, "execution_result": null, "result_note": "当前查询无今日截止的选择", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q21", "question_zh": "截至昨日的客户借方余额应计利息是多少?", "sql": "-- 查询客户借方余额应计利息 (截至2026-04-01)\nSELECT \n SUM(AccruedDebitInterest) AS TotalDebitInterestAccrued,\n SUM(AccruedCreditInterest) AS TotalCreditInterestAccrued,\n SUM(AccruedDebitInterest) - SUM(AccruedCreditInterest) AS NetDebitInterest,\n COUNT(DISTINCT AccountID) AS AccountCount\nFROM BCAccountCash\nWHERE AccruedDebitInterest > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "BCAccountCash", "columns": []}}, "joins": []}, "explanation": "- `AccruedDebitInterest` 借款应计利息\n- `AccruedCreditInterest` 存款应计利息", "question_en": "What is the interest accrued on client debit balances as of yesterday?", "rating": 8, "execution_result": null, "result_note": "| TotalDebitInterestAccrued | TotalCreditInterestAccrued | NetDebitInterest | AccountCount |\n|---------------------------|---------------------------|-----------------|-------------|\n| 2,022.70 | 464.15 | 1,558.55 | 55 |", "tags": ["filter", "account", "interest", "cash", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q23", "question_zh": "列出所有逾期未付保证金利息的账户。", "sql": "-- 查询逾期保证金利息账户\nSELECT \n c.AccountID,\n a.Name AS AccountName,\n c.LoanInterestMarginOverdue AS MarginOverdueInterest,\n c.LoanInterestMarginBOverdue AS MarginBOverdueInterest,\n c.LoanInterestOverdue AS GeneralOverdueInterest\nFROM BCAccountCash c\nINNER JOIN MCAccount a ON c.AccountID = a.AccountID\nWHERE c.LoanInterestMarginOverdue > 0 \n OR c.LoanInterestMarginBOverdue > 0\n OR c.LoanInterestOverdue > 0\nORDER BY (c.LoanInterestMarginOverdue + c.LoanInterestMarginBOverdue + c.LoanInterestOverdue) DESC;", "schema_info": {"tables": {"BCAccountCash": {"alias": "c", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "c.AccountID = a.AccountID"}]}, "explanation": "- `LoanInterestMarginOverdue` 保证金账户逾期利息\n- `LoanInterestMarginBOverdue` B类保证金逾期利息", "question_en": "Show all accounts with overdue margin interest payments.", "rating": 8, "execution_result": null, "result_note": "当前查询无逾期利息记录", "tags": ["join", "ordering", "margin", "filter", "account", "interest"], "difficulty": "hard"}
|
||||
{"qid": "Q26", "question_zh": "本月各交易所的结算费用明细如何?", "sql": "-- 按交易所统计结算费用 (2026年4月)\n-- 说明:BCAccountInstrument 表中 TotalBoughtFee/TotalSoldFee 是持仓级别的交易费用字段\n-- LastTransactionDate 表示该持仓最后交易日期\n-- 查询逻辑:筛选最后交易日期在本月内的持仓记录,按交易所汇总交易费用\nSELECT \n bi.MarketID,\n m.MarketName,\n SUM(bi.TotalBoughtFee) AS TotalBuyFee,\n SUM(bi.TotalSoldFee) AS TotalSellFee,\n SUM(bi.TotalBoughtFee + bi.TotalSoldFee) AS TotalSettlementFee,\n COUNT(DISTINCT bi.AccountID) AS TradingAccountCount\nFROM BCAccountInstrument bi\nINNER JOIN MCMarket m ON bi.MarketID = m.MarketID\nWHERE bi.LastTransactionDate >= '2026-04-01' AND bi.LastTransactionDate < '2026-05-01'\nGROUP BY bi.MarketID, m.MarketName\nORDER BY TotalSettlementFee DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "bi", "columns": []}, "MCMarket": {"alias": "m", "columns": []}}, "joins": [{"type": "INNER", "on": "bi.MarketID = m.MarketID"}]}, "explanation": "- `BCAccountInstrument` 存储持仓级别信息,包含各持仓的交易费用累计\n- `MCMarket` 存储市场信息,提供市场名称\n- `LastTransactionDate` 用于过滤本月有交易的持仓记录\n- 按市场分组汇总结算费用", "question_en": "What is the breakdown of settlement fees by exchange for this month?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "ordering", "filter", "trade", "aggregation", "date_range"], "difficulty": "hard"}
|
||||
{"qid": "Q27", "question_zh": "列出所有超过3天的暂记账户分录。", "sql": "-- 查询超过3天的暂记账户分录 (2026-04-02)\n-- 说明:TCAccountCashMovement 是现金流水表\n-- NeedHoldFlag='Y' 表示暂记分录\n-- Amount - ReleasedAmount 表示未释放金额(暂记余额)\n-- 筛选未释放且超过3天的暂记分录\nSELECT \n cm.AccountID,\n cm.MovementID,\n cm.ValueDate,\n cm.CurrencyID,\n cm.Amount - ISNULL(cm.ReleasedAmount, 0) AS PendingBalance,\n cm.Remark,\n DATEDIFF(DAY, cm.ValueDate, '2026-04-02') AS DaysOutstanding\nFROM TCAccountCashMovement cm\nWHERE cm.NeedHoldFlag = 'Y'\n AND cm.Amount - ISNULL(cm.ReleasedAmount, 0) != 0\n AND DATEDIFF(DAY, cm.ValueDate, '2026-04-02') > 3\nORDER BY DaysOutstanding DESC, PendingBalance DESC;", "schema_info": {"tables": {"TCAccountCashMovement": {"alias": "cm", "columns": []}}, "joins": []}, "explanation": "- `TCAccountCashMovement` 存储现金流水记录\n- `NeedHoldFlag = 'Y'` 标识暂记(待确认)分录\n- `Amount - ReleasedAmount` 计算未释放的暂记余额\n- `DATEDIFF` 计算距今天数\n- `DATEDIFF > 3` 筛选超过3天的记录", "question_en": "List all suspense account entries older than 3 days.", "rating": 9, "execution_result": null, "result_note": "**查询结果:0条记录**\n\n当前没有超过3天未释放的暂记账户分录。所有暂记分录的 ReleasedAmount = Amount,已全部释放。", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q29", "question_zh": "列出后台系统中所有活跃用户账户及其最后登录日期。", "sql": "-- 查询活跃用户及其登录情况\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType,\n CASE \n WHEN u.LastLogonTime >= DATEADD(DAY, -7, GETDATE()) THEN '近7天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -30, GETDATE()) THEN '近30天活跃'\n WHEN u.LastLogonTime >= DATEADD(DAY, -90, GETDATE()) THEN '近90天活跃'\n ELSE '长期未登录'\n END AS ActivityStatus\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储用户信息\n- `LastLogonTime` 最后登录时间", "question_en": "List all active user accounts in the back office system with last login date.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | ActivityStatus |\n|--------|----------|--------|-----------------|---------------|----------------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-08 | 近7天活跃 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 | 长期未登录 |\n| SING | WONG LO SING | N | Y | 2025-10-21 | 长期未登录 |\n| LEONNG | LEON NG | N | Y | 2025-10-21 | 长期未登录 |", "tags": ["account", "date_function", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q30", "question_zh": "按结算日期划分的未结算交易总风险敞口是多少?", "sql": "-- 按结算日期分组的未结算交易敞口\nSELECT \n SettlementType,\n SUM(Amount) AS TotalExposure\nFROM (\n SELECT 'DueBuy_T1' AS SettlementType, SUM(DueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'DueSell_T1' AS SettlementType, SUM(DueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueBuy' AS SettlementType, SUM(NextDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextDayDueSell' AS SettlementType, SUM(NextDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueBuy' AS SettlementType, SUM(NextTwoDayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'NextTwoDayDueSell' AS SettlementType, SUM(NextTwoDayDueSell) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueBuy' AS SettlementType, SUM(TodayDueBuy) AS Amount FROM BCAccountInstrument\n UNION ALL\n SELECT 'TodayDueSell' AS SettlementType, SUM(TodayDueSell) AS Amount FROM BCAccountInstrument\n) t\nGROUP BY SettlementType\nORDER BY SettlementType;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表包含所有账户的证券持仓和交收信息\n- `DueBuy/DueSell` 表示T+1到期的买卖数量", "question_en": "What is the total exposure from unsettled trades by settlement date?", "rating": 8, "execution_result": null, "result_note": "| SettlementType | TotalExposure |\n|----------------|---------------|\n| DueBuy_T1 | 0 |\n| DueSell_T1 | 0 |\n| NextDayDueBuy | 0 |\n| NextDayDueSell | 0 |\n| NextTwoDayDueBuy | 0 |\n| NextTwoDayDueSell | 0 |\n| TodayDueBuy | 1,800 |\n| TodayDueSell | 1,000 |\n\n**注:** `DueBuy/DueSell` 等字段表示应交收数量(T+1/T+2/今日),非金额敞口。如需金额敞口,需乘以价格。", "tags": ["union", "trade", "ordering", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q31", "question_zh": "指定日期或日期范围内收到的交易量(如成交金额)及相应佣金是多少?", "sql": "-- 交易量和佣金统计\nSELECT \n SUM(TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(TotalBoughtFee) AS TotalBuyCommission,\n SUM(TotalSoldConsideration) AS TotalSellConsideration,\n SUM(TotalSoldFee) AS TotalSellCommission,\n SUM(TotalBoughtConsideration) + SUM(TotalSoldConsideration) AS TotalConsideration,\n SUM(TotalBoughtFee) + SUM(TotalSoldFee) AS TotalCommission\nFROM BCAccountInstrument;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录了账户所有历史买卖交易\n- `TotalBoughtConsideration / TotalSoldConsideration`: 买卖成交金额", "question_en": "What is the trading volume (e.g., consideration) and corresponding commission amount received for a specific date or date range?", "rating": 9, "execution_result": null, "result_note": "| TotalBuyConsideration | TotalBuyCommission | TotalSellConsideration | TotalSellCommission | TotalConsideration | TotalCommission |\n|---------------------|-------------------|----------------------|--------------------|-------------------|-----------------|\n| 945,480,833.78 | 793,149.07 | 278,693,891.64 | 809,248.89 | 1,224,174,725.42 | 1,602,397.96 |", "tags": ["trade", "aggregation"], "difficulty": "easy"}
|
||||
{"qid": "Q32", "question_zh": "各市场客户不同资产(如股票、债券、基金、虚拟资产)的总持仓是多少?", "sql": "-- 按市场统计客户持仓\nSELECT \n b.MarketID,\n COUNT(DISTINCT b.AccountID) AS AccountCount,\n SUM(b.Settled) AS TotalQuantity,\n SUM(b.CostAmount) AS TotalCostAmount,\n SUM(b.TotalBoughtQuantity) AS TotalBoughtQty,\n SUM(b.TotalSoldQuantity) AS TotalSoldQty\nFROM BCAccountInstrument b\nGROUP BY b.MarketID\nORDER BY TotalCostAmount DESC;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "b", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 表记录账户在各市场的持仓\n- `MarketID` 区分不同市场", "question_en": "What is the total client holding of different assets (e.g., stocks, bonds, funds, virtual assets) by each market?", "rating": 8, "execution_result": null, "result_note": "| MarketID | AccountCount | TotalQuantity | TotalCostAmount | TotalBoughtQty | TotalSoldQty |\n|----------|-------------|---------------|-----------------|---------------|-------------|\n| HKEX | 2,102 | 717,471,548 | 87,813,213.45 | 1,015,923,906 | 298,452,798 |\n| SETW | 2 | 3,100 | 32,298.50 | 4,100 | 1,000 |", "tags": ["account", "holding", "ordering", "aggregation"], "difficulty": "medium"}
|
||||
{"qid": "Q33", "question_zh": "今日是否有追缴保证金通知?", "sql": "-- 查询今日追缴保证金记录 (固定日期: 2026-04-02)\nSELECT \n m.AccountID,\n a.Name AS AccountName,\n m.CallForDeposit,\n m.CallForDepositDate,\n m.CallForDepositDays\nFROM HCAccountMarginCallForDeposit m\nINNER JOIN MCAccount a ON m.AccountID = a.AccountID\nWHERE m.CallForDepositDate = '2026-04-02';", "schema_info": {"tables": {"HCAccountMarginCallForDeposit": {"alias": "m", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "m.AccountID = a.AccountID"}]}, "explanation": "- `HCAccountMarginCallForDeposit` 记录追缴保证金信息\n- `CallForDeposit` 追缴金额", "question_en": "Have there been any margin calls today?", "rating": 9, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "margin", "filter"], "difficulty": "easy"}
|
||||
{"qid": "Q34", "question_zh": "保证金账户前20大持仓(按市值)是多少?", "sql": "-- 保证金账户按市值排序的前20持仓\nSELECT TOP 20\n a.AccountID,\n a.Name AS AccountName,\n a.MarketValue,\n a.MarginDebitRatio AS MarginDebitBalanceRatio,\n a.MarginPosition,\n a.CallForDeposit,\n a.MarginFacilityFlag\nFROM MCAccount a\nWHERE a.MarginFacilityFlag = 'Y'\n AND a.State = 'A'\n AND a.MarketValue > 0\nORDER BY a.MarketValue DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 表包含所有账户信息\n- `MarginFacilityFlag = 'Y'` 筛选保证金账户", "question_en": "What are the top 20 holdings (based on market value) for margin accounts?", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginPosition |\n|-----------|-------------|------------|----------------|\n| M050009 | NG SUN SHU*** | 57,420,000 | 35,515,021.58 |\n| M050013 | NG CHUNG WAI*** | 19,504,520 | 10,918,958.78 |\n| M050193 | WONG KING YIU*** ^ | 11,682,920 | 3,340,099.05 |\n| P020160 | LAW SHIU MING DENNIS | 7,520,370 | 0 |\n| P030078 | MAK SUI BING | 7,120,309.94 | 0 |\n| P051101 | CHUNG CHUNG YEE | 7,117,808.04 | 0 |\n| M050170 | FUNG LAI FONG ANNA | 7,009,227.25 | 4,136,857 |\n| P220005 | LAI KAM SUI # | 5,837,102.10 | 97.97 |\n| P280628 | CHAN KWOK MO # | 5,761,997.48 | 62,508.23 |\n| P280455 | LEUNG KA CHI # | 5,487,971.20 | -64,981.22 |\n\n(共20条记录,以上展示前10条)", "tags": ["ordering", "holding", "margin", "filter", "limit", "account"], "difficulty": "hard"}
|
||||
{"qid": "Q35", "question_zh": "列出本月按客户主任分组的佣金总额,以及相应的成交金额和返佣金额。", "sql": "-- 按经纪商/客户主任分组的佣金统计\nSELECT \n a.AEID,\n u.Name AS AEName,\n COUNT(DISTINCT a.AccountID) AS AccountCount,\n SUM(bi.TotalBoughtFee) AS TotalBuyCommission,\n SUM(bi.TotalSoldFee) AS TotalSellCommission,\n SUM(bi.TotalBoughtConsideration) AS TotalBuyConsideration,\n SUM(bi.TotalSoldConsideration) AS TotalSellConsideration,\n SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) AS TotalCommission\nFROM MCAccount a\nLEFT JOIN MCUser u ON a.AEID = u.UserID\nLEFT JOIN BCAccountInstrument bi ON a.AccountID = bi.AccountID\nWHERE a.State = 'A'\nGROUP BY a.AEID, u.Name\nHAVING SUM(bi.TotalBoughtFee) + SUM(bi.TotalSoldFee) > 0\nORDER BY TotalCommission DESC;", "schema_info": {"tables": {"MCAccount": {"alias": "a", "columns": []}, "MCUser": {"alias": "u", "columns": []}, "BCAccountInstrument": {"alias": "bi", "columns": []}}, "joins": [{"type": "LEFT", "on": "a.AEID = u.UserID"}, {"type": "LEFT", "on": "a.AccountID = bi.AccountID"}]}, "explanation": "- `MCAccount.AEID` 关联经纪商/客户主任\n- `BCAccountInstrument` 包含交易费用数据", "question_en": "List the total commission received this month by AE, along with corresponding consideration and rebate amounts.", "rating": 8, "execution_result": null, "result_note": "| AEID | AEName | AccountCount | TotalBuyCommission | TotalSellCommission | TotalCommission |\n|------|--------|-------------|-------------------|--------------------|----------------|\n| C01 | CHAN YUET HUNG | 628 | 183,244.64 | 187,220.59 | 370,465.23 |\n| C28 | CHAN SHU SHAN | 405 | 179,275.89 | 176,760.39 | 356,036.28 |\n| C05 | CENTRAL | 517 | 97,368.51 | 102,819.88 | 200,188.39 |\n| C33 | LEON NG | 13 | 71,541.06 | 72,620.60 | 144,161.66 |\n| C07 | CHAN WING PAI | 75 | 73,255.68 | 69,115.58 | 142,371.26 |\n| C10 | TOKWAWAN / KOWLOON CITY | 369 | 51,059.78 | 57,288.86 | 108,348.64 |\n| C08 | WONG HON KONG | 380 | 47,505.15 | 46,300.39 | 93,805.54 |\n| C36 | Name Of C36 | 146 | 40,945.66 | 35,682.86 | 76,628.52 |\n| C66 | CHEUNG YUK LING IVA | 17 | 24,458.82 | 22,723.18 | 47,182.00 |\n| C19 | WONG LO SING | 60 | 13,337.69 | 13,912.30 | 27,249.99 |\n\n(共15个AE有佣金记录,以上展示前10条)\n\n**注:** 当前SQL无日期条件,统计所有历史累计佣金。如需\"本月\"佣金,需添加 `LastTransactionDate >= '2026-04-01'` 条件。", "tags": ["join", "ordering", "filter", "account", "left_join", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q37", "question_zh": "是否有正在进行的IPO事件,其认购状态如何?", "sql": "-- 查询进行中的IPO (2026年4月)\nSELECT \n i.InstrumentID,\n i.MarketID,\n i.Name AS InstrumentName,\n i.State AS InstrumentStatus,\n ip.Quantity AS SubscriptionLot,\n ip.SubscriptionAmount,\n ip.CreatedOn AS SubscriptionDate\nFROM MCInstrument i\nINNER JOIN MCInstrumentIPODetail ip ON i.InstrumentID = ip.InstrumentID\nWHERE YEAR(ip.CreatedOn) = 2026\n AND MONTH(ip.CreatedOn) = 4\nORDER BY ip.CreatedOn DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "i", "columns": []}, "MCInstrumentIPODetail": {"alias": "ip", "columns": []}}, "joins": [{"type": "INNER", "on": "i.InstrumentID = ip.InstrumentID"}]}, "explanation": "- `MCInstrument` 表记录证券信息\n- `MCInstrumentIPODetail` 记录IPO认购详情", "question_en": "Are there any IPO events currently in progress, and what is their subscription status?", "rating": 8, "execution_result": null, "result_note": "", "tags": ["join", "filter", "ipo", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q39", "question_zh": "列出今日需要执行的公司行动(如权益分派)。", "sql": "-- 查询今日生效的公司行动 (固定日期: 2026-04-02)\nSELECT \n e.EntitlementID,\n e.MarketID,\n e.InstrumentID,\n i.Name AS InstrumentName,\n e.BalanceType,\n e.BalanceDate,\n e.BalanceExDate,\n e.Remark,\n e.State\nFROM MSBEntitlement e\nINNER JOIN MCInstrument i ON e.InstrumentID = i.InstrumentID\nWHERE e.State = 'A'\n AND (\n e.BalanceDate = '2026-04-02'\n OR e.BalanceExDate = '2026-04-02'\n OR e.AutoHoldDate = '2026-04-02'\n OR e.AutoDeductDate = '2026-04-02'\n );", "schema_info": {"tables": {"MSBEntitlement": {"alias": "e", "columns": []}, "MCInstrument": {"alias": "i", "columns": []}}, "joins": [{"type": "INNER", "on": "e.InstrumentID = i.InstrumentID"}]}, "explanation": "- `MSBEntitlement` 记录所有权益分派信息\n- `BalanceDate` 权益登记日期", "question_en": "List corporate actions (e.g., entitlements) that need to be performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "corporate_action"], "difficulty": "easy"}
|
||||
{"qid": "Q40", "question_zh": "列出今日执行的所有股票转移/移动。", "sql": "-- 今日股票转入/转出 (固定日期: 2026-04-02)\nSELECT \n AccountID,\n MarketID,\n InstrumentID,\n TodayIn AS QuantityIn,\n TodayOut AS QuantityOut,\n HoldForDeposit AS PendingDeposit,\n HoldForWithdrawal AS PendingWithdrawal\nFROM BCAccountInstrument\nWHERE TodayIn > 0 OR TodayOut > 0;", "schema_info": {"tables": {"BCAccountInstrument": {"alias": "BCAccountInstrument", "columns": []}}, "joins": []}, "explanation": "- `BCAccountInstrument` 记录股票持仓变动\n- `TodayIn` 今日转入数量", "question_en": "List all stock movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["filter"], "difficulty": "easy"}
|
||||
{"qid": "Q41", "question_zh": "列出今日执行的所有现金划转。", "sql": "-- 今日现金变动汇总 (固定日期: 2026-04-02)\nSELECT \n b.AccountID,\n a.Name AS AccountName,\n b.TodayIn AS CashIn,\n b.TodayOut AS CashOut,\n b.BankAvailableBalance\nFROM BCAccountCash b\nINNER JOIN MCAccount a ON b.AccountID = a.AccountID\nWHERE b.TodayIn > 0 OR b.TodayOut > 0;", "schema_info": {"tables": {"BCAccountCash": {"alias": "b", "columns": []}, "MCAccount": {"alias": "a", "columns": []}}, "joins": [{"type": "INNER", "on": "b.AccountID = a.AccountID"}]}, "explanation": "- `BCAccountCash` 记录账户现金变动\n- `TodayIn` 今日现金流入", "question_en": "List all cash movements performed today.", "rating": 8, "execution_result": null, "result_note": "当前查询无结果", "tags": ["join", "filter", "cash"], "difficulty": "easy"}
|
||||
{"qid": "Q42", "question_zh": "列出后台系统中的活跃用户。", "sql": "-- 查询后台系统活跃用户\nSELECT \n u.UserID,\n u.Name AS UserName,\n u.Status,\n u.LogonEnableFlag,\n u.LastLogonTime,\n u.BranchID,\n u.DepartmentID,\n CASE u.CompanyAEFlag WHEN 'Y' THEN '公司经纪' ELSE '个人' END AS AEType\nFROM MCUser u\nWHERE u.State = 'A'\n AND u.LogonEnableFlag = 'Y'\nORDER BY u.LastLogonTime DESC;", "schema_info": {"tables": {"MCUser": {"alias": "u", "columns": []}}, "joins": []}, "explanation": "- `MCUser` 存储系统用户信息\n- `State = 'A'` 用户状态正常", "question_en": "List active users in the back office.", "rating": 9, "execution_result": null, "result_note": "| UserID | UserName | Status | LogonEnableFlag | LastLogonTime | AEType |\n|--------|----------|--------|-----------------|---------------|--------|\n| SUPPORT | SUPPORT | N | Y | 2026-04-03 18:53:04 | 个人 |\n| ROSANNA | ROSANNA | N | Y | 2025-10-21 16:47:11 | 个人 |", "tags": ["filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q43", "question_zh": "列出持仓为负数(透支)的账户。", "sql": "-- 查询透支持仓账户\nSELECT \n AccountID,\n Name AS AccountName,\n MarketValue,\n AssetBalance,\n LiabilityBalance,\n MarginPosition,\n MarginFacilityFlag\nFROM MCAccount\nWHERE MarketValue < 0\n AND State = 'A'\nORDER BY MarketValue ASC;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MarketValue < 0` 筛选持仓为负的账户\n- 持仓为负通常表示账户存在透支或结算问题", "question_en": "List accounts with overdrawn positions.", "rating": 9, "execution_result": null, "result_note": "| AccountID | AccountName | MarketValue | MarginFacilityFlag |\n|-----------|-------------|-------------|-------------------|\n| P030012 | LAI YEE TAK HELEN | -112,196.60 | N |\n| P350022 | CHAN YAU KING*** | -92,950.00 | N |\n| P011212 | NG SIU PING | -12,352.00 | N |", "tags": ["account", "holding", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q47", "question_zh": "今日/指定日期发放了多少份日结单或月结单?", "sql": "-- 查询报表发放统计 (2026-04-02)\nSELECT \n 'Daily Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastDailyStatementDate = '2026-04-02'\nUNION ALL\nSELECT \n 'Monthly Statement' AS StatementType,\n COUNT(*) AS StatementCount\nFROM MCAccount\nWHERE LastMonthlyStatementDate = '2026-04-02';", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount` 记录账户报表发送日期\n- `LastDailyStatementDate` 最近日结单发送日期", "question_en": "How many daily or monthly statements were issued today / on a specific date?", "rating": 9, "execution_result": null, "result_note": "", "tags": ["union", "filter", "aggregation"], "difficulty": "hard"}
|
||||
{"qid": "Q48", "question_zh": "列出所有支持保证金的证券及其相应的保证金比例。", "sql": "-- 查询支持保证金的证券\nSELECT \n InstrumentID,\n Name AS InstrumentName,\n MarginPercentage AS MarginRatio,\n CASE \n WHEN MarginPercentage >= 0.7 THEN '高'\n WHEN MarginPercentage >= 0.5 THEN '中'\n WHEN MarginPercentage > 0 THEN '低'\n ELSE 'N/A'\n END AS RiskLevel,\n MarginLimitPerInstrument,\n CollateralRatio\nFROM MCInstrument\nWHERE MarginPercentage IS NOT NULL\n AND MarginPercentage > 0\n AND State = 'A'\nORDER BY MarginPercentage DESC;", "schema_info": {"tables": {"MCInstrument": {"alias": "MCInstrument", "columns": []}}, "joins": []}, "explanation": "- `MCInstrument` 存储证券信息\n- `MarginPercentage` 保证金比例", "question_en": "List all instruments that support margin and their corresponding margin ratios.", "rating": 9, "execution_result": null, "result_note": "| InstrumentID | InstrumentName | MarginRatio | RiskLevel |\n|-------------|----------------|-------------|-----------|\n| 00001 | CKH HOLDINGS(S) | 0.70 | 高 |\n| 00002 | CLP HOLDINGS(S) | 0.70 | 高 |\n| 00003 | HK & CHINA GAS(S) | 0.70 | 高 |\n\n(共767条记录)", "tags": ["margin", "limit", "filter", "ordering"], "difficulty": "easy"}
|
||||
{"qid": "Q49", "question_zh": "本月、本季度和今年分别开了多少账户?", "sql": "-- 开户统计 (2026年4月)\nSELECT \n COUNT(CASE WHEN MONTH(OpenDate) = 4 AND YEAR(OpenDate) = 2026 THEN 1 END) AS April2026,\n COUNT(CASE WHEN DATEPART(QUARTER, OpenDate) = 2 AND YEAR(OpenDate) = 2026 THEN 1 END) AS Q2_2026,\n COUNT(CASE WHEN YEAR(OpenDate) = 2026 THEN 1 END) AS Year2026,\n COUNT(*) AS TotalAccounts,\n MIN(OpenDate) AS EarliestOpenDate,\n MAX(OpenDate) AS LatestOpenDate\nFROM MCAccount\nWHERE OpenDate IS NOT NULL;", "schema_info": {"tables": {"MCAccount": {"alias": "MCAccount", "columns": []}}, "joins": []}, "explanation": "- `MCAccount.OpenDate` 账户开户日期\n- 按月、季度、年分别统计新开户数量", "question_en": "How many accounts were opened this month, this quarter, and this year?", "rating": 9, "execution_result": null, "result_note": "| April2026 | Q2_2026 | Year2026 | TotalAccounts | EarliestOpenDate | LatestOpenDate |\n|-----------|---------|----------|---------------|------------------|----------------|\n| 0 | 0 | 0 | 1,951 | 1993-03-05 | 2025-10-16 |", "tags": ["account", "limit", "filter", "aggregation"], "difficulty": "easy"}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
Binary file not shown.
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
将 Few-shot 经验数据集(JSONL)写入 Chroma 持久化向量库。
|
||||
|
||||
用法(仓库根目录):
|
||||
python scripts/build_fewshot_chroma_index.py
|
||||
python scripts/build_fewshot_chroma_index.py --samples data/experiences/all_samples.jsonl --force
|
||||
|
||||
构建完成后在 .env 中设置:
|
||||
FEWSHOT_USE_CHROMA=true
|
||||
FEWSHOT_CHROMA_PATH=./data/embeddings/chroma_fewshot
|
||||
|
||||
Embedding 与 Schema 向量一致,由 USE_LOCAL_EMBEDDING / OPENAI_* / MODELSCOPE_* 等决定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
_BACKEND = _REPO_ROOT / "backend"
|
||||
if str(_BACKEND) not in sys.path:
|
||||
sys.path.insert(0, str(_BACKEND))
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("build_fewshot_chroma")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Few-shot JSONL → Chroma 向量索引")
|
||||
parser.add_argument(
|
||||
"--samples",
|
||||
default=os.getenv("FEWSHOT_DATA_PATH", "data/experiences/all_samples.jsonl"),
|
||||
help="JSONL 路径(相对仓库根或绝对路径)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--persist-dir",
|
||||
default=os.getenv("FEWSHOT_CHROMA_PATH", "data/embeddings/chroma_fewshot"),
|
||||
help="Chroma 持久化目录",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="清空已有集合并全量重建",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
samples_path = Path(args.samples)
|
||||
if not samples_path.is_absolute():
|
||||
samples_path = _REPO_ROOT / samples_path
|
||||
if not samples_path.is_file():
|
||||
logger.error("样本文件不存在: %s", samples_path)
|
||||
return 1
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(_REPO_ROOT / ".env")
|
||||
|
||||
from utils.embedding import get_embedder
|
||||
from utils.fewshot_chroma_store import FewShotChromaStore
|
||||
from utils.fewshot_selector import ExperienceSample
|
||||
|
||||
rows: list[ExperienceSample] = []
|
||||
with samples_path.open("r", encoding="utf-8") as f:
|
||||
for line_no, line in enumerate(f, 1):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
rows.append(ExperienceSample.from_dict(json.loads(line)))
|
||||
except json.JSONDecodeError as e:
|
||||
logger.warning("跳过第 %s 行 JSON 错误: %s", line_no, e)
|
||||
|
||||
if not rows:
|
||||
logger.error("未解析到任何样本")
|
||||
return 1
|
||||
|
||||
embed_path = os.getenv("EMBEDDING_MODEL_PATH", "").strip() or None
|
||||
embedder = get_embedder(embed_path)
|
||||
persist = Path(args.persist_dir)
|
||||
if not persist.is_absolute():
|
||||
persist = _REPO_ROOT / persist
|
||||
|
||||
store = FewShotChromaStore(embedder, persist_dir=str(persist))
|
||||
n = store.build_from_samples(rows, force_rebuild=args.force)
|
||||
logger.info("完成: 写入 %s 条 → %s", n, persist)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,182 @@
|
||||
"""
|
||||
Parse 常问问题对应SQL_50个问题知识库_Workbuddy生成.md into JSONL aligned with all_samples.jsonl.
|
||||
Merges schema_info, tags, difficulty from all_samples when qid matches.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MD_PATH = ROOT / "data" / "常问问题对应SQL_50个问题知识库_Workbuddy生成.md"
|
||||
REF_JSONL = ROOT / "data" / "experiences" / "all_samples.jsonl"
|
||||
OUT_PATH = ROOT / "data" / "experiences" / "workbuddy_50_questions.jsonl"
|
||||
|
||||
# `question_en` right after `question_zh` so long lines are easy to spot in editors.
|
||||
JSONL_KEY_ORDER = [
|
||||
"qid",
|
||||
"question_zh",
|
||||
"question_en",
|
||||
"sql",
|
||||
"schema_info",
|
||||
"explanation",
|
||||
"rating",
|
||||
"execution_result",
|
||||
"result_note",
|
||||
"tags",
|
||||
"difficulty",
|
||||
]
|
||||
|
||||
CJK_RE = re.compile(r"[\u4e00-\u9fff\u3400-\u4dbf]")
|
||||
SECTION_RE = re.compile(r"^## (Q\d+)\.\s*.*$", re.MULTILINE)
|
||||
SQL_BLOCK_RE = re.compile(r"```sql\s*\n(.*?)```", re.DOTALL)
|
||||
RATING_RE = re.compile(r"\*\*评分:\s*(\d+)/10")
|
||||
|
||||
|
||||
def has_cjk(s: str) -> bool:
|
||||
return bool(CJK_RE.search(s))
|
||||
|
||||
|
||||
def parse_questions(text: str) -> tuple[str, str]:
|
||||
"""Split body after '### 问题' into English vs Chinese lines."""
|
||||
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
||||
en_parts: list[str] = []
|
||||
zh_parts: list[str] = []
|
||||
for ln in lines:
|
||||
if has_cjk(ln):
|
||||
zh_parts.append(ln)
|
||||
else:
|
||||
en_parts.append(ln)
|
||||
return (" ".join(en_parts).strip(), " ".join(zh_parts).strip())
|
||||
|
||||
|
||||
def dedupe_sql_blocks(blocks: list[str]) -> list[str]:
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for b in blocks:
|
||||
key = b.strip()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(b.rstrip())
|
||||
return out
|
||||
|
||||
|
||||
def extract_sql_blocks(region: str) -> list[str]:
|
||||
blocks = [m.group(1).strip() for m in SQL_BLOCK_RE.finditer(region)]
|
||||
return dedupe_sql_blocks(blocks)
|
||||
|
||||
|
||||
def reorder_row(d: dict) -> dict:
|
||||
return {k: d[k] for k in JSONL_KEY_ORDER}
|
||||
|
||||
|
||||
def parse_block(qid: str, body: str, ref: dict) -> dict:
|
||||
ap = body.find("\n## 附录")
|
||||
if ap != -1:
|
||||
body = body[:ap].rstrip()
|
||||
|
||||
# --- 问题 ---
|
||||
m_q = re.search(r"### 问题\s*\n(.*?)(?=\n### 查询SQL\s)", body, re.DOTALL)
|
||||
if not m_q:
|
||||
raise ValueError(f"{qid}: missing ### 问题")
|
||||
question_en, question_zh = parse_questions(m_q.group(1))
|
||||
if not question_en and question_zh:
|
||||
if qid == "Q50":
|
||||
question_en = "List all client trade records for today."
|
||||
else:
|
||||
question_en = ref.get("question_en") or ""
|
||||
|
||||
# --- SQL + result_note ---
|
||||
m_sql_hdr = re.search(r"### 查询SQL\s*\n", body)
|
||||
if not m_sql_hdr:
|
||||
raise ValueError(f"{qid}: missing ### 查询SQL")
|
||||
tail = body[m_sql_hdr.end() :]
|
||||
idx_exec = tail.find("### SQL执行结果")
|
||||
idx_reason = tail.find("### SQL理由")
|
||||
|
||||
if idx_exec != -1 and (idx_reason == -1 or idx_exec < idx_reason):
|
||||
sql_region = tail[:idx_exec]
|
||||
chunk = tail[idx_exec:idx_reason] if idx_reason != -1 else tail[idx_exec:]
|
||||
result_note = re.sub(
|
||||
r"^### SQL执行结果\s*",
|
||||
"",
|
||||
chunk,
|
||||
count=1,
|
||||
flags=re.MULTILINE,
|
||||
).strip()
|
||||
elif idx_reason != -1:
|
||||
sql_region = tail[:idx_reason]
|
||||
last_end = 0
|
||||
for m in SQL_BLOCK_RE.finditer(sql_region):
|
||||
last_end = m.end()
|
||||
result_note = sql_region[last_end:].strip() if last_end else ""
|
||||
else:
|
||||
raise ValueError(f"{qid}: no ### SQL理由 / ### SQL执行结果")
|
||||
|
||||
sql_parts = extract_sql_blocks(sql_region)
|
||||
sql = "\n\n".join(sql_parts) if sql_parts else ref.get("sql", "")
|
||||
|
||||
# --- explanation & rating ---
|
||||
m_reason = re.search(r"### SQL理由\s*\n(.*?)(?=\n### SQL准确度评分\s|\Z)", body, re.DOTALL)
|
||||
explanation = ""
|
||||
if m_reason:
|
||||
explanation = "\n".join(
|
||||
ln.rstrip() for ln in m_reason.group(1).splitlines() if ln.strip().startswith("-")
|
||||
).strip()
|
||||
|
||||
m_rating = RATING_RE.search(body)
|
||||
rating = int(m_rating.group(1)) if m_rating else ref.get("rating")
|
||||
|
||||
base = dict(ref)
|
||||
base.update(
|
||||
{
|
||||
"qid": qid,
|
||||
"question_zh": question_zh or ref.get("question_zh") or "",
|
||||
"question_en": question_en,
|
||||
"sql": sql,
|
||||
"explanation": explanation if explanation else (ref.get("explanation") or ""),
|
||||
"rating": rating,
|
||||
"execution_result": None,
|
||||
"result_note": result_note.strip() if result_note else (ref.get("result_note") or ""),
|
||||
}
|
||||
)
|
||||
return reorder_row(base)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
md = MD_PATH.read_text(encoding="utf-8")
|
||||
refs: dict[str, dict] = {}
|
||||
with REF_JSONL.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
obj = json.loads(line)
|
||||
refs[obj["qid"]] = obj
|
||||
|
||||
matches = list(SECTION_RE.finditer(md))
|
||||
rows: list[dict] = []
|
||||
for i, m in enumerate(matches):
|
||||
qid = m.group(1)
|
||||
start = m.end()
|
||||
end = matches[i + 1].start() if i + 1 < len(matches) else len(md)
|
||||
body = md[start:end]
|
||||
ref = refs.get(qid, {})
|
||||
row = parse_block(qid, body, ref)
|
||||
rows.append(row)
|
||||
|
||||
if len(rows) != 50:
|
||||
raise SystemExit(f"expected 50 sections, got {len(rows)}")
|
||||
|
||||
OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
with OUT_PATH.open("w", encoding="utf-8", newline="\n") as out:
|
||||
for row in rows:
|
||||
out.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
|
||||
print(f"Wrote {OUT_PATH} ({len(rows)} lines)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,25 +0,0 @@
|
||||
"""DBHub 风格数据库工具;实现位于 ``backend/db``,经 ``dbhub_tools`` 转发。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .dbhub_tools import (
|
||||
DbHubTools,
|
||||
dbhub_tools,
|
||||
execute_sql,
|
||||
execute_sql_all,
|
||||
execute_sql_count_only,
|
||||
probe_sql_execution_status,
|
||||
probe_sql_execution_status_ex,
|
||||
search_objects,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DbHubTools",
|
||||
"dbhub_tools",
|
||||
"execute_sql",
|
||||
"execute_sql_all",
|
||||
"execute_sql_count_only",
|
||||
"probe_sql_execution_status",
|
||||
"probe_sql_execution_status_ex",
|
||||
"search_objects",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,90 +0,0 @@
|
||||
"""
|
||||
从 DBHub allowed-keywords.ts 等价移植:只读 SQL 判定。
|
||||
参见 dbhub/src/utils/allowed-keywords.ts
|
||||
|
||||
与 ``backend/db/dbhub_allowed_keywords.py`` 保持一致;此处使用同目录 ``dbhub_sql_parser`` 导入,
|
||||
便于在仅将 ``tools/`` 加入 ``sys.path`` 的脚本中单独使用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
from dbhub_sql_parser import ConnectorType, strip_comments_and_strings
|
||||
|
||||
ALLOWED_KEYWORDS: dict[ConnectorType, list[str]] = {
|
||||
"postgres": ["select", "with", "explain", "show"],
|
||||
"mysql": ["select", "with", "explain", "show", "describe", "desc"],
|
||||
"mariadb": ["select", "with", "explain", "show", "describe", "desc"],
|
||||
"sqlite": ["select", "with", "explain", "pragma"],
|
||||
"sqlserver": ["select", "with", "explain", "showplan"],
|
||||
}
|
||||
|
||||
_MUTATING = [
|
||||
"insert",
|
||||
"update",
|
||||
"delete",
|
||||
"drop",
|
||||
"alter",
|
||||
"create",
|
||||
"truncate",
|
||||
"merge",
|
||||
"grant",
|
||||
"revoke",
|
||||
"rename",
|
||||
]
|
||||
_mutating_pattern = re.compile(rf"\b(?:{'|'.join(_MUTATING)})\b", re.IGNORECASE)
|
||||
_mutating_pattern_with_replace = re.compile(
|
||||
rf"\b(?:{'|'.join(_MUTATING)}|replace\s+(?:(?:low_priority|delayed)\s+)?into)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_MUTATING_PATTERNS: dict[ConnectorType, re.Pattern[str]] = {
|
||||
"postgres": _mutating_pattern,
|
||||
"mysql": _mutating_pattern_with_replace,
|
||||
"mariadb": _mutating_pattern_with_replace,
|
||||
"sqlite": _mutating_pattern_with_replace,
|
||||
"sqlserver": _mutating_pattern,
|
||||
}
|
||||
|
||||
_SELECT_INTO_PATTERN = re.compile(r"\bselect\b[\s\S]+\binto\b", re.IGNORECASE)
|
||||
|
||||
_EXPLAIN_ANALYZE_PATTERN = re.compile(
|
||||
r"^explain\s+(?:\([^)]*\banalyze\b(?!\s*(?:=\s*)?(?:false|off|0)\b)[^)]*\)|\banalyze\b(?!\s*(?:=\s*)?(?:false|off|0)\b)(?:\s+verbose\b)?)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _check_read_only(cleaned_sql: str, connector_type: ConnectorType | str) -> bool:
|
||||
if not cleaned_sql:
|
||||
return False
|
||||
m = re.search(r"\S+", cleaned_sql)
|
||||
first_word = m.group(0) if m else ""
|
||||
keyword_list = ALLOWED_KEYWORDS.get(connector_type, []) # type: ignore[arg-type]
|
||||
if first_word not in keyword_list:
|
||||
return False
|
||||
if first_word == "with":
|
||||
pat = _MUTATING_PATTERNS.get(connector_type, _mutating_pattern) # type: ignore[arg-type]
|
||||
if pat.search(cleaned_sql):
|
||||
return False
|
||||
if first_word in ("select", "with") and _SELECT_INTO_PATTERN.search(cleaned_sql):
|
||||
return False
|
||||
if first_word == "explain":
|
||||
em = _EXPLAIN_ANALYZE_PATTERN.match(cleaned_sql)
|
||||
if em:
|
||||
after_explain = cleaned_sql[em.end() :].strip()
|
||||
if after_explain and not _check_read_only(after_explain, connector_type):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_read_only_sql(sql: str, connector_type: ConnectorType | str) -> bool:
|
||||
"""Check if a SQL query is read-only (DBHub-compatible)."""
|
||||
cleaned = strip_comments_and_strings(sql, connector_type if connector_type in ALLOWED_KEYWORDS else None)
|
||||
cleaned = cleaned.strip().lower()
|
||||
return _check_read_only(cleaned, connector_type)
|
||||
|
||||
|
||||
def allowed_keywords_list(connector_type: ConnectorType | str) -> list[str]:
|
||||
return ALLOWED_KEYWORDS.get(connector_type, []) # type: ignore[arg-type]
|
||||
@@ -1,268 +0,0 @@
|
||||
"""
|
||||
从 DBHub sql-parser.ts 等价移植:按方言剥离注释/字符串、切分语句。
|
||||
参见 dbhub/src/utils/sql-parser.ts
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Callable, Literal, TypedDict
|
||||
|
||||
ConnectorType = Literal["postgres", "mysql", "mariadb", "sqlite", "sqlserver"]
|
||||
|
||||
|
||||
class _Token(TypedDict):
|
||||
type: int # 0 Plain, 1 Comment, 2 QuotedBlock
|
||||
end: int
|
||||
|
||||
|
||||
_TOKEN_PLAIN = 0
|
||||
_TOKEN_COMMENT = 1
|
||||
_TOKEN_QUOTED = 2
|
||||
|
||||
|
||||
def _plain_token(i: int) -> _Token:
|
||||
return {"type": _TOKEN_PLAIN, "end": i + 1}
|
||||
|
||||
|
||||
def _scan_single_line_comment(sql: str, i: int) -> _Token | None:
|
||||
if i + 1 >= len(sql) or sql[i] != "-" or sql[i + 1] != "-":
|
||||
return None
|
||||
j = i
|
||||
while j < len(sql) and sql[j] != "\n":
|
||||
j += 1
|
||||
return {"type": _TOKEN_COMMENT, "end": j}
|
||||
|
||||
|
||||
def _scan_multi_line_comment(sql: str, i: int) -> _Token | None:
|
||||
if i + 1 >= len(sql) or sql[i] != "/" or sql[i + 1] != "*":
|
||||
return None
|
||||
j = i + 2
|
||||
while j + 1 < len(sql) and not (sql[j] == "*" and sql[j + 1] == "/"):
|
||||
j += 1
|
||||
if j + 1 < len(sql):
|
||||
j += 2
|
||||
return {"type": _TOKEN_COMMENT, "end": j}
|
||||
|
||||
|
||||
def _scan_multi_line_comment_mysql(sql: str, i: int) -> _Token | None:
|
||||
if i + 1 >= len(sql) or sql[i] != "/" or sql[i + 1] != "*":
|
||||
return None
|
||||
nxt = sql[i + 2] if i + 2 < len(sql) else ""
|
||||
nxt2 = sql[i + 3] if i + 3 < len(sql) else ""
|
||||
if nxt == "!" or (nxt == "M" and nxt2 == "!"):
|
||||
return None
|
||||
return _scan_multi_line_comment(sql, i)
|
||||
|
||||
|
||||
def _scan_nested_multi_line_comment(sql: str, i: int) -> _Token | None:
|
||||
if i + 1 >= len(sql) or sql[i] != "/" or sql[i + 1] != "*":
|
||||
return None
|
||||
j = i + 2
|
||||
depth = 1
|
||||
while j < len(sql) and depth > 0:
|
||||
if j + 1 < len(sql) and sql[j] == "/" and sql[j + 1] == "*":
|
||||
depth += 1
|
||||
j += 2
|
||||
elif j + 1 < len(sql) and sql[j] == "*" and sql[j + 1] == "/":
|
||||
depth -= 1
|
||||
j += 2
|
||||
else:
|
||||
j += 1
|
||||
return {"type": _TOKEN_COMMENT, "end": j}
|
||||
|
||||
|
||||
def _scan_single_quoted_string(sql: str, i: int) -> _Token | None:
|
||||
if sql[i] != "'":
|
||||
return None
|
||||
j = i + 1
|
||||
while j < len(sql):
|
||||
if j + 1 < len(sql) and sql[j] == "'" and sql[j + 1] == "'":
|
||||
j += 2
|
||||
elif sql[j] == "'":
|
||||
j += 1
|
||||
break
|
||||
else:
|
||||
j += 1
|
||||
return {"type": _TOKEN_QUOTED, "end": j}
|
||||
|
||||
|
||||
def _scan_double_quoted_string(sql: str, i: int) -> _Token | None:
|
||||
if sql[i] != '"':
|
||||
return None
|
||||
j = i + 1
|
||||
while j < len(sql):
|
||||
if j + 1 < len(sql) and sql[j] == '"' and sql[j + 1] == '"':
|
||||
j += 2
|
||||
elif sql[j] == '"':
|
||||
j += 1
|
||||
break
|
||||
else:
|
||||
j += 1
|
||||
return {"type": _TOKEN_QUOTED, "end": j}
|
||||
|
||||
|
||||
_dollar_quote_open_regex = re.compile(r"^\$([a-zA-Z_]\w*)?\$")
|
||||
|
||||
|
||||
def _scan_dollar_quoted_block(sql: str, i: int) -> _Token | None:
|
||||
if sql[i] != "$":
|
||||
return None
|
||||
nxt = sql[i + 1] if i + 1 < len(sql) else ""
|
||||
if nxt.isdigit():
|
||||
return None
|
||||
remaining = sql[i:]
|
||||
m = _dollar_quote_open_regex.match(remaining)
|
||||
if not m:
|
||||
return None
|
||||
tag = m.group(0)
|
||||
body_start = i + len(tag)
|
||||
close_idx = sql.find(tag, body_start)
|
||||
end = close_idx + len(tag) if close_idx != -1 else len(sql)
|
||||
return {"type": _TOKEN_QUOTED, "end": end}
|
||||
|
||||
|
||||
def _scan_backtick_quoted_identifier(sql: str, i: int) -> _Token | None:
|
||||
if sql[i] != "`":
|
||||
return None
|
||||
j = i + 1
|
||||
while j < len(sql):
|
||||
if j + 1 < len(sql) and sql[j] == "`" and sql[j + 1] == "`":
|
||||
j += 2
|
||||
elif sql[j] == "`":
|
||||
j += 1
|
||||
break
|
||||
else:
|
||||
j += 1
|
||||
return {"type": _TOKEN_QUOTED, "end": j}
|
||||
|
||||
|
||||
def _scan_bracket_quoted_identifier(sql: str, i: int) -> _Token | None:
|
||||
if sql[i] != "[":
|
||||
return None
|
||||
j = i + 1
|
||||
while j < len(sql):
|
||||
if j + 1 < len(sql) and sql[j] == "]" and sql[j + 1] == "]":
|
||||
j += 2
|
||||
elif sql[j] == "]":
|
||||
j += 1
|
||||
break
|
||||
else:
|
||||
j += 1
|
||||
return {"type": _TOKEN_QUOTED, "end": j}
|
||||
|
||||
|
||||
def _scan_token_ansi(sql: str, i: int) -> _Token:
|
||||
return (
|
||||
_scan_single_line_comment(sql, i)
|
||||
or _scan_multi_line_comment(sql, i)
|
||||
or _scan_single_quoted_string(sql, i)
|
||||
or _scan_double_quoted_string(sql, i)
|
||||
or _plain_token(i)
|
||||
)
|
||||
|
||||
|
||||
def _scan_token_postgres(sql: str, i: int) -> _Token:
|
||||
return (
|
||||
_scan_single_line_comment(sql, i)
|
||||
or _scan_nested_multi_line_comment(sql, i)
|
||||
or _scan_single_quoted_string(sql, i)
|
||||
or _scan_double_quoted_string(sql, i)
|
||||
or _scan_dollar_quoted_block(sql, i)
|
||||
or _plain_token(i)
|
||||
)
|
||||
|
||||
|
||||
def _scan_token_mysql(sql: str, i: int) -> _Token:
|
||||
return (
|
||||
_scan_single_line_comment(sql, i)
|
||||
or _scan_multi_line_comment_mysql(sql, i)
|
||||
or _scan_single_quoted_string(sql, i)
|
||||
or _scan_double_quoted_string(sql, i)
|
||||
or _scan_backtick_quoted_identifier(sql, i)
|
||||
or _plain_token(i)
|
||||
)
|
||||
|
||||
|
||||
def _scan_token_sqlite(sql: str, i: int) -> _Token:
|
||||
return (
|
||||
_scan_single_line_comment(sql, i)
|
||||
or _scan_multi_line_comment(sql, i)
|
||||
or _scan_single_quoted_string(sql, i)
|
||||
or _scan_double_quoted_string(sql, i)
|
||||
or _scan_backtick_quoted_identifier(sql, i)
|
||||
or _scan_bracket_quoted_identifier(sql, i)
|
||||
or _plain_token(i)
|
||||
)
|
||||
|
||||
|
||||
def _scan_token_sqlserver(sql: str, i: int) -> _Token:
|
||||
return (
|
||||
_scan_single_line_comment(sql, i)
|
||||
or _scan_multi_line_comment(sql, i)
|
||||
or _scan_single_quoted_string(sql, i)
|
||||
or _scan_double_quoted_string(sql, i)
|
||||
or _scan_bracket_quoted_identifier(sql, i)
|
||||
or _plain_token(i)
|
||||
)
|
||||
|
||||
|
||||
_DIALECT_SCANNERS: dict[ConnectorType, Callable[[str, int], _Token]] = {
|
||||
"postgres": _scan_token_postgres,
|
||||
"mysql": _scan_token_mysql,
|
||||
"mariadb": _scan_token_mysql,
|
||||
"sqlite": _scan_token_sqlite,
|
||||
"sqlserver": _scan_token_sqlserver,
|
||||
}
|
||||
|
||||
|
||||
def _get_scanner(dialect: ConnectorType | None) -> Callable[[str, int], _Token]:
|
||||
if dialect and dialect in _DIALECT_SCANNERS:
|
||||
return _DIALECT_SCANNERS[dialect]
|
||||
return _scan_token_ansi
|
||||
|
||||
|
||||
def strip_comments_and_strings(sql: str, dialect: ConnectorType | None = None) -> str:
|
||||
"""Replace comments, string literals, and dialect-specific quoted blocks with a single space each."""
|
||||
scan_token = _get_scanner(dialect)
|
||||
parts: list[str] = []
|
||||
plain_start = -1
|
||||
i = 0
|
||||
n = len(sql)
|
||||
while i < n:
|
||||
token = scan_token(sql, i)
|
||||
if token["type"] == _TOKEN_PLAIN:
|
||||
if plain_start == -1:
|
||||
plain_start = i
|
||||
else:
|
||||
if plain_start != -1:
|
||||
parts.append(sql[plain_start:i])
|
||||
plain_start = -1
|
||||
parts.append(" ")
|
||||
i = token["end"]
|
||||
if plain_start != -1:
|
||||
parts.append(sql[plain_start:])
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def split_sql_statements(sql: str, dialect: ConnectorType | None = None) -> list[str]:
|
||||
"""Split SQL into individual statements, handling semicolons inside quoted contexts."""
|
||||
scan_token = _get_scanner(dialect)
|
||||
statements: list[str] = []
|
||||
stmt_start = 0
|
||||
i = 0
|
||||
n = len(sql)
|
||||
while i < n:
|
||||
if sql[i] == ";":
|
||||
trimmed = sql[stmt_start:i].strip()
|
||||
if trimmed:
|
||||
statements.append(trimmed)
|
||||
stmt_start = i + 1
|
||||
i += 1
|
||||
continue
|
||||
token = scan_token(sql, i)
|
||||
i = token["end"]
|
||||
trimmed = sql[stmt_start:].strip()
|
||||
if trimmed:
|
||||
statements.append(trimmed)
|
||||
return statements
|
||||
@@ -1,41 +0,0 @@
|
||||
"""
|
||||
DBHub 风格 SQL 执行与元数据探索。
|
||||
|
||||
**实现单一来源**:``backend/db/dbhub_tools.py``(含 ``execute_sql`` / ``execute_sql_all`` /
|
||||
``execute_sql_count_only`` / ``search_objects`` / ``probe_sql_execution_status`` / ``probe_sql_execution_status_ex``)。
|
||||
|
||||
本文件将 ``backend`` 加入 ``sys.path`` 后从 ``db`` 包转发,避免 ``tools/`` 与 ``backend/db`` 双份漂移。
|
||||
若你在本仓库内迭代 DB 工具逻辑,请直接修改 ``backend/db/dbhub_tools.py``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_root = Path(__file__).resolve().parents[1]
|
||||
_backend = _root / "backend"
|
||||
if _backend.is_dir() and str(_backend) not in sys.path:
|
||||
sys.path.insert(0, str(_backend))
|
||||
|
||||
from db.dbhub_tools import ( # noqa: E402
|
||||
DbHubTools,
|
||||
dbhub_tools,
|
||||
execute_sql,
|
||||
execute_sql_all,
|
||||
execute_sql_count_only,
|
||||
probe_sql_execution_status,
|
||||
probe_sql_execution_status_ex,
|
||||
search_objects,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DbHubTools",
|
||||
"dbhub_tools",
|
||||
"execute_sql",
|
||||
"execute_sql_all",
|
||||
"execute_sql_count_only",
|
||||
"probe_sql_execution_status",
|
||||
"probe_sql_execution_status_ex",
|
||||
"search_objects",
|
||||
]
|
||||
Reference in New Issue
Block a user