左连接子查询访问

Posted

技术标签:

【中文标题】左连接子查询访问【英文标题】:left join subquery access 【发布时间】:2016-08-24 10:26:40 【问题描述】:

以下代码可以正常工作(即不会出错)但是它连接了来自子查询“e”的所有内容。我希望它只返回 [Total Cancellations] 而不是 [Business Unit]

感谢帮助

SELECT *
FROM (SELECT c.*,b.[Total Bookings]
FROM (SELECT DISTINCT a.[business unit], count(a.[lookup_id]) as [Total Colleagues in DMS]
FROM EVERYTHING AS a
GROUP BY a.[business unit]

)  AS c 


LEFT JOIN (SELECT a.[business unit], count(a.[lookup_id]) as [Total Bookings]
FROM EVERYTHING AS a
WHERE a.[session_code]is not null
GROUP BY a.[business unit]

)  AS b ON c.[business unit]=b.[business unit]

)  AS d LEFT JOIN (SELECT a.[business unit], count(a.[lookup_id]) as [Total Cancellations]
FROM EVERYTHING AS a
WHERE a.[Has Booking been cancelled (Yes / No)]=1
group by a.[business unit]

)  AS e ON d.[business unit]=e.[business unit];

    enter code here

【问题讨论】:

您正在使用SELECT *,我希望它会从连接查询中返回 all 列。通过明确提及您要保留的列来限制这一点。 如何在响应中发布代码?谢谢 请不要将您的查询作为评论发布! 什么是访问?您是说 MS Access 吗?标签明确建议不要将 access 用于 MS Office 程序,而应使用 ms-access。也调整标题。 【参考方案1】:

这样试试,

   SELECT d.[business unit]
    ,d.[Total Colleagues in DMS]
    ,d.[Total Bookings]
    ,e.[Total Cancellations]
--,f.columnname
FROM (
    SELECT c.*
        ,b.[Total Bookings]
    FROM (
        SELECT DISTINCT [business unit]
            ,count([lookup_id]) AS [Total Colleagues in DMS]
        FROM EVERYTHING
        GROUP BY [business unit]
        ) c
    LEFT JOIN (
        SELECT [business unit]
            ,count([lookup_id]) AS [Total Bookings]
        FROM EVERYTHING
        WHERE [session_code] IS NOT NULL
        GROUP BY [business unit]
        ) b ON c.[business unit] = b.[business unit]
    ) d
LEFT JOIN (
    SELECT [business unit]
        ,count([lookup_id]) AS [Total Cancellations]
    FROM EVERYTHING
    WHERE [Has Booking been cancelled (Yes / No)] = 1
    GROUP BY [business unit]
    ) e ON d.[business unit] = e.[business unit];
    --LEFT JOIN (....) f ON ...

【讨论】:

太棒了。效果很好。谢谢 您可以投票或选择适合您的答案。 如果我需要进一步添加左连接,我该怎么做?再次感谢 再次感谢您的帮助。我更改了查询并添加了额外的 LEFT JOIN 但它出错了。非常感激。不知道我哪里错了。

以上是关于左连接子查询访问的主要内容,如果未能解决你的问题,请参考以下文章

使用子查询改进 MySql 查询左外连接

多表查询_左连接多表操作_子查询

子查询左连接引用父ID

MS访问多查询左连接

交叉连接,内连接,子查询,外左连接,右连接,联合查询

选择中的左连接与子查询的奇怪问题