sql - 不同的值何时可以在列之间互换
问题描述
我有以下查询 -
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 行是相同的值(它们只是在不同的列中)。
解决方案
使用LEAST
andGREATEST
对这两个值进行排序。
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;
推荐阅读
- c# - 如何将一个表数据与另一个表数据匹配然后显示匹配的数据?ASP.NET MVC
- typescript - 只读字段未正确呈现
- excel-formula - 在 Excel 中查找重复项并创建波段
- ios - Swift 合并处理 Flatmap 中的错误
- pyspark - 如何使用类型提示优化 PySpark toPandas()
- python - 正则表达式用于匹配括号之间的数据,但带有要匹配的模式
- java - 在 Scala 注释中使用 Java 枚举的“简单表达式的非法开始”
- python - asyncio.start_unix_server 和 redis 的套接字错误
- javascript - 我如何让 JavaScript 在没有扩展的情况下在 chrome 上运行
- nginx - 具有多个域的 Nginx 负载均衡器