根据其他列选择列中的值

我有两个表,信息和交易记录。 信息看起来像这样:

customer ID Postcode 1 ABC 123 2 DEF 456

交易如下:

customer ID day frequency 1 1/1/12 3 1 3/5/12 4 2 4/6/12 2 3 9/9/12 1

我想知道每个邮递区号哪一天出现频率最高。

我知道如何从两个不同的表中进行引用,但是我不太确定如何根据其值将多个列引用到其他列。

输出应该是这样的:

customer ID postcode day frequency 1 ABC 123 3/5/12 4 2 DEF 456 4/6/12 2 3 GHI 789 9/9/12 1

以此类推。

WANGHUGANG 回答:根据其他列选择列中的值

您可以使用相关子查询进行过滤:

select
    i.*,t.day,t.frequency
from info i
inner join transactions t on t.customerID = i.customerID
where t.frequency = (
    select max(t.frequency)
    from info i1
    inner join transactions t1 on t1.customerID = i1.customerID
    where i1.postcode = i.postcode
)

或者,如果您的RBDMS支持窗口功能,则可以使用rank()

select *
from (
    select
        i.*,t.frequency,rank() over(partition by i.postcode order by t.frequency desc)
    from info i
    inner join transactions t on t.customerID = i.customerID
) t
where rn = 1
本文链接:https://www.f2er.com/3121111.html

大家都在问