3

背景

我正在使用CASE2010 年、2011 年和 2012 年的表达式对这些数据进行透视,并按公司分组。正在旋转/返回的“度量”是max(state)针对每个案例/每年的,并且效果很好。

问题

我正在尝试max(invoice_date)从每个 的所有记录中获取最新记录company_name,但查询仅返回满足表达式的date位置CASE而不是max(invoice_date).

以下是表格数据的示例:

company_name  |  invoice_date | year      |  state
--------------------------------------------------------
CompanyA      |  20130101     | 2012      |   1
CompanyA      |  20130101     | 2012      |   3
CompanyB      |  20130102     | 2012      |   2
CompanyA      |  20120103     | 2011      |   3
CompanyB      |  20120104     | 2011      |   1
CompanyB      |  20120104     | 2011      |   3
CompanyA      |  20110101     | 2010      |   4
CompanyB      |  20110105     | 2010      |   2

这是所需视图的示例:

company_name  |  invoice_date |  2010   |   2011   |  2012
--------------------------------------------------------------
CompanyA      |  20130101     |   4     |    3     |   3 
CompanyB      |  20130102     |   2     |    3     |   2 

这是我得到的结果示例:

company_name  |  invoice_date |  2010   |   2011   |  2012
--------------------------------------------------------------
CompanyA      |  20110101     |   4     |    3     |   3 
CompanyB      |  20110105     |   2     |    3     |   2 

请注意,dateA 公司和 B 公司的日期均为 2011 年,这不是这两家公司表中的最新日期。我正在尝试获取max(invoice_date).

解决了:

select
company_name AS company_name,
max(invoice_date) AS invoice_date,
max((case when (year = 2010) then state else 0 end)) AS `2010`,
max((case when (year = 2011) then state else 0 end)) AS `2011`,
max((case when (year = 2012) then state else 0 end)) AS `2012`,
from tbl
group by company_name 
order by invoice_date desc
4

2 回答 2

0

我会像这样重写您的查询:

select company_name AS company_name,
  max(invoice_date) AS invoice_date,
  sum(year = 2010) AS `2010`,
  sum(year = 2011) AS `2011`,
  sum(year = 2012) AS `2012`
from tbl
group by company_name 
order by invoice_date desc

特别是有趣的案例陈述可以做得更短。

于 2013-04-08T12:50:17.960 回答
0

如果我是你,我会使用这样的准备好的语句,以便它动态地获取所有年份。这样,当 2013 年数据显示时,您不必更改查询:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT(
    'MAX((CASE WHEN (year = \'',
    year,
    '\') THEN state ELSE 0 END)) AS \''
    year,
    '\''
  )
) INTO @sql
FROM tbl;

SET @sql = CONCAT('SELECT
  company_name AS company_name,
  MAX(invoice_date) AS invoice_date,', @sql, '
  FROM tbl
  GROUP BY company_name 
  ORDER BY invoice_date desc');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-04-08T12:37:06.623 回答