sql - 每行红移数据库中列出的最受欢迎的类别
问题描述
我需要以下数据:例如瑞典男性品牌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 列条目都是空的。有人可以帮忙吗?
解决方案
如果对于每个客户,您想要最常用于 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
推荐阅读
- swiftui - 在 SwiftUI TabView 中动态隐藏选项卡 - 选项卡在更多...溢出项中混合
- r - 用下一个更高的因子水平替换因子值
- github-pages - Jekyll 主题未加载
- r - 在R中合并具有不同列名的数据框
- python - 处理多种情况的最佳方法
- picker - 在 App Script 的 Google 选择器中过滤多种文件类型
- java - 将具有 json 数组属性的 JSON 对象转换为 java 对象时收到以下错误
- azure - Azure 服务总线接收和删除
- function - 如何从另一个文件调用函数
- aerospike - 通过端口转发访问 Kubernetes 中的 Aerospike 集群?