在计算字段上重用别名

时间:2012-05-22 15:35:40

标签: mysql subquery

下午好,想知道是否有人能指出我正朝着正确的方向努力,因为我有点挣扎。我有一个mysql查询,我需要在计算字段中包含一个别名:

 Select tblComms._CommMonth, 
        tblComms._Reference, 
        tblComms._ClientName, 
        tblComms._Premium, 
        tblComms._CommDue, 
        tblComms._Employee_Name, 
        tblCont.Retention, 
        (tblComms._CommDue) * (tblCont.Retention) / 100 As Paid, 
        (tblComms._CommDue) - (Paid) As Payable 
 From tblComms Inner Join dbo_companyref On 
      dbo_companyref._Reference = tblComms._Reference 
      Inner Join tblCont 
      On dbo_companyref._Advisor_Name = tblCont._Employee_Name

这会在字段列表中返回错误“未知列'付费',有什么办法可以在创建后使用付费别名吗?我正在尝试推出一个在Access& amp;创建的新系统。 SQL,他们只是使用保存的查询/ SP ..

3 个答案:

答案 0 :(得分:3)

不允许。当别名和其他列处于SELECT的同一级别时,您不能将该列用作别名。

你可以使用别名,如果它是这样的 -

SELECT alias
FROM (SELECT column1 AS alias
      FROM table);

答案 1 :(得分:3)

你可以在mysql中使用变量:

Select tblComms._CommMonth, 
    tblComms._Reference, 
    tblComms._ClientName, 
    tblComms._Premium, 
    tblComms._CommDue, 
    tblComms._Employee_Name, 
    tblCont.Retention, 
    @Paid := (tblComms._CommDue) * (tblCont.Retention) / 100 As Paid, 
    (tblComms._CommDue) - (@Paid) As Payable From tblComms Inner Join dbo_companyref On 
  dbo_companyref._Reference = tblComms._Reference 
  Inner Join tblCont 
  On dbo_companyref._Advisor_Name = tblCont._Employee_Name

答案 2 :(得分:-1)

使用(select Paid)

 Select tblComms._CommMonth, 
    tblComms._Reference, 
    tblComms._ClientName, 
    tblComms._Premium, 
    tblComms._CommDue, 
    tblComms._Employee_Name, 
    tblCont.Retention, 
    (tblComms._CommDue) * (tblCont.Retention) / 100 As Paid, 
    (tblComms._CommDue) - (select Paid) As Payable 
  From tblComms Inner Join dbo_companyref On 
  dbo_companyref._Reference = tblComms._Reference 
  Inner Join tblCont 
  On dbo_companyref._Advisor_Name = tblCont._Employee_Name