1

这是我的桌子

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;

任何帮助将不胜感激!谢谢

4

2 回答 2

1

试试这个:

SELECT company,
  MAX(CASE WHEN year = 2008 THEN amount ELSE 0 END) AS '2008',
  MAX(CASE WHEN year = 2009 THEN amount ELSE 0 END) AS '2009'
FROM tbl
GROUP BY company;

看看它的实际效果:

这会给你:

|  COMPANY | 2008 | 2009 |
--------------------------
| CompanyA |    5 |    0 |
| CompanyB |    4 |    1 |
| CompanyC |    0 |    4 |
于 2013-04-06T08:58:34.767 回答
0

这是在 MySQL 中旋转表的方式:

select max(case fiscal_year when '2008' then amount else 0 end) as '2008',
       max(case fiscal_year when '2009' then amount else 0 end) as '2009',
       ...
于 2013-04-06T08:58:43.800 回答