在dbt中旋转带撇号的列

zazmityj  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(447)

我正试图用撇号旋转一列,但这在dbt中非常困难。有什么想法吗?我尝试了双引号,但dbt没有发现这一点,我不能在pivot中使用like语句。

{% set pvt_details=[
      ('General liability cover_rated_premium' , 'gl_premium')
    , ('Contractors' errors and omissions cover_rated_premium','eo_premium') ] %}
 WITH filtered AS (
     SELECT
     quote_id
    , target
    , premium_after_amount
 from {{ source('acdc', 'chopin_quote_rating_steps') }} cqrs
 WHERE target IN ({% for column in pvt_details %} '{{column[0]}}' {%- if not loop.last -%} 
, {%- endif %}
  {% endfor %})
    AND action = 'initial_premium'
  )
  select *
  from filtered
  pivot(sum(premium_after_amount)
   for target in ({% for column in pvt_details %} '{{column[0]}}' {%- if not loop.last -%} , 
{%- endif %}
{% endfor %}))
  as p (quote_id,
        {% for column in pvt_details %} {{column[1]}} {%- if not loop.last -%} , {%- endif 
%}
        {% endfor %})
y0u0uwnf

y0u0uwnf1#

{% set pvt_details=[
('General liability cover_rated_premium', 'gl_premium'),
("Contractor\\\'s errors and omissions cover_rated_premium", 'eo_premium') 
] %}

select
  concat_ws(' :: ',
    {% for column in pvt_details %} 
        '{{ column[0] }}'
    {%- if not loop.last -%},  {%- endif %}
    {% endfor %}
) as column_selection
from {{ ref('reference_model') }}
limit 1

Collapse

来自dbt的克里斯汀。jinja2似乎有一个问题,引用的方式,许多其他语言处理它=/。

hfwmuf9z

hfwmuf9z2#

在dbt宏中尝试此链接。有一个宏只用于枢轴。
https://github.com/fishtown-analytics/dbt-utils/blob/master/macros/sql/pivot.sql
将值从行透视到列。
例子:

Input: `public.test`

| size | color |
|------+-------|
| S    | red   |
| S    | blue  |
| S    | red   |
| M    | red   |

select
  size,
  {{ dbt_utils.pivot('color', dbt_utils.get_column_values('public.test',
                                                          'color')) }}
from public.test
group by size

Output:

| size | red | blue |
|------+-----+------|
| S    | 2   | 1    |
| M    | 1   | 0    |
``` `dbt_utils.pivot()` 论据:
column:列名,必需
值:要转换为列的行值列表,必需
别名:是否创建列别名,默认为true
agg:sql聚合函数,默认为sum
cmp:sql值比较,默认为=
前缀:列别名前缀,默认为空
后缀:列别名后缀,默认为空
then\u value:比较成功时使用的值,默认值为1
else\u value:比较失败时使用的值,默认值为0
quote\u identifiers:是否用双引号括住列别名,默认值为true

{% macro pivot(column,
values,
alias=True,
agg='sum',
cmp='=',
prefix='',
suffix='',
then_value=1,
else_value=0,
quote_identifiers=True) %}
{% for v in values %}
{{ agg }}(
case
when {{ column }} {{ cmp }} '{{ v }}'
then {{ then_value }}
else {{ else_value }}
end
)
{% if alias %}
{% if quote_identifiers %}
as {{ adapter.quote(prefix ~ v ~ suffix) }}
{% else %}
as {{prefix ~ v ~ suffix }}
{% endif %}
{% endif %}
{% if not loop.last %},{% endif %}
{% endfor %}
{% endmacro %}

kg7wmglp

kg7wmglp3#

如果他们想坚持自己的质疑,我怀疑他们会调出
“承包商的错误和遗漏包括\u额定\u保费”
以“承包商的错误和遗漏包括您使用的地方”
而不是“可能会修好吗?”?但不能百分之百确定是否还有其他问题。我认为UTILS的关键宏应该太好了!只是不确定它是否能很好地处理这个问题(我认为应该)。他们也不能在与pivot相同的步骤中重命名列(我认为这就是这里正在发生的事情),但是他们可以很容易地使用pivot函数,然后在随后的cte中重命名列
来自dbt的andrew

相关问题