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.
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.
SQL Server SUM() Function The SUM() function calculates the sum of a set of values. Note: NULL values are ignored.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With