如何比较具有相同年份和月份的相似行ID的两行中的值?

问题描述 投票:0回答:1

我想检测具有相同component_id的行,其中值不同,但月份和年份的日期相同。

连接多个表后我的派生表-

component_id  value  date         id
1             100    2019-12-31   1
2             400    2019-12-31   2
1             111    2019-12-20   3
2             400    2018-12-20   4
1             221    2019-12-30   5

所需的数据格式-

id1    id2    value1    value2    date1        date2        component_id  

1      3      100       111      2019-12-31   2019-12-20      1

1      5      100       221      2019-12-31   2019-12-30      1

3      5      111       221      2019-12-20   2019-12-30      1 

我无法找出SQL代码。请帮助。

sql postgresql
1个回答
0
投票

这听起来像是自我加入:

select t1.*, t2.*
from t t1 join
     t t2
     on t1.component_id = t2.component_id and
        t1.value <> t2.value and
        date_trunc('month', t1.date) = date_trunc('month', 2.date) and
        t1.id < t2.id;

您可以使用CTE,因此不必为派生表重复逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.