转置和标准

时间:2015-07-22 16:43:32

标签: where-clause teradata transpose

我想知道是否有更高效的编写下面的代码(这不起作用)。我试图转置一个数据集,但只想要Dogs和Cats大于1的值。因为在一个组中有猫和狗。

下面的代码不起作用,但我试图依据上述声明。请随时修改以下代码和/或提供更好的代码。提前谢谢!

    select 
    ,group_id
    ,sum(case when product = '18' then 1 else 0 end) as "Dogs"
    ,sum(case when product = '20' then 1 else 0 end) as "Cats"

    from risk_bl

    where dogs > 1 and cats > 1

    group by 1

1 个答案:

答案 0 :(得分:1)

尝试使用HAVING子句:

select 
,group_id
,sum(case when product = '18' then 1 else 0 end) as "Dogs"
,sum(case when product = '20' then 1 else 0 end) as "Cats"

from risk_bl
group by 1
having sum(case when product = '18' then 1 else 0 end) > 1 
and sum(case when product = '20' then 1 else 0 end)> 1

正如dnoeth指出的那样,Teradata允许你在你的having子句中使用别名(除其他外),所以你的having子句也可以读取:

 having dogs > 1 and cats > 1

在分组和聚合之后应用having子句,我认为这就是你想要的。