如何限定CASE表达式中的条件(类似于WHERE子句)

时间:2013-04-06 08:55:16

标签: mysql sql case aggregate-functions conditional-statements

这是我的表

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(金额)并按公司分组,但我需要每年最多。

我认为我需要CASE表达式中的条件要使用WHERE子句或嵌套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;

任何帮助都会非常感激! THX

2 个答案:

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

答案 1 :(得分: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',
       ...