Skip to content
Advertisement

Count amount of same value

I have a simple task which I to be honest have no idea how to accomplish. I have these values from SQL query:

| DocumentNumber | CustomerID |
------------------------------
|  AAA           |     1      |
|  BBB           |     1      |
|  CCC           |     2      |
|  DDD           |     3      |
-------------------------------

I would like to display a bit modified table like this:

| DocumentNumber | CustomerID |  Repeate |
-----------------------------------------
|  AAA           |     1      | Multiple |
|  BBB           |     1      | Multiple |
|  CCC           |     2      | Single   |
|  DDD           |     3      | Single   |
------------------------------------------

So, the idea is simple – I need to append a new column and set ‘Multiple’ and ‘Single’ value depending on if customer Id exists multiple times

Advertisement

Answer

Use window functions:

select t.*,
       (case when count(*) over (partition by CustomerId) = 1 then 'Single'
             else 'Multiple'
        end) as repeate
from t;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement