如何通过在同一查询中创建的字段(MS ACCESS)对查询返回的记录记录进行排序

时间:2019-05-21 17:29:15

标签: sql ms-access ms-office

查询(对于这个问题,我认为您不需要查看架构):

SELECT Agencies.AgencyName, (SELECT DISTINCT MAX(Invoices.CostsTotal) FROM Invoices WHERE Contracts.ContractID = Invoices.ContractID) AS MaxInvoice
FROM Contracts 
LEFT JOIN Agencies ON Contracts.AgencyID = Agencies.AgencyID
ORDER BY MaxInvoice DESC;

我们如何通过在同一查询中创建的字段对查询返回的记录集进行排序?

我看过功能FIELDS(INDEX)吗?但这在访问中不存在吗?也不确定它是否会正常工作。在这种情况下,我想按MaxInvoice字段对记录集进行排序。

当我尝试运行此查询时,MS Access会提示我输入MaxInvoice的参数值

2 个答案:

答案 0 :(得分:2)

您可以编写父 SELECT 来包裹当前的SELECT。 像这样:

SELECT * FROM (
 SELECT Agencies.AgencyName, 
 (SELECT DISTINCT MAX(Invoices.CostsTotal) FROM Invoices 
 WHERE Contracts.ContractID = Invoices.ContractID) AS MaxInvoice
 FROM Contracts LEFT JOIN Agencies 
 ON Contracts.AgencyID = Agencies.AgencyID
) AS ContractsLargestInvoice
ORDER BY ContractsLargestInvoice.MaxInvoice DESC;

答案 1 :(得分:2)

大多数SQL方言支持在ORDER BY中使用别名。但是MS Access比大多数数据库都离SQL标准更远。

我建议您重写查询以将Invoices移到FROM子句中-使用聚合来获取所需的内容:

SELECT a.AgencyName, MAX(i.CostsTotal) AS MaxInvoice
FROM (Contracts as c LEFT JOIN
     Agencies as a 
     ON c.AgencyID = a.AgencyID) LEFT JOIN
     Invoices as i
     ON i.ContractID = c.ContractID
GROUP BY a.AgencyName
ORDER BY MAX(i.CostsTotal) DESC;

您使用LEFT JOIN并从 second 表而不是第一个表中选择一个字段似乎很奇怪。这可能是NULL