如何在SQL查询中使用计算列

时间:2012-01-24 21:24:33

标签: sql sql-server

我不知道这个问题的标题是否被理解,但我的意思是这个。

我有一张销售表,我需要“格式化”表格,添加查询一些列以指示总数,更改率(我从另一个表中获取)和以其他货币评级的总金额。

所以我的查询如下:

SELECT SalesID,SalesType,SalesDate,CurrencyType,
       case when CurrencyType = 1 then Total else 0 AS TotalOnLocalCurrency,
       case when CurrencyType = 2 then Total else 0 AS TotalOnOtherCurrency,
      (TotalOnLocalCurrency/dbo.GetCurrencyRate(SalesDate)) + TotalOnOtherCurrency) Total
FROM Sales

如果这种情况可能,我的意思是我试图这样做,但我收到了这个错误:

  

无效的列名称'TotalOnLocalCurrency'。

4 个答案:

答案 0 :(得分:2)

您可以将整个公式放在后续行中,也可以使用CROSS APPPLY

SELECT SalesID,
       SalesType,
       SalesDate,
       CurrencyType,
       TotalOnLocalCurrency,
       TotalOnOtherCurrency,
      (TotalOnLocalCurrency/dbo.GetCurrencyRate(SalesDate)) + TotalOnOtherCurrency Total
FROM Sales
CROSS APPLY (SELECT CASE WHEN CurrencyType = 1 then Total else 0) CxA(TotalOnLocalCurrency)
CROSS APPLY (SELECT case when CurrencyType = 2 then Total else 0) CxB(TotalOnOtherCurrency)

答案 1 :(得分:1)

您收到错误是因为您对表达式CurrencyType = 1 then Total else 0 AS TotalOnLocalCurrency设了别名。您不能在同一个select子句中引用别名列名,这违反了逻辑查询处理规则。相反,要么引用表达式本身,要么将表达式包装在表表达式中,并根据表表达式进行查询。

答案 2 :(得分:0)

您不能使用在同一查询中引入的列别名。如果您使用的是SQL Server 2005及更高版本,我将使用CTE(公用表表达式)来处理此问题。

;WITH SalesData AS
(
    SELECT 
        SalesID, SalesType, SalesDate, CurrencyType,
        TotalOnLocalCurrency = CASE WHEN CurrencyType = 1 THEN Total ELSE 0 END,
        TotalOnOtherCurrency = CASE WHEN CurrencyType = 2 THEN Total ELSE END 
    FROM Sales
)
SELECT 
   SalesID, SalesType, SalesDate, CurrencyType,
   TotalOnLocalCurrency, TotalOnOtherCurrency,
   Total = (TotalOnLocalCurrency/dbo.GetCurrencyRate(SalesDate)) + TotalOnOtherCurrency) 
FROM  
   SalesData

答案 3 :(得分:0)

尝试更多类似的内容:

select 
SalesID,SalesType,SalesDate,CurrencyType,
TotalOnLocalCurrency,TotalOnOtherCurrency,
TotalOnLocalCurrency/dbo.GetCurrencyRate(SalesDate)) + TotalOnOtherCurrency as total from
(
    SELECT SalesID,SalesType,SalesDate,CurrencyType,
           case when CurrencyType = 1 then Total else 0 END AS TotalOnLocalCurrency,
           case when CurrencyType = 2 then Total else 0 END AS TotalOnOtherCurrency
    FROM Sales) t