2017-03-04 87 views
0

目前,我有我的數據庫中的兩個表:數據庫設計爲每年支付

  • 「客戶」同列:CUSTOMER_ID,CUSTOMER_NAME
  • 「金」與列:payment_id,CUSTOMER_ID,一年,支付 (布爾),付款人

列「年」表示「付款人」支付的年份。

這給了我只有一個支付列:

SELECT customer_id, paid AS paid_for_2017 FROM customers LEFT JOIN payments ON customers.customer_id=payments.customer_id AND year=2017; 

現在我需要一個SELECT查詢,給了我下面的:

customer_name, paid_for_2017, paid_for_2018,... 

我該怎麼辦呢?我應該改變我的數據庫設計嗎?歡迎提出建議。

回答

2

如果你知道這些年來,你可以使用有條件聚集:

SELECT customer_id, 
     SUM(CASE WHEN year = 2017 THEN paid END) AS paid_for_2017, 
     SUM(CASE WHEN year = 2018 THEN paid END) AS paid_for_2018 
FROM customers c LEFT JOIN 
    payments p 
    ON c.customer_id = p.customer_id 
GROUP BY customer_id;