我有以下疑问:
select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
如果我将所有对count(column_name)的调用替换为count(*),会有什么不同?
这个问题的灵感来自于如何在Oracle中查找表中的重复值。
为了澄清接受的答案(可能是我的问题),将count(column_name)替换为count(*)将在结果中返回一个额外的行,其中包含null值和列中空值的计数。
我们可以使用Stack Exchange Data Explorer通过一个简单的查询来说明两者的区别。Stack Overflow数据库中的Users表的列通常为空,就像用户的Website URL一样。
-- count(column_name) vs. count(*)
-- Illustrates the difference between counting a column
-- that can hold null values, a 'not null' column, and count(*)
select count(WebsiteUrl), count(Id), count(*) from Users
如果您在Data Explorer中运行上述查询,您将看到count(Id)和count(*)的计数是相同的,因为Id列不允许空值。但是,WebsiteUrl计数要低得多,因为该列允许为空。
COUNT(*)语句指示SQL Server返回表中的所有行,包括null。
COUNT(column_name)只检索行上具有非空值的行。
请参阅SQL Server 2008的测试执行代码:
-- Variable table
DECLARE @Table TABLE
(
CustomerId int NULL
, Name nvarchar(50) NULL
)
-- Insert some records for tests
INSERT INTO @Table VALUES( NULL, 'Pedro')
INSERT INTO @Table VALUES( 1, 'Juan')
INSERT INTO @Table VALUES( 2, 'Pablo')
INSERT INTO @Table VALUES( 3, 'Marcelo')
INSERT INTO @Table VALUES( NULL, 'Leonardo')
INSERT INTO @Table VALUES( 4, 'Ignacio')
-- Get all the collumns by indicating *
SELECT COUNT(*) AS 'AllRowsCount'
FROM @Table
-- Get only content columns ( exluce NULLs )
SELECT COUNT(CustomerId) AS 'OnlyNotNullCounts'
FROM @Table
我们可以使用Stack Exchange Data Explorer通过一个简单的查询来说明两者的区别。Stack Overflow数据库中的Users表的列通常为空,就像用户的Website URL一样。
-- count(column_name) vs. count(*)
-- Illustrates the difference between counting a column
-- that can hold null values, a 'not null' column, and count(*)
select count(WebsiteUrl), count(Id), count(*) from Users
如果您在Data Explorer中运行上述查询,您将看到count(Id)和count(*)的计数是相同的,因为Id列不允许空值。但是,WebsiteUrl计数要低得多,因为该列允许为空。