首页 > 解决方案 > 每行红移数据库中列出的最受欢迎的类别

问题描述

我需要以下数据:例如瑞典男性品牌A EUR 瑞典女性品牌A EUR 瑞典男性品牌B EUR england 男性品牌A EUR england 女性品牌A EUR england 男性品牌B EUR england 女性品牌C EUR

欧元来自这样一个事实,即 8000 人中,5000 人使用欧元,2000 人使用 gbp,1000 人使用 SEk。所以最受欢迎的货币是欧元。我希望它显示在每一行

获取最受欢迎的货币,max_curr

并且对于返回的每一行都有一个名为 max_curr 的列,并显示该值

    select 
cdl.country
,cd.gender
,cd.brand
,t.max_curr
from customer_data_list cdl  
left join customer_data cd on cd.customerid = cdr.customerid
left join 
(
    select 
        trans.customerid, a.*
    from
    (
        select
            a.*
            ,max(count_currency) over() as max_curr
        FROM
        (
            select 
                t.currency
                ,count(t.currency) as count_currency
            from transactions t
            where t.function = 'DEPOSIT' and t.status = 'ACCEPTED' 
            group by t.currency
            order by currency
        ) a
    ) a
    left join transactions trans on trans.currency = a.currency 
    where count_currency = max_curr) t on t.customerid = cdl.customerid 

这没有返回我需要的内容,因为大多数 max_curr 列条目都是空的。有人可以帮忙吗?

标签: sqlamazon-redshift

解决方案


如果对于每个客户,您想要最常用于 ACCEPTED、DEPOSIT 交易的货币,那么您可以使用聚合和窗口函数:

select cc.*
from (select t.customerid, t.currency, count(*) as cnt,
             row_number() over (partition by t.customerid order by count(*) desc) as seqnum
      from transactions t
      where t.function = 'DEPOSIT' and
            t.status = 'ACCEPTED' 
      group by t.customerid, t.currency
     ) cc
where seqnum = 1;

编辑:

对于问题的修订解释,只需使用交叉连接:

select t.customerid, t.currency, count(*) as cnt,
       tt.currency as most_popular_currency
from transactions t cross join
     (select t.currency
      from transactions t
      where t.function = 'DEPOSIT' and
            t.status = 'ACCEPTED'
      group by t.currency
      order by count(*) desc
      limit 1
     ) tt
where t.function = 'DEPOSIT' and
      t.status = 'ACCEPTED' 
group by t.customerid, t.currency

推荐阅读