简体   繁体   中英

count the instances of value in sub-query, update table

I am trying to count the number of times a value (mytype) appears within a distinct id value, and update my table with this count (idsubtotal) for each row. The table I have:

id   | mytype | idsubtotal
-----+--------+-----------
 44    red  
101    red     
101    red
101    blue
101    yellow
494    red
494    blue
494    blue
494    yellow
494    yellow

I need to calculate/update the idsubtotal column, so it is like:

id   | mytype | idsubtotal
-----+--------+-----------
 44    red      1
101    red      2    
101    red      2
101    blue     1
101    yellow   1
494    red      1
494    blue     2
494    blue     2
494    yellow   2
494    yellow   2

When I try this below, it is counting how many times the mytype value appears in the entire table, but I need to know how many times it appears within that sub-group of id values (eg How many times does "red" appear within id 101 rows, answer = 2).

SELECT id, mytype,
COUNT(*) OVER (PARTITION BY mytype) idsubtotal
FROM table_name

I know storing this subtotal in the table itself (versus calculating it live when needed) constitutes a bad data model for the table, but I need to do it this way in my case.

Also, my question is similar to this question but slightly different, and nothing I've tried to tweak using my very primitive understanding of SQL from the previous responses or other posts have worked. TIA for any ideas.

UPDATE table_name a
SET idsubtotal=(  SELECT COUNT(1)
                  FROM table_name  b
                  WHERE a.id=b.id
                  AND a.mytype=b.mytype
                )

When I try this below, it is counting how many times the mytype value appears in the entire table, but I need to know how many times it appears within that sub-group of id values (eg How many times does "red" appear within id 101 rows, answer = 2).

SELECT id, mytype, COUNT(*) 
FROM table_name
GROUP BY id, mytype 

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