首页 > 解决方案 > 不同的值何时可以在列之间互换

问题描述

我有以下查询 -

select distinct v.npi1, v.npi2, 
count(*)
from hcpc cross join lateral
     (values (f_rend, f_bill), (f_rend, t_rend), (f_rend, t_bill), (f_bill, t_rend), 
     (f_bill, t_bill), (t_rend, t_bill)
     ) v(npi1, npi2)
     where 
     npi1 <> npi2
     and npi1 <> ''
     and npi2 <> ''
     group by v.npi1, v.npi2

它正在产生这样的结果 -

npi1    npi2        count
1033543 1295706         8
1225257 129570666       1
1295706 1033543         17

我如何得到这个结果 -

npi1    npi2        count
1033543 1295706         25
1225257 129570666       1

这是因为第 1 行和第 3 行是相同的值(它们只是在不同的列中)。

标签: sqlpostgresql

解决方案


使用LEASTandGREATEST对这两个值进行排序。

select
  least(v.npi1, v.npi2) as value1,
  greatest(v.npi1, v.npi2) as value2,
  count(*)
from hcpc cross join lateral
     (values (f_rend, f_bill), (f_rend, t_rend), (f_rend, t_bill), (f_bill, t_rend), 
     (f_bill, t_bill), (t_rend, t_bill)
     ) v(npi1, npi2)
where npi1 <> npi2
  and npi1 <> ''
  and npi2 <> ''
group by least(v.npi1, v.npi2), greatest(v.npi1, v.npi2)
order by value1, value2;

推荐阅读