如何在SQL中引用自定义字段

时间:2020-03-06 14:19:53  来源:igfitidea点击:

我正在使用mssql,但在使用子查询时遇到了麻烦。真正的查询非常复杂,但其结构与此相同:

select 
  customerName, 
  customerId,
  (
    select count(*) 
    from Purchases 
    where Purchases.customerId=customerData.customerId
  ) as numberTransactions
from customerData

我想做的是按事务数对表进行排序,但是当我使用

order by numberTransactions

它告诉我没有这样的领域。是否有可能做到这一点?我应该使用某种特殊关键字,例如" this"或者" self"吗?

解决方案

使用字段编号,在这种情况下:

order by 3

做一个内部联接。它更容易且更具可读性。

select 
customerName,
customerID,
count(*) as numberTransactions
from
    customerdata c inner join purchases p on c.customerID = p.customerID
group by customerName,customerID
order by numberTransactions

编辑:嗨,弥敦道,

我们意识到我们可以将整个表作为子项内部连接吗?

Select T.*, T2.*
From T inner join 
(select 
customerName,
customerID,
count(*) as numberTransactions
from
    customerdata c inner join purchases p on c.customerID = p.customerID
group by customerName,customerID
) T2 on T.CustomerID = T2.CustomerID
order by T2.numberTransactions

或者,如果这样不好,我们可以使用临时表(#T1等)构造查询

我们需要重复逻辑。 SQL Server在我们命名的列上不是很聪明,但不是FROM语句中数据集的一部分。

所以用

select 
  customerName, 
  customerId,
  (
    select count(*) 
    from Purchases p
    where p.customerId = c.customerId
  ) as numberTransactions
from customerData c
order by (select count(*) from purchases p where p.customerID = c.customerid)

另外,使用别名,它们使代码更易于阅读和维护。 ;)

使用GROUP BYJOIN可以实现相同的目的,而我们将摆脱子查询。这可能也会更快。

我认为我们可以在SQL2005中执行此操作,但不能在SQL2000中执行此操作。

有时,我们必须为SQL的语法而苦恼(子句的预期范围)

SELECT *
FROM
(
select
  customerName,
  customerId,
  (
    select count(*)
    from Purchases
    where Purchases.customerId=customerData.customerId
  ) as numberTransactions
from customerData
) as sub
order by sub.numberTransactions

另外,使用JOIN的解决方案是正确的。查看查询计划,SQL Server应该为两个解决方案提供相同的计划。

有更好的方法来获得结果,但是仅从示例查询中就可以在SQL2000或者更高版本上使用。

如果我们将别名包装在单个记号'numberTransactions'中,然后调用ORDER BY'numberTransactions'

select
  customerName, 
  customerId,
  (
    select count(*) 
    from Purchases 
    where Purchases.customerId=customerData.customerId
  ) as 'numberTransactions'
from customerData
ORDER BY 'numberTransactions'