简体   繁体   中英

query postgres for distinction across two columns

i have a database with the following table

Col1 | Col2 | Col3  |  
 A   | C     | data1
 A   | B     | data2
 B   | A     | data3
 A   | D     | data4
 C   | A     | data5

I need a query that will select all distinct rows across Col1 and Col2 (So AC == CA), but I need to count the total.

So my return might be like

Combo| Count
AC | 2
AB | 2
AD | 1

This looks like a simple aggregation query with a twist because the ordering is not important:

select least(col1, col2) || greatest(col1, col2), count(*) as cnt
from t
group by least(col1, col2) || greatest(col1, col2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM