前几天我问了一个类似的问题,但似乎没有人能够回答它,并在互联网上搜索了几天但仍然没有结果,也许我没有以正确的方式提出这个问题:One-to-many Query in MySQL
所以我在尝试的时候再说一遍,也许会有点不同。这基本上是我想要做的简化版本:
CREATE TABLE Customer(
customer_id INT NOT NULL,
first_name varchar(20),
last_name varchar(20)
);
CREATE TABLE Payment(
customer_id INT NOT NULL,
amount_paid INT,
year YEAR,
FOREIGN KEY (customer_id) REFERENCES Customer(customer_id)
);
我想要的是组织左边的first_name,只出现一次,然后每年在单独的列中列出付款金额,因为我将把它附加到WPF,我想要一个电子表格样式表示数据。所以,理想情况下它看起来像这样:
name 2009 2008 2007
John 500 600 NULL
Anne NULL 500 600
Bob NULL NULL 600
我的方法是计算不同年份的付款次数,并将其用作循环计数器。而不是循环并收集每年的数据。用年份数代表amount_paid的每一列。我不仅不确定如何做到这一点,因为我最初的方法是使用UNION,但是我意识到只是将所有内容放在同一列而不是单独的列中。那么我应该使用什么?我只是要求一些指导。谢谢!
答案 0 :(得分:1)
使用:
SELECT c.first_name,
MAX(CASE WHEN p.year = 2009 THEN c.amount_paid ELSE NULL END) AS 2009,
MAX(CASE WHEN p.year = 2008 THEN c.amount_paid ELSE NULL END) AS 2008,
MAX(CASE WHEN p.year = 2007 THEN c.amount_paid ELSE NULL END) AS 2007
FROM CUSTOMER c
JOIN PAYMENT p ON p.customer_id = c.customer_id
GROUP BY c.first_name
答案 1 :(得分:0)
pivot
功能,因此唯一可行的方法是使用任何编程语言格式化结果集。
答案 2 :(得分:0)
我没有测试过,但我认为这样的事情有效:
select * from ((select name, sum(amount_paid) as 2009 from customer, payment
where customer.customer_id = payment.customer_id
and payment.year = 2009) a,
(select name, sum(amount_paid) as 2008 from customer, payment
where customer.customer_id = payment.customer_id
and payment.year = 2008) b
(select name, sum(amount_paid) as 2007 from customer, payment
where customer.customer_id = payment.customer_id
and payment.year = 2007) c);