使用where子句获取包含相关记录数的所有类别

时间:2017-12-28 10:11:40

标签: sql-server tsql

所以我有两张桌子:

Categories

-------------------
| Id | Name       |
-------------------
| 1  | Category1  |
-------------------
| 2  | Category2  |
-------------------
| 3  | Category3  |
-------------------

Products

--------------------------------------------
| Id | CategoryId | Name     | CreatedDate |
--------------------------------------------
| 1  |     1      | Product1 | 2017-05-05  |
--------------------------------------------
| 1  |     1      | Product2 | 2017-05-06  |
--------------------------------------------
| 2  |     2      | Product3 | 2017-12-21  |
--------------------------------------------

我需要一个查询,以便在创建这些产品的特定时间范围内选择所有类别以及每个类别的产品数量(CreatedDate)。

我现在拥有的是:

SELECT c.[Name], COUNT(p.[Id]) AS ProductCount
FROM Categories AS c
LEFT JOIN Products AS p ON p.[CategoryId] = c.[Id]
WHERE p.[CreatedDate] BETWEEN '2017-05-01' AND '2017-06-01'
GROUP BY c.[Name]

我的问题是,我在结果集中没有看到Category2Category3,因为他们没有通过WHERE条款。我想查看结果集中的所有类别。

1 个答案:

答案 0 :(得分:2)

where条件放在left join子句

SELECT c.[Name], COUNT(p.[Id]) AS ProductCount
FROM Categories AS c
LEFT JOIN Products AS p ON p.[CategoryId] = c.[Id]
                       AND p.[CreatedDate] BETWEEN '2017-05-01' AND '2017-06-01'
GROUP BY c.[Name]

这种方式仅适用于连接,而不适用于完整的结果集。