我目前在我的数据库中有两个表:
“年”一栏表示“付款人”已付款的年份。
这只给我一个付费专栏:
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,...
我该怎么做?我应该更改我的数据库设计吗?欢迎提出建议。
答案 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;