我有三个表需要连接。我能够连接其中两个并获得所需的结果,并且此结果表需要与另一个表连接。
表1:
+----------+---------+------+
| Username | Country | Team |
+----------+---------+------+
| abc | US | New |
| abc | CAN | New |
| bcd | US | Old |
+----------+---------+------+
表2:
+----------+-------------+----------+------------+
| Username | CompanyCode | Document | Entry Date |
+----------+-------------+----------+------------+
| abc | 1 | 112 | 24/06/2014 |
| abc | 2 | 123 | 24/06/2014 |
| bcd | 3 | 456 | 24/06/2014 |
| efg | 4 | 984 | 24/06/2014 |
+----------+-------------+----------+------------+
我编写了以下代码..
SELECT Username, CompanyCode, Document, IIF(MONTH([Entry Date]) = 6 AND YEAR([Entry Date]) = 2014, 'TRUE', 'FALSE') AS [Posted],
COALESCE(tNew.Country, 'not there') AS DC, COALESCE(tNew.Team, 'not there') AS Team FROM Table2
OUTER APPLY
(
SELECT TOP 1 Country, Team FROM Table1
WHERE Table1.[Username] = Table2.[Username]
) tNew
...结果为 (Table99)...
+----------+--------------+----------+------------+--------+-----------+-----------+
| Username | Company Code | Document | Entry Date | Posted | Country | Team |
+----------+--------------+----------+------------+--------+-----------+-----------+
| abc | 1 | 112 | 24/06/2014 | TRUE | US | New |
| abc | 2 | 123 | 24/06/2014 | TRUE | US | New |
| bcd | 3 | 456 | 24/06/2014 | TRUE | US | Old |
| efg | 4 | 984 | 24/06/2014 | TRUE | not there | not there |
+----------+--------------+----------+------------+--------+-----------+-----------+
现在我有另一个表,Table3:
+--------------+--------------+
| Company Code | Company Name |
+--------------+--------------+
| 1 | MS |
| 2 | APL |
| 3 | GOO |
| 4 | IBM |
| 5 | AMZ |
+--------------+--------------+
我想将 Company Code
上的 Table99 与 Table3 连接起来,并计算 Document
WHERE Posted = TRUE AND Country <> 'not there'
的计数,结果...
+--------------+--------------+-----------------+
| Company Code | Company Name | Total Documents |
+--------------+--------------+-----------------+
| 1 | MS | 1 |
| 2 | APL | 1 |
| 3 | GOO | 1 |
| 4 | IBM | 0 |
| 5 | AMZ | 0 |
+--------------+--------------+-----------------+
最佳答案
对 Table3
和原始查询执行 LEFT JOIN
,然后使用条件 SUM
进行计数:
SELECT
t3.CompanyCode,
t3.CompanyName,
SUM(CASE WHEN t.Posted = 'TRUE' AND t.Country <> 'not there' THEN 1 ELSE 0 END)
FROM Table3 t3
LEFT JOIN (
SELECT
Username,
CompanyCode,
Document,
tnew.Country,
IIF(MONTH(EntryDate) = 6 AND YEAR(EntryDate) = 2014, 'TRUE', 'FALSE') AS [Posted],
COALESCE(tNew.Country, 'not there') AS DC,
COALESCE(tNew.Team, 'not there') AS Team
FROM Table2
OUTER APPLY(
SELECT TOP 1 Country, Team FROM Table1
WHERE Table1.[Username] = Table2.[Username]
) tNew
) t
ON t3.CompanyCode = t.CompanyCode
GROUP BY t3.CompanyCode, t3.CompanyName
ORDER BY t3.CompanyCode
关于sql-server - 在 SQL 中连接多个表并获取 Count 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35594749/