访问SQL - 订单联合查询彼此独立

时间:2018-03-28 18:56:27

标签: sql ms-access

我正在为我们的团队自动化一些数据透视表,并且已经成功地重新创建了一个汇总表,该汇总表能够按区域获取所有相关数字,然后使用带有以下代码的union包含汇总行:

SELECT region, round(sum(iif([Entered In Portal] = "Y", 1, 0)) / count(*) * 
100,1) & "%" as [% Entered]
from tblITPortalYTD
where [Compliance Reporting Month] = Forms!frmMonth!Month
group by region
UNION ALL 
SELECT "Total" as region, round(sum(iif([Entered In Portal] = "Y", 1, 0))  / 
count(*) * 100,1) & "%" as [% Entered]
from tblITPortalYTD
where [Compliance Reporting Month] = Forms!frmMonth!Month;

这样可以导致第一个查询返回按区域排序,第二个查询显示为附加到底部作为摘要行。问题是,最好让其中一个区域出现在总行的正上方(超出正常的字母顺序)。

示例:a,b,c,d,e,f,摘要 - > a,c,d,e,f,b,摘要

我尝试使用ORDER BY IIF(Region = A,1,IIF(region = B,2,3))排序方法,但它不起作用。如果我单独在第一个查询上使用此方法,则排序完美,但将其与UNION ALL组合会将其覆盖为其原始状态。

这可能吗?

1 个答案:

答案 0 :(得分:0)

您无法在UNION查询中进行真正的排序。您需要将结果集包装在子查询中,然后按顺序排序:

SELECT * 
FROM
(
    SELECT region
        ,round(sum(iif([Entered In Portal] = "Y", 1, 0)) / count(*) * 100, 1) & "%" AS [% Entered]
    FROM tblITPortalYTD
    WHERE [Compliance Reporting Month] = Forms ! frmMonth ! Month
    GROUP BY region

    UNION ALL

    SELECT "Total" AS region
        ,round(sum(iif([Entered In Portal] = "Y", 1, 0)) / count(*) * 100, 1) & "%" AS [% Entered]
    FROM tblITPortalYTD
    WHERE [Compliance Reporting Month] = Forms ! frmMonth ! Month
)subquery
ORDER BY IIF(Region = A, 1, IIF(region = B, 2, 3))

但是现在,你的总排不能保证在底部抖动。要修复,您可以为每个查询添加一个排序列:

SELECT region , [% Entered] 
FROM
(
    SELECT region
        ,round(sum(iif([Entered In Portal] = "Y", 1, 0)) / count(*) * 100, 1) & "%" AS [% Entered]
        ,IIF(Region = A, 1, IIF(region = B, 2, 3)) as myorder
    FROM tblITPortalYTD
    WHERE [Compliance Reporting Month] = Forms ! frmMonth ! Month
    GROUP BY region

    UNION ALL

    SELECT "Total" AS region
        ,round(sum(iif([Entered In Portal] = "Y", 1, 0)) / count(*) * 100, 1) & "%" AS [% Entered],
        99999 as myorder
    FROM tblITPortalYTD
    WHERE [Compliance Reporting Month] = Forms ! frmMonth ! Month
)subquery
ORDER BY myorder

并根据需要进行调整。