Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sum function in where clause in SQL Server?

I am new to SQL Server. I want to equal two columns using sum function. Please find the below query.

select top 1000 
    o.orderamount, sum(oi.amount), oi.orderid 
from 
    orders o 
inner join 
    orderitem oi on o.orderid = oi.orderid 
where 
    orderamount = sum(oi.amount)
group by  
    oi.orderid, orderamount
order by 
    oi.orderid desc

Whenever I execute this code, I get an error.

Please help me.

like image 271
Pavan Reddy Avatar asked Dec 04 '17 07:12

Pavan Reddy


People also ask

Can we use SUM () in WHERE SQL?

In SQL, we use the SUM() function to add the numeric values in a column. It is an aggregate function in SQL. The aggregate function is used in conjunction with the WHERE clause to extract more information from the data.

How do I SUM in SQL Server?

SQL Server SUM() Function The SUM() function calculates the sum of a set of values. Note: NULL values are ignored.

Can we use SUM function in having clause?

Example - Using SUM function You could also use the SQL SUM function to return the name of the department and the total sales (in the associated department). The SQL HAVING clause will filter the results so that only departments with sales greater than $1000 will be returned.

How do you write a SUM function in SQL?

Example - With Single Expression SELECT SUM(salary) AS "Total Salary" FROM employees WHERE salary > 25000; In this SQL SUM Function example, we've aliased the SUM(salary) expression as "Total Salary". As a result, "Total Salary" will display as the field name when the result set is returned.


1 Answers

You can just use HAVING:

select  top 1000 o.orderamount, sum(oi.amount), oi.orderid 
from orders o 
inner join orderitem oi on o.orderid = oi.orderid 
group by oi.orderid ,orderamount
HAVING orderamount = sum(oi.amount)
order by oi.orderid desc
like image 87
gotqn Avatar answered Nov 15 '22 07:11

gotqn