在Access中组合两个SQL查询

时间:2017-09-27 12:41:00

标签: sql ms-access

我今天早上已经尝试了几个小时左右,将两个访问(Access 365)查询合并到一个语句中,以便我可以运行报告。我已经在论坛上阅读并尝试了各种组合,但却无法让它们发挥作用。我不是一个SQL大师,并且想知道是否有人可以提供帮助并指出我哪里出错了。

我有一个表(数据),它有2个相关列 审核用户名,出勤参考名称, 每次创建订单时都会记录, 如果它是电子的,则用户名是" DRIP"如果手动输入,则获取登录的用户名。

我想要的是每个请求者一行,第一列是请求者名称(出席参考名称),第2列是请求者出现的次数(请求总数),第3列请求者的总次数以电子方式制作(电子请求总数) 所以我可以制作第4列,以便显示请求者的电子请求百分比

我工作的是两个查询

工作表(用记事本写 - 我在访问中省略了 - 行):

    --Total number of unique requests per requester
    SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of requests]
    FROM Data
    GROUP BY Data.[Attendance Ref Name]

    --Total Number of unique requester received electronically per Requester.
    SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of Electronic requests]FROM Data WHERE (((Data.[Audit Username])="DRIP"))
    GROUP BY Data.[Attendance Ref Name];

我尝试了什么:

    SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name]) AS [Total Number of requests]FROM Data
    UNION
    SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name]) AS [Total Number of Electronic requests]FROM Data WHERE (((Data.[Audit Username])="DRIP"))
    GROUP BY Data.[Attendance Ref Doctor Name];

    SELECT
    (SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name])FROM Data) AS [Total Number of requests],
    (SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name])FROM Data WHERE Data.[Audit Username]="DRIP")AS [Total Number of Electronic requests]

我甚至经历了https://www.w3schools.com/sql/default.asp教程

但我无法让任何有能力帮助的人工作,让我摆脱困境? 提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要使用联接将第一个和第二个查询的结果链接在一起。

假设所有引用名称都在两个表中,您可以使用以下内容:

SELECT q1.[Attendance Ref Name], q1.[Total Number of requests], q2.[Total Number of Electronic requests]
FROM (
    SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of requests]
    FROM Data
    GROUP BY Data.[Attendance Ref Name]
) AS q1
INNER JOIN (
    SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of Electronic requests]FROM Data WHERE (((Data.[Audit Username])="DRIP"))
    GROUP BY Data.[Attendance Ref Name]
) AS q2
ON q1.[Attendance Ref Name] = q2.[Attendance Ref Name]