不完全确定如何提出问题,所以我给了它最好的节目,并希望这些解释能够帮助我们明白这一点。有任何问题,请询问。
我的数据库有以下设置:
create table spooner_pec
(
id int,
year varchar(20),
policy_number int,
primary_name varchar(200),
experience_rate decimal(10,2),
mco_name varchar(200)
);
插入这些值:
insert into spooner_pec values
(1,'2009',183586,'ZBIN LANDSCAPING INC', 1.22, 'GENEX CARE FOR OHIO'),
(1,'2011',183586,'ZBIN LANDSCAPING INC', 0.93, 'COMPMANAGEMENT HEALTH SYSTEMS, INC.'),
(1,'2012',183586,'ZBIN LANDSCAPING INC', 0.92, 'HEALTH MANAGEMENT SOLUTIONS, INC.'),
(1,'2013',183586,'ZBIN LANDSCAPING INC', 0.50, 'CAREWORKS'),
(1,'2014',183586,'ZBIN LANDSCAPING INC', 0.47, 'UNIVERSITY HOSPITALS COMPCARE'),
(1,'2010',183586,'ZBIN LANDSCAPING INC', 1.27, 'SHEAKLEY UNICOMP')
我目前工作的查询是:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when year = ',
year,
' then experience_rate end) AS `',
year, '-Pen`'
) ORDER BY year
) INTO @sql
FROM
spooner_pec;
SET @sql = CONCAT('SELECT policy_number, primary_name, ', @sql, '
FROM spooner_pec
GROUP BY policy_number');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
所以我每个公司都有一行,然后是每年一年的笔列。我现在需要做的只是获取最近一年的罚款大于1的行。因此,如果输入的所有数据的最后一年是2014年,那么我需要2014-Pen,在这种情况下,> 1。