patternMinor
count multiple occurences of attribute values for each row in sql
Viewed 0 times
eachsqloccurencesforattributemultiplevaluescountrow
Problem
I have a
With
I only get
But what I would like as a result is
How to achieve this?
mytable structured as follows and I would like to count occurences of values for attribute in each row:id | attribute
--------------
1 | spam
2 | egg
3 | spamWith
SELECT id, attribute, COUNT(attribute) FROM mytable GROUP BY attributeI only get
id | attribute | count
----------------------
1 | spam | 2
2 | egg | 1But what I would like as a result is
id | attribute | count
----------------------
1 | spam | 2
2 | egg | 1
3 | spam | 2How to achieve this?
Solution
select
m1.id,
m1.attribute,
(select count(*) from mytable m2 where m2.attribute = m1.attribute)
from
mytable m1
;Another version:
select
m1.id,
m1.attribute,
m2.c
from
mytable m1
join (SELECT attribute, COUNT(attribute) as c FROM mytable GROUP BY attribute) m2
on (m1.attribute = m2.attribute)
;A better version for databases with analytic/window functions:
select
m1.id,
m1.attribute,
count(*) over (partition by m1.attribute)
from
mytable m1
;Code Snippets
select
m1.id,
m1.attribute,
(select count(*) from mytable m2 where m2.attribute = m1.attribute)
from
mytable m1
;select
m1.id,
m1.attribute,
m2.c
from
mytable m1
join (SELECT attribute, COUNT(attribute) as c FROM mytable GROUP BY attribute) m2
on (m1.attribute = m2.attribute)
;select
m1.id,
m1.attribute,
count(*) over (partition by m1.attribute)
from
mytable m1
;Context
StackExchange Database Administrators Q#176860, answer score: 9
Revisions (0)
No revisions yet.