首页 > 解决方案 > SQL Postgres比较同一张表中的数据

问题描述

我有一个“费用”表,在这个表中我有一个 ID、一个描述、一个价格和一个位置。我要做的是生成一个与表中的描述匹配的查询,并为我提供一个位置的两个定价列。到目前为止,我能做的最好的事情是在两个位置之间重复:

select charge1.description, charge1.price price1, charge2.price price2
from charge charge1 inner join
(
    select * from charge
) charge2
on LOWER(charge1.description) = LOWER(charge2.description) 
where charge1.id != charge2.id 
and charge1.location != charge2.location;

这将给出如下结果:

Description | price1 | price2
-----------------------------
burger      | 5      | 10
burger      | 10     | 5
steak       | 40     | 20
steak       | 20     | 40

我想要这样的结果:

Description | price1 | price2
-----------------------------
burger      | 5      | 10
steak       | 40     | 20

标签: sqlpostgresql

解决方案


这是你想要的吗?

select c1.description, c1.price as price1, c2.price as price2
from charge c1 inner join
     charge c2
     on LOWER(c1.description) = LOWER(c2.description) 
where c1.id < c2.id and c1.location <> c2.location;

我认为没有location必要进行比较,但如果没有样本数据,我不确定这是否属实。


推荐阅读