简体   繁体   English

SQL服务器中如何在一个表中添加显示总行数的列

[英]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:所需的 output:

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

Thank you!谢谢!

You can use OVER clause, like this:您可以使用OVER子句,如下所示:

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.在 OVER 子句中,您可以使用类似于 GROUP BY 的 PARTITION BY。 For example, you can count the rows only for particular user:例如,您可以仅为特定用户计算行数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM