简体   繁体   中英

SQL count distinct values for each row

I got a table looking like this

+-----+---------+
|Group|Value    |
+-----+---------+
|A    |1        |
+-----+---------+
|B    |2        |
+-----+---------+
|C    |1        |
+-----+---------+
|D    |3        |
+-----+---------+

And I would like to add a column in my select command that count GROUP based on value, lookin like this:

+-----+---------+---------+
|Group|Value    | COUNT   |
+-----+---------+---------+
|A    |1        |2        |
+-----+---------+---------+
|B    |2        |1        |
+-----+---------+---------+
|C    |1        |2        |
+-----+---------+---------+
|D    |3        |1        |
+-----+---------+---------+

Value 1 got the two groups A and C the other values for each one in this example.

Additional is it possible to consider all values for VALUES and GROUP even if a WHERE filtered out some of them in the select query?

You want a window function:

select t.*, count(*) over (partition by value) as count
from t;

You have a problem if the query has a where clause. The where applies to the window function. So you need a subquery for the count:

select t.*
from (select t.*, count(*) over (partition by value) as count
      from t
     ) t
where . . .;

Or a correlated subquery might be convenient under some circumstances:

select t.*,
       (select count(*) from t t2 where t2.value = t.value) as count
from t
where . .  .;

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