简体   繁体   English

在子查询,更新表中计算值的实例

[英]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. 我试图计算一个值(mytype)出现在一个不同的id值中的次数,并用此计数(idsubtotal)为每一行更新我的表。 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: 我需要计算/更新idsubtotal列,所以就像:

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). 当我在下面尝试此操作时,它计算的是mytype值在整个表中出现的次数,但是我需要知道它在id值子组中出现了多少次(例如,“ red”在其中出现了多少次) ID 101行,答案= 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. 另外,我的问题与此问题相似,但略有不同,并且我从以前的回答或其他帖子中对SQL的原始理解中,也没有尝试进行任何调整。 TIA for any ideas. TIA有任何想法。

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). 当我在下面尝试此操作时,它计算的是mytype值在整个表中出现的次数,但是我需要知道它在id值子组中出现了多少次(例如,“ red”在其中出现了多少次) ID 101行,答案= 2)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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