You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用DBT验证表中symbol_type等三字段的唯一组合?

验证多字段组合唯一性的DBT测试方案

方案1:使用DBT内置unique测试

直接在模型的schema.yml配置文件中,针对目标字段组合添加唯一性测试,不同数据库写法略有差异:

支持多字段参数的数据库(如Postgres、BigQuery)

可直接传入字段数组:

models:
  - name: your_table_name  # 替换为你的数据表名
    columns:
      - name: symbol_type
      - name: symbol_subtype
      - name: taker_symbol
    tests:
      - unique:
          column_name: [symbol_type, symbol_subtype, taker_symbol]

不支持多字段参数的数据库(如MySQL)

通过concat拼接字段生成唯一键,若字段可能为NULL,需用coalesce处理避免拼接结果为NULL:

models:
  - name: your_table_name
    columns:
      - name: symbol_type
      - name: symbol_subtype
      - name: taker_symbol
    tests:
      - unique:
          column_name: "concat(coalesce(symbol_type, 'NULL'), '|', coalesce(symbol_subtype, 'NULL'), '|', coalesce(taker_symbol, 'NULL'))"

运行测试命令:

dbt test --select your_table_name

注:内置测试仅提示存在重复,不会返回具体重复组合。


方案2:自定义测试返回重复组合

如果需要直接获取重复的字段组合及重复次数,创建自定义测试:

  1. 在项目tests目录下新建unique_symbol_combo.sql文件:
select
  symbol_type,
  symbol_subtype,
  taker_symbol,
  count(*) as duplicate_count
from {{ ref('your_table_name') }}  -- 替换为你的数据表名
group by symbol_type, symbol_subtype, taker_symbol
having count(*) > 1
  1. 在schema.yml中引用该自定义测试:
models:
  - name: your_table_name
    tests:
      - unique_symbol_combo  # 对应tests目录下的SQL文件名
  1. 运行自定义测试:
dbt test --select test.unique_symbol_combo

测试失败时,控制台会输出所有重复的字段组合及对应重复次数。


注意事项

  • 数据库默认不会将NULL与NULL视为重复值,若需包含NULL场景的验证,必须用coalesce将NULL替换为特定标识后再处理。
  • 若测试的是源表而非模型,需将{{ ref('your_table_name') }}替换为{{ source('your_source_name', 'your_table_name') }}。

内容的提问来源于stack exchange,提问作者Harris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:30:59