SQL 选择总和()从(选择(选择())
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13256813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SELECT SUM() FROM (SELECT (SELECT ())
提问by rlp
I have a correct working T-SQL-script in this form
我有这种形式的正确工作 T-SQL 脚本
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 selectI supposed this to work, however, it does not. I keep getting "Incorrect syntax near."
从 select 中读取select count(*)我认为这可以工作,但是,它没有。我不断收到“附近有错误的语法”。
I do not know if it is important but that is here named columnA is itself maked by a SELECT statement.
我不知道这是否重要,但这里命名的 columnA 本身是由 SELECT 语句生成的。
回答by Taryn
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
回答by Dominic Goulet
There is absolutely no problem whatsoever to achieve what you want. We don't see your entier query, but the most common problem is people forget to add an alias to their nested select
statement. Take a look at this sample that works perfectly :
要实现你想要的,绝对没有任何问题。我们没有看到您的 entier 查询,但最常见的问题是人们忘记为他们的嵌套select
语句添加别名。看看这个完美运行的示例:
select sum(col1) as sum1
from ( select col1
from ( select 1 col1 union all select 2 union all select 3 ) tmp
) tmp2
According to the OP, here is your final query :
根据 OP,这是您的最终查询:
SELECT SUM(numbers)
FROM (
SELECT columnA
AS
'numbers'
FROM tableA
WHERE clause
) tmp