这是我的桌子
Company | Year | Amount
------------------------
CompanyA | 2008 | 5
CompanyA | 2008 | 4
CompanyB | 2008 | 4
CompanyB | 2009 | 1
CompanyC | 2009 | 4
CompanyC | 2010 | 2
伪代码
SELECT company,
CASE WHEN year = 2008 THEN select max(amount) for each company where the year is = 2008
CASE WHEN year = 2009 THEN select max(amount) for each company where the year is = 2009
GROUP BY company
我已经能够让 CASE 工作,但它选择了所有年份的 MAX(数量)并按公司分组,但我需要每年的最大值。
我想我需要用 WHERE 子句或嵌套的 CASE 来限定 CASE 表达式中的条件,但不能让它工作。
真实代码
select
record_id AS record_id,
invoice_date AS invoice_date,
company_id AS company_id,
company_name AS company_name,
fiscal_year AS fiscal_year,
(CASE fiscal_year WHEN '2008' THEN MAX(amount) ELSE 0 END) AS `2008`,
(CASE fiscal_year WHEN '2009' THEN MAX(amoutn) ELSE 0 END) AS `2009`,
(CASE fiscal_year WHEN '2010' THEN MAX(amount) ELSE 0 END) AS `2010`,
(CASE fiscal_year WHEN '2011' THEN MAX(amount) ELSE 0 END) AS `2011`,
(CASE fiscal_year WHEN '2012' THEN MAX(amount) ELSE 0 END) AS `2012`,
(CASE fiscal_year WHEN '2013' THEN MAX(amount) ELSE 0 END) AS `2013`
from tbl
group by company_name
order by invoice_date desc, record_id desc;
任何帮助将不胜感激!谢谢