我想加入3個表格並獲得每個聯繫人案例的計數。到目前爲止,我已經寫了這個查詢,但結果顯示我有聯繫誰有案件。我想要一個新的列,它會顯示每個聯繫人的「案例數」,因此結果應該是3行3列(最後一列是個案數)如何通過在sql上連接3個表來插入行數?
表A(聯繫人)
+-----------------------+----+---------------------------------+
| Name | id | Organization |
+-----------------------+----+---------------------------------+
| Heidi Wilson-Reynolds | 2 | Alabama Arts Services |
+-----------------------+----+---------------------------------+
| Dr. Andrew Zope | 3 | Connecticut Empowerment Academy |
+-----------------------+----+---------------------------------+
| Rolando Cooper Sr. | 8 | Dutton Advocacy Trust |
+-----------------------+----+---------------------------------+
表B(情況聯繫人)
+----+---------+------------+
| id | case_id | contact_id |
+----+---------+------------+
| 1 | 1 | 2 |
+----+---------+------------+
| 2 | 2 | 3 |
+----+---------+------------+
| 3 | 3 | 8 |
+----+---------+------------+
| 4 | 4 | 2 |
+----+---------+------------+
| 5 | 5 | 3 |
+----+---------+------------+
| 6 | 6 | 8 |
+----+---------+------------+
表C(例)
+----+-----------+
| id | status_id |
+----+-----------+
| 1 | 1 |
+----+-----------+
| 2 | 1 |
+----+-----------+
| 3 | 1 |
+----+-----------+
| 4 | 1 |
+----+-----------+
| 5 | 1 |
+----+-----------+
| 6 | 1 |
+----+-----------+
曲兒Y:
SELECT
A.display_name AS 'Name',
A.organization_name AS 'Organization'
FROM
A
INNER JOIN
B ON A.id = B.contact_id
INNER JOIN
C ON B.case_id = C.id
WHERE
A.contact_type = 'Individual' and C.status_id = 1; # Case status 1 is "Ongoing"
結果:
+-----------------------+---------------------------------+
| Name | Organization |
+-----------------------+---------------------------------+
| Heidi Wilson-Reynolds | Alabama Arts Services |
+-----------------------+---------------------------------+
| Dr. Andrew Zope | Connecticut Empowerment Academy |
+-----------------------+---------------------------------+
| Rolando Cooper Sr. | Dutton Advocacy Trust |
+-----------------------+---------------------------------+
| Heidi Wilson-Reynolds | Alabama Arts Services |
+-----------------------+---------------------------------+
| Dr. Andrew Zope | Connecticut Empowerment Academy |
+-----------------------+---------------------------------+
| Rolando Cooper Sr. | Dutton Advocacy Trust |
+-----------------------+---------------------------------+
這是結果,我想它表明,我想我需要使用COUNT()函數:
+-----------------------+---------------------------------+-----------------+
| Name | Organization | number_of_cases |
+-----------------------+---------------------------------+-----------------+
| Heidi Wilson-Reynolds | Alabama Arts Services | 2 |
+-----------------------+---------------------------------+-----------------+
| Dr. Andrew Zope | Connecticut Empowerment Academy | 2 |
+-----------------------+---------------------------------+-----------------+
| Rolando Cooper Sr. | Dutton Advocacy Trust | 2 |
+-----------------------+---------------------------------+-----------------+
我刪除基於MySQL Workbench標記的SQL Server標記。 –