Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for count()

Tags:

sql-server

I have used the count() function to calculate each of the rows values

select course, count(*) course_count from student_table
group by course;

Without using count() is there any alternative to accomplish this?

like image 273
Siddharth Avatar asked Sep 01 '25 03:09

Siddharth


2 Answers

You could use SUM(1) instead:

SELECT
    course,
    SUM(1) AS course_count
FROM student_table
GROUP BY
    course;

SUM(1) happens to behave the same way as count here, because it sums 1 for each record. However, COUNT in fact is the semantically correct function to use here.

like image 194
Tim Biegeleisen Avatar answered Sep 02 '25 19:09

Tim Biegeleisen


You can also use the below way.

CREATE TABLE Account
( Account_id Int, AccountName varchar(20));

INSERT INTO Account (Account_id, AccountName) 
Values (1, 'Test'), (2, 'Test A'), (3, 'Test A'), (4, 'Test C'), (5, 'Test D')

Select AccountName, Max(CntTotal) as CntTotal from(
Select AccountName,
    ROW_NUMBER() OVER (Partition By AccountName Order By AccountName) as CntTotal
from Account
)a group by AccountName

Online Demo

like image 40
Suraj Kumar Avatar answered Sep 02 '25 19:09

Suraj Kumar