我是一个SQL菜鸟,所以在这里寻求帮助。我有一个示例查询,如下所示。现在我想修改查询,以便我可以对同一查询中的Test,Test1和Test2值执行以下操作:
OutputValue = Test + Test1 - Test2
然后显示OutputValue的结果以及Test,Test1& TEST2。
SELECT
CAST(balancefwd.Shares AS NUMERIC) / 1000 AS Test,
SUM(CAST(booksdata.sharesissued AS NUMERIC) / 1000) AS Test1,
SUM(CAST(booksdata.sharesretired AS NUMERIC) / 1000) AS Test2
FROM
SQLTest.TestBooks.dbo.booksdata booksdata
JOIN
SQLTest.TestBooks.dbo.balancefwd balancefwd ON booksdata.companynumber = balancefwd.companynumber
WHERE
booksdata.CompanyNumber= '<number>'
GROUP BY
balancefwd.shares
有什么建议吗?
答案 0 :(得分:1)
您可以将查询包装在另一层中:
SELECT t.*, t.test + t.test1 - t.test2 as total
FROM (Select cast(balancefwd.Shares as numeric)/1000 as Test,
sum(cast(booksdata.sharesissued as numeric)/1000)as Test1,
sum(cast(booksdata.sharesretired as numeric)/1000)as Test2
from SQLTest.TestBooks.dbo.booksdata booksdata
join SQLTest.TestBooks.dbo.balancefwd balancefwd on booksdata.companynumber=balancefwd.companynumber
where booksdata.CompanyNumber= '<number>')
然后可以使用派生列。
虽然你的查询看起来有点不对..你想在这做什么?为什么没有分组条款?表中只有1条记录吗?为什么要总结test1
和test2
而不是test
?
答案 1 :(得分:0)
以下是问题的答案: 给子查询命名(t1)我能够对派生值执行算术运算。
Select t1.Test, t1.Test1, t1.Test2, t1.Test+t1.Test1-t1.Test2 as OutputValue from
(SELECT
CAST(balancefwd.Shares AS NUMERIC) / 1000 AS Test,
SUM(CAST(booksdata.sharesissued AS NUMERIC) / 1000) AS Test1,
SUM(CAST(booksdata.sharesretired AS NUMERIC) / 1000) AS Test2
FROM
SQLTest.TestBooks.dbo.booksdata booksdata
JOIN
SQLTest.TestBooks.dbo.balancefwd balancefwd ON booksdata.companynumber = balancefwd.companynumber
WHERE
booksdata.CompanyNumber= '<number>'
GROUP BY
balancefwd.shares) t1