Compute By clause in SQL Server



We can use this clause to sum/count/avg/max/min so on. This clause will give you the output as detail and summary which is based on the fields you want to summarize.



select *
from #temp
order by student
compute sum(marks) by student


in above compute by clause, you must specify the field you want to sum in Compute clause and specify the field in By clause based on which field you need to compute.

Very important thing is you must specify the Order By clause in which specify the fileds whatever you specify in By clause in Compute clause.

The output of above query is,




When we try with max,min,avg, the query and output would be as shown below,


Using Max()

select * from #temp

order by student

compute max(marks) by student



Using Min ()

select * from #temp

order by student

compute min(marks) by student

Using Avg()

select * from #temp

order by student

compute avg(marks) by student






Comments

Popular posts from this blog

SQL SERVER – TRIM() Function – UDF TRIM()