clickhouse中数组的使用

需求如下:

表flight_sale_history:

     discount: 折扣

     air_code: 航班号

表discount_cabin:

     air_code: 航班号

     discount: 折扣

     cabin: 舱位数组

要求对flight_sale_history中的每一条记录,求出discount_cabin中折扣最接近的舱位数组的第一个舱位。

想法:

1. 将discount_cabin变成每个air_code一条记录,discount和cabin变成一个数组字段。

SELECT air_code, groupArray(array(toString(discount), cabin[1])) d2 FROM discount_cabin GROUP BY air_code

这里用到了array()把两个值变成一个数组, groupArray把一组值变成一个大数组。因为array不支持浮点数和字符串放一起, 所以需要将浮点数变成字符串

2. 将flight_sale_history和上面的SQL join, 对上面的大数组,对flight_sale_history中discount和大数组的discount的差值的绝对值排序,第一个就是折扣最接近的那个。

arraySort(x -> abs(h.discount - toFloat32(d2[1])), d2)

完整的SQL为

select h.air_code, arraySort(x -> abs(h.discount - toFloat32(d2[1])), d2)[1][2] from flight_sale_history h inner join

(SELECT air_code, groupArray(array(toString(discount), cabin[1])) d2 FROM discount_cabin GROUP BY air_code) d on h.air_code=d.air_code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值