下面的這篇微軟官方文件,介紹了SQL Server中的GROUP BY語句:
SELECT - GROUP BY- Transact-SQL
其中這裡有說到,如果GROUP BY後面的列中有NULL值,那麼SQL Server會將GROUP BY列中所有的NULL值認為是相等的,並將NULL歸類到一個GROUP中:
If a grouping column contains NULL values, all NULL values are considered equal, and they are collected into a single group.
例如,下面的Students表的Grade列中有兩行NULL值:
SELECT [Id] ,[Name] ,[Grade] ,[Age] FROM [dbo].[Students];
如果我們在查詢中去GROUP BY列Grade,那麼SQL Server會認為那兩行NULL值是相等的,所以最後GROUP BY查詢後,會將Grade列中的NULL值歸類到一個GROUP:
SELECT Grade,COUNT(*) as [Count] FROM [dbo].[Students] GROUP BY Grade;