Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT SUM() FROM (SELECT (SELECT ())

I have a correct working T-SQL-script in this form

SELECT  columnA
        AS
        'numbers'
FROM    tableA
WHERE   clause

This script gives me as one column, called numbers, of integers. I want to sum these.

Calling the above lines 'script' I tried the following setup

SELECT  SUM(numbers)
FROM    (
            script
        )

Reading select count(*) from select I supposed this to work, however, it does not. I keep getting "Incorrect syntax near."

I do not know if it is important but that is here named columnA is itself maked by a SELECT statement.

like image 218
rlp Avatar asked Nov 06 '12 18:11

rlp


People also ask

How do I sum in SELECT query?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

How do I get the sum of a column in SQL?

The SUM() function returns the total sum of a numeric column.

How do I use the sum function in SQL?

SQL SUM function is used to find out the sum of a field in various records. You can take sum of various records set using GROUP BY clause. Following example will sum up all the records related to a single person and you will have total typed pages by every person.

Can we use sum function in WHERE clause?

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.


1 Answers

You need an alias on the subquery:

SELECT  SUM(numbers)
FROM    
(
    script  -- your subquery will go here
) src   -- place an alias here

So your full query will be:

select sum(numbers)
from
(
   SELECT  columnA  AS numbers
   FROM    tableA
   WHERE   clause
) src
like image 147
Taryn Avatar answered Oct 09 '22 22:10

Taryn