我有这两个表
客户:
id | name | address
---+---------------------+-------------------------
1 | company 1 | some address information
2 | company 2 | another address
3 | yet another company | no address here
订单:
id | customer_id | date
---+-------------+---------
1 | 2 | 20151209
2 | 2 | 20151211
3 | 3 | 20151210
4 | 1 | 20151223
现在,我希望左侧的每个客户以及右侧任意时间段内的订单数量得到一个结果表。 例如,假设此期间为20151207< = date< = 20151211,则结果表应如下所示:
name | orders count
--------------------+-------------
company 1 | 0
company 2 | 2
yet another company | 1
注:date = 20151207表示2015年12月7日。
如何加入他们?
答案 0 :(得分:1)
SELECT c.name,COUNT(CASE WHEN((2015年至2015年之间的合作)或(o.date ISNULL))o.customer_id END)AS"总销售额"来自客户AS c LEFT JOIN订单o ON c.id == o.customer_id GROUP BY c.name