Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a column that shows the number of times a value in another column appears without combining rows in SQL Server

I have a database that looks like this:

+----------------+
| Account Number | 
+----------------+
| A0001          |
| A0001          |
| A0001          |
| A0002          |
| A0003          |
| A0003          |
+----------------+

I need to create a column that has the number of times an Account Number appears without changing the number of rows.

I know that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT Account Number, COUNT(*) AS Counts
FROM database
GROUP BY Account Number

returns

+----------------+--------+
| Account Number | Counts |
+----------------+--------+
| A0001          | 3      |
| A0002          | 1      |
| A0003          | 2      |
+----------------+--------+

But I need something that looks like this:

+----------------+--------+
| Account Number | Counts |
+----------------+--------+
| A0001          | 3      |
| A0001          | 3      |
| A0001          | 3      |
| A0002          | 1      |
| A0003          | 2      |
| A0003          | 2      |
+----------------+--------+

I am using Microsoft SQL Server.

>Solution :

you can use count as a window function here:

Select AccountNumber, 
 count(*) over (partition by AccountNumber) as counts
from Table
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading