年度付款的数据库设计

时间:2017-03-04 17:23:25

标签: mysql sql database

我目前在我的数据库中有两个表:

  • “customers”的列:customer_id,customer_name
  • “付款”的列:payment_id,customer_id,year,paid (bool),付款人

“年”一栏表示“付款人”已付款的年份。

这只给我一个付费专栏:

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,...

我该怎么做?我应该更改我的数据库设计吗?欢迎提出建议。

1 个答案:

答案 0 :(得分: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;