从相同 table 的两列中查找值相同的数据

Finding data where the value is the same in two columns from the same table

所以我有一个简单的 table 来保存我们每天提供给客户的物品和用户实际使用的物品。

date         |  offered_name  |  used_name  |  h_id
----------------------------------------------------------
2019-06-20   | Obsidian       |  Obsidian   |  100
2019-06-20   | Obsidian       |  Limestone  |  101
2019-06-20   | Limestone      |  Sandstone  |  102
2019-06-21   | Obsidian       |  Limestone  |  100
2019-06-21   | Obsidian       |  Sandtone   |  101
2019-06-21   | Limestone      |  Limestone  |  102

我想找到所提供的物品与二手物品相匹配的所有实例。用户可以更改他们的 used_item,所以我只关心他们是否至少匹配过一次 offered_name。如果他们从未匹配过,那么我不想 select 他们。上面的输出看起来像:

h_id  | used_offered_item_at_least_once
---------------------------------------
100   | 1 
101   | 0 
102   | 1 

类似于这个问题SQL - find all instances where two columns are the same,但我想比较两个不同的列,而不是只检查一个。

您可以使用 group by 和 having:

select h_id, count(1) "used_offered_item_at_least_once" from your_table
where offered_name  = used_name
group by h_id
having count(1) = 1 

您可以使用conditional aggregation

select h_id,
       cast(sign(sum(case when offered_name = used_name then 
          1 
       else
          0
       end)) as int) as used_offered_item_at_least_once
  from tab
 group by h_id

我会用 case 表达式来写这个:

select id,
       max(case when offered_name = used_name then 1 else 0 end) as used_offered_item_at_least_once
from t
group by id;

我想不出更简单的方式来表达逻辑。