我正在使用mssql并且在使用子查询时遇到问题。真正的查询非常复杂,但它具有与此相同的结构:
select
customerName,
customerId,
(
select count(*)
from Purchases
where Purchases.customerId=customerData.customerId
) as numberTransactions
from customerData
我想要做的是按交易次数排序表,但是当我使用
时order by numberTransactions
它告诉我没有这样的领域。是否有可能做到这一点?我应该使用某种特殊关键字,例如this
或self
?
答案 0 :(得分:8)
使用字段编号,在这种情况下:
order by 3
答案 1 :(得分:7)
有时您必须与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应为这两种解决方案提供相同的计划。
答案 2 :(得分:4)
进行内部联接。它更容易,更易读。
编辑:嘿Nathan,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等)构建查询
答案 3 :(得分:2)
有更好的方法来获取结果,但只是从您的示例查询中,这将适用于SQL2000或更好。
如果您将别名包裹在单个刻度'numberTransactions'中,然后调用 ORDER BY'numberTransactions'
select
customerName,
customerId,
(
select count(*)
from Purchases
where Purchases.customerId=customerData.customerId
) as 'numberTransactions'
from customerData
ORDER BY 'numberTransactions'
答案 4 :(得分:0)
使用GROUP BY
和JOIN
可以实现同样的目的,您将摆脱子查询。这也可能更快。
答案 5 :(得分:0)
我认为您可以在SQL 2005中执行此操作,但不能在SQL 2000中执行此操作。
答案 6 :(得分:-1)
您需要复制逻辑。 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)
此外,使用别名,它们使您的代码更易于阅读和维护。 ;)