2015-12-07 23 views
2

我有這兩個表如何正確連接這兩個表格?

客戶:

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 < =日期< = 20151211,所得到的表應該是這樣的:

name    | orders count 
--------------------+------------- 
company 1   | 0 
company 2   | 2 
yet another company | 1 

注:日期= 20151207裝置12月7日2015年

如何加入他們?

回答

1

SELECT c.name,COUNT(CASE WHEN((o.date BETWEEN 20151207 AND 20151211)OR(o.date ISNULL))THEN o.customer_id END)AS「Total Sales」FROM customers AS c LEFT JOIN orders o ON c.id == o.customer_id GROUP BY c.name

+1

typo - 等於運算符是= not == – amdixon

+0

=和==在sqlite中是一樣的我確信它運行良好當我在SqliteBrowser中檢查它時(見:http://sqlitebrowser.org) – Fallso

+0

@amdixon剛剛檢查過,它們是一樣的:https://www.sqlite.org/lang_expr.html – Fallso