【发布时间】:2016-06-06 07:20:28
【问题描述】:
我有三个需要连接的表。我能够加入其中两个并获得所需的结果,而这个结果表需要与另一个表连接。
表 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 |
+--------------+--------------+-----------------+
【问题讨论】:
-
在
Table1中用户abc的两条记录中,为什么您对Country=US的一条感兴趣,而不是Country=CAN的一条?是什么“业务逻辑”使它成为重要的记录? -
好问题斯图尔特。一个用户可能支持多个国家。我很想知道用户是否存在于我的 Table1 中,而不是他/她支持哪个国家/地区。
-
啊好。我的回答是基于这个假设:-)
标签: sql-server tsql join