多个表上的SQL LEFT JOIN

时间:2016-03-16 14:42:06

标签: mysql sql count left-join

给出三个表:

  1. Account
    1. UniqueID
    2. Account Group
  2. VR
    1. UniqueID
    2. AccountID
  3. CR
    1. UniqueID
    2. AccountID
  4. AccountID中的VRCR中的UniqueID引用Account中的Account

    我想获得一个结果,该结果显示第一列中的Account Account组和VRAccount中的数据量第二列,最后是第3列中每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(*)

    但没有COUNT显示我想要的实际金额。

    即使Account.AccountId {{1}}显示的号码无效。

1 个答案:

答案 0 :(得分:1)

我相信你要找的东西是不同的:

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