MS Access Union,Order By 弄乱了我的查询顺序

MS Access Union, Order By mess up my query order

SQL:

SELECT 
    SUM(dbo_SO_SalesHistory.DollarsSold) AS SumDollarsSold,  
    "PHOA" As CustomerNo
FROM  
    dbo_SO_SalesHistory
WHERE 
    ((dbo_SO_SalesHistory.[CustomerNo]) IN ("PHOM","PHOB", "PHOA", "HOMP")) 
    AND ((dbo_SO_SalesHistory.InvoiceDate) BETWEEN [BeginDate] AND [EndDate])

UNION

SELECT TOP 9 
    SUM(DollarsSold), CustomerNo 
FROM 
    dbo_SO_SalesHistory
WHERE 
    ((dbo_SO_SalesHistory.CustomerNo) NOT IN ("PHOM","PHOB", "PHOA", "HOMP")) 
    AND ((dbo_SO_SalesHistory.InvoiceDate) BETWEEN [BeginDate] AND [EndDate])
GROUP BY 
    dbo_SO_SalesHistory.CustomerNo 
ORDER BY 
    1 DESC;

当我 运行 分别查询两个时,查询的第二部分返回我期望的输出:

但是当我 运行 它和 UNION 一起时,顺序就有点混乱了:

在代码ORDER BY 1 DESC中,1指的是第一列,即总和。

我试过了

ORDER BY SUM(dbo_SO_SalesHistory.DollarsSold) DESC;

而是 returns 一个错误:

Err3

如有任何建议,我们将不胜感激!

更新:这是当前查询输出:

[]

所需的输出如下所示:

(我从图1中剪切并粘贴了第2~10行)。我希望这将有助于您的理解!

我当前的查询:

Sum of Dollar | Customer
--------------+----------
     10       |    A   
      8       |    B
      1       |    Q

所需的查询输出

14 | B_Total
10 | A
 5 | C

B_Total (14) 是 X (4), Y (3), Z (2) AND B (5)

更新:当前查询

SELECT 
    SumDollarsSold, CustomerNo, MyOrder 
FROM 
    (SELECT 
         SUM(dbo_SO_SalesHistory.DollarsSold) AS SumDollarsSold, 
         "PHOALLE" AS CustomerNo, 1 AS MyOrder
     FROM 
         dbo_SO_SalesHistory
     WHERE 
         ((dbo_SO_SalesHistory.[CustomerNo]) IN ("PHOMIN","PHOALLE","PHOBROO","PHOMP"))  
         AND ((dbo_SO_SalesHistory.InvoiceDate) Between [BeginDate] And [EndDate])
     UNION
     SELECT TOP 9 
         SUM(DollarsSold), CustomerNo, 2 as MyOrder 
     FROM 
         dbo_SO_SalesHistory
     WHERE 
         ((dbo_SO_SalesHistory.CustomerNo) NOT IN ("PHOM","PHOA","PHOB","PHOM")) 
         AND ((dbo_SO_SalesHistory.InvoiceDate) Between [BeginDate] And [EndDate])
     GROUP BY 
         dbo_SO_SalesHistory.CustomerNo
     ORDER BY 
         1 DESC
) a 
ORDER BY 
    MyOrder, SumDollarsSold DESC;

当您使用 UNION 时,无法保证任何顺序,因此您将丢失您已经在第二个查询中完成的 ORDER BY。您可以添加另一个字段以确保第一条记录始终位于最前面,但您需要将其包含在所选字段中。像这样:

SELECT 
    SumDollarsSold, CustomerNo, MyOrder 
FROM 
    (SELECT 
         SUM(dbo_SO_SalesHistory.DollarsSold) AS SumDollarsSold, 
         "PHOA" AS CustomerNo, 1 AS MyOrder
     FROM 
         dbo_SO_SalesHistory
     WHERE 
         ((dbo_SO_SalesHistory.[CustomerNo]) IN ("PHOM","PHOB", "PHOA", "PHOM"))  
         AND ((dbo_SO_SalesHistory.InvoiceDate) Between [BeginDate] And [EndDate])
     UNION
     (SELECT TOP 9 
         SUM(DollarsSold), CustomerNo, 2 as MyOrder 
     FROM 
         dbo_SO_SalesHistory
     WHERE 
         ((dbo_SO_SalesHistory.CustomerNo) NOT IN ("PHOM","PHOB", "PHOA", "PHOM")) 
         AND ((dbo_SO_SalesHistory.InvoiceDate) Between [BeginDate] And [EndDate])
     GROUP BY 
         dbo_SO_SalesHistory.CustomerNo
     ORDER BY 
         SUM(DollarsSold) DESC)
) a 
ORDER BY 
    MyOrder, SumDollarsSold DESC;