简体   繁体   中英

SQL Count elements in pairs

I have a simple table

CREATE TABLE aaa AS
(
  ogid integer NOT NULL,
  ocolor character varying(80) NOT NULL,
  vgid integer NOT NULL,
  vcolor character varying(80) NOT NULL,
)

aa contains some values, like in this example

Ogid OColor Vgid VColor
1   v       1   v
1   v       5   r
1   v       8   g
2   r       5   r
3   g       7   r
4   g       5   r
5   r       7   r
5   r       9   g
6   g       6   g

I need to count the number of elements in every couple (OColor, VColor) grouping together simmetric couples ( for example the elements of gr and rg go together ).

I need a result similar to:

OColor Vcolor nelement
b      b      10
b      g      16
g      v      2 

If I understand correctly, you can just use least() and greatest() :

select least(ocolor, vcolor), greatest(ocolor, vcolor), count(*)
from table t
group by least(ocolor, vcolor), greatest(ocolor, vcolor);

However, your question is confusing because the results seem to have nothing to do with the sample data.

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