简体   繁体   English

在SQL中是否也可以计算不同值的数量?

[英]Is it possible in SQL to count the number of distinct values as well?

I am thinking that this statement will and should pick the distinct values from my table and then also have a count of them or at least that is what I would like in a separate column. 我认为该语句将并且应该从我的表中选择不同的值,然后还要对它们进行计数,或者至少这是我希望在单独的列中得到的值。 Is it possible to count the number of distinct values in SQL, from what I am gathering probably not. 是否有可能从我收集的数据中不算出SQL中不同值的数量。

Question: Can I count the number of distinct values of last names? 问题:我可以计算姓氏的不同值的数量吗?

SQL Statement: SQL语句:

select distinct c.LastName as 'Distinct Last Names', COUNT(*)
from Customer as c;

Error: 错误:

Msg 8120, Level 16, State 1, Line 1
Column 'Customer.LastName' is invalid in the select list because it is not contained 
in either an aggregate function or the GROUP BY clause.

Output -- Without the count 输出-无计数

'Distinct Last Names' “不同的姓氏”

LTest1 LTest2 LTest3 LTest1 LTest2 LTest3

Since you donot have a Group by clause in the query, All your columns in the Select should use some kind of an aggregation or else SQL will not be happy. 由于查询中没有Group by子句,因此Select中的所有列都应使用某种聚合,否则SQL将不满意。

Try this 尝试这个

select COUNT(distinct c.LastName) 'Distinct Last Names'
from Customer as c;

If I understand your question correctly, you want the result in two columns. 如果我正确理解了您的问题,则希望将结果分为两列。

If so, you can use Group By . 如果是这样,您可以使用“ 分组依据”

SELECT c.LastName as 'Distinct Last Names', COUNT(*) 
FROM Customer as c
GROUP BY c.LastName

I'd use a subquery for this. 我会为此使用子查询。 The inner query returns a distict list of last names. 内部查询返回姓氏的离散列表。 The outer query counts the distict values. 外部查询将计算离散值。 I prefer count(1) over count(*) because there's no need to return metadata for all of the columns in the customer table. 与count(*)相比,我更喜欢count(1),因为不需要为客户表中的所有列返回元数据。

SELECT COUNT(1)
FROM (
    SELECT DISTINCT LASTNAME 
    FROM CUSTOMER
) a

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

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