Hi I have a question about SUM in sql,
I have a query that looks like this
SELECT
SUM ( table_one.field + table_two.field ) as total_field
SUM ( total_field + table_one.anotherfield )
FROM
table_one
JOIN
table_two ON table_one.id = table_two.id
WHERE
table_one = 1
But this doesn't work ( dont mind possible typing errors in JOIN statement, only the second SUM is the probly the query works perfecly without that SUM)
Is there another way to do it, as I need the total_field within my application. I can ofcource add those numbers within the application but I prefer to do it in sql.
You cannot use the column alias in an aggregate to reference the value, just SUM again;
SELECT
SUM ( table_one.field + table_two.field ) as total_field, --your missing a , also
SUM ( table_one.field + table_two.field + table_one.anotherfield )
FROM
table_one
JOIN
table_two ON table_one.id = table_two.id
WHERE
table_one = 1
SUM is an aggregate function. This means you can aggregate data from a field over several tuples and sum it up into a single tuple.
What you want to do is this:
SELECT
table_one.field + table_two.field,
table_one.field + table_two.field + table_one.anotherfield
or maybe this:
SELECT
SUM(table_one.field) + SUM(table_two.field),
SUM(table_one.field) + SUM(table_two.field) + SUM(table_one.anotherfield)
Try replacing "total_field" with "table_one.field + table_two.field" in second SUM().
The name "total_field" is an alias and as such cannot be used in an aggregate functions
The easiest and quickest way is to simply replace the code for total_field in the second calculation.
SELECT
SUM ( ISNULL(table_one.field,0) + ISNULL(table_two.field,0) ) as total_field
SUM ( ISNULL(table_one.field,0) + ISNULL(table_two.field,0) + IsNUll(table_one.anotherfield,0) )
from
table_one
As your code doesn't cater for a null value in the fields you may get warnings when sum the values. I would suggest using IsNull as above and if there is a null value just treat it as 0.
You could use a subquery like this:
SELECT
total_field,
total_field + sum_anotherfield
FROM (
SELECT
SUM(table_one.field + table_two.field) AS total_field,
SUM(table_one.anotherfield) AS sum_anotherfield
FROM
table_one
JOIN
table_two ON table_one.id = table_two.id
WHERE
table_one.somefield = 1
) x
Related
Here I have two tables as student_information and exmaination_marks.
examination_marks table have 3 columns for three subjects and include their marks.
I want to select the roll_number and name of the student from the student_information table where sum of the three subject's marks in examination_marks table is less than 100.
Both table has roll_number as primary key.
Here is the query I wrote.
select
si.roll_number,
si.name
from
student_information as si
left outer join examination_marks as em on
si.roll_number = em.roll_number
where
sum(em.subject_one + em.subject_two + em.subject_three) < 100;
But I got an error saying "ERROR 1111 (HY000) at line 1: Invalid use of group function"
Can any one help me with this?
sum(em.subject_one + em.subject_two + em.subject_three)< 100
this is the problem . Try these
Where (SELECT subject_one + subject_two + subject_three FROM examination_marks WHERE em.roll_number = si.roll_number) < 100
SUM is an "aggregate function" which can only be used inside a query which has a GROUP BY clause.
To get the sum of values within the same row you need to use the + operator. If the columns are NULL-able then you'll also need to use COALESCE (or ISNULL) to prevent NULL values invalidating your entire expression.
Like so:
SELECT
si.roll_number,
si.name,
COALESCE( em.subject_one, 0 ) + COALESCE( em.subject_two, 0 ) + COALESCE( em.subject_three, 0 ) AS sum_marks
FROM
student_information AS si
LEFT OUTER JOIN examination_marks AS em ON
si.roll_number = em.roll_number
WHERE
COALESCE( em.subject_one, 0 ) + COALESCE( em.subject_two, 0 ) + COALESCE( em.subject_three, 0 ) < 100;
(If you're wondering why the COALESCE( em.subje... expression is repeated in the SELECT and WHERE clauses, that's because SQL is horribly designed by (obscene profanities) is an unnecessarily verbose language).
hello I have an SQL query that selects a SUM value in the first column and I want the second column to be ( first_column / another_field )
select sum(a.amount), (sum(a.amount) / d.total_loading_weight * 1000) as MarginPerTon
from tra_affair a join tra_Delivery d on a.delivery=d.delivery_id
where a.delivery='394179' and a.is_margin='1'
I am getting the "not a single-group group function" error
The problem is: d.total_loading_weight. I'm not sure what you want, but something like:
select sum(a.amount),
(sum(a.amount) / sum(d.total_loading_weight * 1000)) as MarginPerTon
from tra_affair a join
tra_Delivery d
on a.delivery = d.delivery_id
where a.delivery = '394179' and a.is_margin = '1';
You can also use min() or max() instead of sum() if the values are always the same.
I am trying to to run a query like the one below. The goal is to get the total activity count for every user_key but because the user_key has a complex structure and I need only the part after the '|' symbol I had to use a substring function. However, when I'm trying to run the query, I get the
error:
SQL Error [42Y36]: Column reference 'USER_KEY' is invalid, or is part of an invalid expression. For a SELECT list with a GROUP BY, the columns and expressions being selected may only contain valid grouping expressions and valid aggregate expressions.
The substring function works OK outside this query. Any workarounds for this problem? Using Splice Machine (NoSql)
SELECT
substr(user_key, instr(user_key,'|') + 1) AS new_user_key,
SUM(
CAST(
activity_count AS INTEGER
)
) AS Total
FROM
schema_name.table_name
GROUP BY
substr(user_key, instr(user_key,'|') + 1)
Your GROUP BY column needs to match the SELECT
SELECT
substr(user_key, instr(user_key,'|') + 1) AS new_user_key,
SUM(
CAST(
activity_count AS INTEGER
)
) AS Total
FROM
schema_name.table_name
GROUP BY
substr(user_key, instr(user_key,'|') + 1) AS new_user_key
I found the answer myself. I used a table subquery:
SELECT new_table.new_user_key, sum(new_table.total)
from
(
SELECT
substr(user_key, instr(user_key,'|') + 1) AS new_user_key,
CAST(activity_count AS INTEGER) AS Total
FROM schema_name.table_name
)
as new_table
GROUP BY
new_table.new_user_key
Let's hope someone will find this post useful and will save some time to him or her.
I project a column in my select statement. ("project" in the relational algebra sense.) With the goal of reducing code duplication, is there a way to reference that projected column in my where clause? Or is there a better way to do that?
Example:
select
(A.Column + A.Column2) * 8 'Column'
from A
where
(A.Column + A.Column2) * 8 < 1000
Basically, what I'm asking, if we think of columns as being "namespaced" by table (where A is a namespace and A.Column is the Column in the A namespace), is: is there a way to refer to the namespace for the ephemeral table we're currently selecting in the where clause of that table itself?
Another way is to use cte, common table expression.
with cte as(
select (A.Column + A.Column2) * 8 as [Column] from A
)
Select * from cte
Where [Column] < 1000
You can do it;
select * from
(
select (A.Column + A.Column2) * 8 as Col from A
) tmp
where Col<1000
I created this CTE that returns first and last names from 2 different tables. I would like to use the CTE to identify all of the records that have the same last names and the first name of one column starts with the same first letter of another column.
This is an example of the results of the CTE. I want the SELECT using the CTE to return only the highlighted results:
;WITH CTE AS
(
SELECT AD.FirstName AS AD_FirstName, AD.LastName AS AD_LastName, NotInAD.FirstName As NotInAD_FirstName, NotInAD.LastName As NotInAD_LastName
FROM PagingToolActiveDirectoryUsers AD JOIN
(
SELECT FirstName, LastName
FROM #PagingUsersParseName
EXCEPT
SELECT D.FirstName, D.LastName
FROM PagingToolActiveDirectoryUsers D
WHERE D.FirstName <> D.LastName AND D.LastName <> D.LoginName
AND D.LoginName LIKE '%[0-9]%[0-9]%'
) AS NotInAD ON NotInAD.LastName = AD.LastName
)
SELECT *
FROM CTE
WHERE (AD_LastName = NotInAD_LastName) AND (AD_FirstName LIKE ('''' + SUBSTRING(NotInAD_FirstName, 1, 1) + '%'''))
ORDER BY AD_LastName, AD_FirstName;
The result of this query returns no rows.
What am I doing wrong?
Thanks.
You're enclosing the string to be searched for with single-quotes, but it doesn't appear that the data in AD_FirstName has those single-quotes embedded in it. I suggest you replace the first line of the WHERE clause with
WHERE (AD_LastName = NotInAD_LastName) AND (AD_FirstName LIKE (SUBSTRING(NotInAD_FirstName, 1, 1) + '%'))
Best of luck.