SQL 对多个表进行 LEFT JOIN

SQL LEFT JOIN on Multiple Tables

给定三个表:

  1. Account
    1. UniqueID
    2. Account Group
  2. VR
    1. UniqueID
    2. AccountID
  3. CR
    1. UniqueID
    2. AccountID

其中 AccountIDVR 中找到,CR 引用 Account 中的 UniqueID

我想获得一个结果,显示第一列中的 AccountAccount 以及每个 Account 组的数据量 VR在第二列中,最后是第三列中每个 Account 组的数据量 CR

实现这种连接的正确方法是什么?

我的尝试:

SELECT account_group AS 'Account Group',
  COUNT(Account.AccountId) AS 'Anzahl Accounts',
  COUNT(VR.ActivityId) AS 'VR',
  COUNT(Contact.ContactId) AS 'Contact'
  FROM [MSCRM].[dbo].[AccountBase]
  LEFT JOIN MSCRM.dbo.visit_report_activityBase
    ON Account.AccountId = VR.account_id
  LEFT JOIN MSCRM.dbo.ContactBase
    ON Account.AccountId = Contact.ParentCustomerId
  GROUP BY account_group
  ORDER BY account_group ASC;

但是没有COUNT(*)显示我想要的实际数量。

甚至 Account.AccountIdCOUNT 也显示无效数字。

我相信您正在寻找的是 count distinct :

SELECT account_group as 'Account Group',
       count(distinct Account.AccountId) as 'Anzahl Accounts',
       count(distinct VR.ActivityId) as 'VR' count(distinct Contact.ContactId) as 'Contact'
  FROM [ MSCRM ] . [ dbo ] . [ AccountBase ] as Account
  left join MSCRM.dbo.visit_report_activityBase as VR
    on Account.AccountId = VR.account_id
  left join MSCRM.dbo.ContactBase as Contact
    on Account.AccountId = Contact.ParentCustomerId
 group by account_group
 order by account_group