SUM函数中的子查询

时间:2017-05-23 08:42:44

标签: sql sql-server sql-server-2008 tsql

我想完成类似的事情:

,sell = (select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (0, 2))
,buy =  (select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (4))
,SUM(sell - buy)  AS current_balance --Invalid column name

...如上图所示,它在最后一行给出了错误。

2 个答案:

答案 0 :(得分:1)

错误是,如果您选择一个列并在select语句中给它一个别名,则不能在同一个select语句中将该别名用作列

试试这个: -

,sell = (select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (0, 2))
,buy =  (select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (4))
,SUM((select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (0, 2))
- (select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (4))) 

答案 1 :(得分:0)

PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter") .AddParameter("name", "Ethernet*") .AddParameter("ThrottleLimit", 5); 的回答:

给定的建议很容易发生变化,你也可以通过使用如下的子查询来解决这个问题:

IDictionary parameters = new Dictionary<String, String>();
parameters.Add("name", "Ethernet*");
parameters.Add("ThrottleLimit", 5);

PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter")
   .AddParameters(parameters)

这样,当您更改India.Rocketselect sell, buy, sell - buy AS current_balance from ( select sell = sum(select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (0, 2)) , buy = sum(select tr.money_value from dpdata.DP_Transaction tr where tr.transaction_type IN (4)) ) as Subquery 的定义时,您也不会忘记更改sell的定义以防止出现任何差异。