1、创建一个临时表,用于演示sqlserver统计记录行数count及其子语句的使用方式IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;CREATE TABLE #tmp1( Col1 varchar(50), Col2 varchar(200), Col3 int );
2、往临时表中插入几行测试数据,其中部分字段的Col2栏位值插入相同值insert into #tmp1(Col1, Col2, Col3) va造婷用痃lues('Code1', '张三', 95);insert into #tmp1(Col1, Col2, Col3) values('Code2', '李四', 96);insert into #tmp1(Col1, Col2, Col3) values('Code3', '王五', 92);insert into #tmp1(Col1, Col2, Col3) values('Code4', '张麻子', 98);insert into #tmp1(Col1, Col2, Col3) values('Code5', '李四', 93);
3、查询临时表中的测试数据select * from #tmp1;
4、使用count(*)统计出临时表的记录行数,这是很长见的统计行数使用方式select COUNT(*) from #tmp1
5、使用count(1)统计出临时表的记录行数,这里仅仅使用1替换掉了星号,据说这样效率更高select COUNT(1) from #tmp1
6、使用count子语句,统计Col2列不相同值的行数,如果将distinct放到count外面,从结果可以看出,并没有达到预期的效果select distinct COUNT(Col2) from #tmp1
7、使用count子语句,统计Col2列不相同值的行数,这个时候就需要将distinct放到count里面去select COUNT(distinct Col2) from #tmp1