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 add a column that shows the total number of rows in a table in SQL Server

I’ve got this table and I wish to add a column that gives the total number of rows in the table:

Table now:

Name         PAT_ID        
---------------------
Brian          123
Brian          356
Brian          3546
Brian          987

Desired output:

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

Name         PAT_ID       TOTAL     
------------------------------------
Brian          123          4
Brian          356          4
Brian          3546         4
Brian          987          4

Thank you!

>Solution :

You can use OVER clause, like this:

CREATE TABLE PATIENT (
  Name VARCHAR(255) NOT NULL,
  PAT_ID INT NOT NULL
);

INSERT INTO PATIENT (Name, PAT_ID)
VALUES ('Brian', 123), ('Brian', 356), ('Brian', 3546), ('Brian', 987);

SELECT *
     ,COUNT(*) OVER () AS [total]
FROM PATIENT

In the OVER clause, you can use PARTITION BY which is like GROUP BY. For example, you can count the rows only for particular user:

SELECT *
     ,COUNT(*) OVER (PARTITION BY Name) AS [total]
FROM PATIENT
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