简体   繁体   English

如何在SQL中显示计数值,而不是列出同一表中的许多行?

[英]How can I show a count value in SQL instead of listing out many rows in the same table?

How can I show a count value in SQL dependent on the value of a field. 如何根据字段的值在SQL中显示计数值。 If I have a table called Orders that has a CustomerID: 如果我有一个名为Orders的表,该表具有一个CustomerID:

CustID
Cust1
Cust2
Cust3
Cust1

How can I have it display repetition count: 如何显示重复次数:

CustID  RepCount
Cust1     2
Cust2     1
Cust3     1
Cust1     2
SELECT CustID, COUNT(CustID) as 'RepCount'
FROM Table1
GROUP BY CustID

You can also have result by this small query 您也可以通过此小查询获得结果

First get a count grouped by custID in a sub query then join back.. If window sets worked in mysql, over partition by custID would be a better approach avoiding a subquery, as it doesn't... a subquery is needed. 首先在子查询中获得按custID分组的计数,然后再加入。如果窗口集在mysql中有效,则按custID对分区进行分区将是避免子查询的更好方法,因为它不需要...需要子查询。

SELECT O.custID, B.RepCount 
FROM Orders O
INNER JOIN (SELECT count(*) RepCount, CustID 
            FROM Orders 
            GROUP BY CustID) B
  ON B.CustId = O.custID

This approach is needed if you really want to see the same cust# listed multiple times. 如果您确实希望多次看到相同的客户编号,则需要这种方法。 If not then a simple select count and group by would work. 如果没有,那么简单的选择计数和分组依据就可以了。 (as others have illustrated) (正如其他人所说明的)

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

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