跨字段和返回字段标题的最大值

时间:2014-06-23 21:42:46

标签: sql max lookup teradata

我的查询结果如下:

    EMAIL   Business    Cars    CookingDIY  EntertainmentFashion    Family  French  Golf    HealthFitness   HomeGarden  Kids    NewsCulture Photography ScienceTech Spanish
1   duck@gmail.com  0   0   1   4   0   0   0   6   0   1   0   0   0   0
2   cat@gmail.com   9   18  0   1   0   0   0   0   18  0   19  0   17  0
3   dog@nl.gmail.com    0   0   1   0   0   0   0   0   0   0   0   0   0   0
4   bird@gmail.com  4   3   0   2   1   0   1   5   0   0   0   0   0   0
5   goat@gmail.com  1   0   3   7   2   0   0   1   2   0   1   0   0   0

我想为每条记录选择最大类别。因此,上面的第一条记录,duck @ gmail.com将在新字段中返回EnterntainmentFashion(4)。第二张唱片会让NewsCulture(19)返回。

这可能吗?

1 个答案:

答案 0 :(得分:1)

如何获得该结果,看起来像是一个透视查询。

如果您只想要三列作为结果,邮件 - 类别 - 计数,您只需撤消旋转并使用ROW_NUMBER:

select email, interest, count(*)
from tab
group by 1,2
qualify 
   row_number() over (partition by email order by count(*) desc) = 1

修改

根据您之前的问题,这可能是基于LIKE的数据透视查询,因此没有简单的方法来移除数据透视...

你的TD版本是什么?

在TD14中有一个最强大的功能,但它只限于10个值,所以你必须嵌套它:

case 
   when Business =   greatest(greatest(Business,Cars,CookingDIY,EntertainmentFashion,Family,French,Golf,HealthFitness,HomeGarden),greatest(Kids,NewsCulture,Photography,ScienceTech,Spanish)) then 'Business ('   || trim(Business)   || ')'
   when Cars =       greatest(greatest(Business,Cars,CookingDIY,EntertainmentFashion,Family,French,Golf,HealthFitness,HomeGarden),greatest(Kids,NewsCulture,Photography,ScienceTech,Spanish)) then 'Cars ('       || trim(Cars)       || ')'
   when CookingDIY = greatest(greatest(Business,Cars,CookingDIY,EntertainmentFashion,Family,French,Golf,HealthFitness,HomeGarden),greatest(Kids,NewsCulture,Photography,ScienceTech,Spanish)) then 'CookingDIY (' || trim(CookingDIY) || ')'
...
end

在你需要使用怪物CASE之前: - (

但是如果您不需要所有这些列,只需要具有最大值的列,您可以在计数之前加入包含所有LIKE通配符的表:

create volatile table interests(interest varchar(30), wildcard varchar(30)) on commit preserve rows;
insert into interests values('Business', 'your wildcard to determine business interest');
...one insert for each interest...

select t1.email, t2.interest, count(*)
from your_base_table as t1
join interests as t2
on t1.last_name like t2.wildcard
group by 1,2
qualify row_number() over (partition by email order by count(*) desc) = 1