SUM按用户每年,按用户分组,每年的动态列

时间:2016-03-21 16:51:53

标签: mysql

此查询已提供给我,我需要将其设置为动态,因此年份列不是硬编码的:

SELECT u.last_name as 'Name', 
COUNT(e.user_id) as 'Total',
SUM(CASE WHEN YEAR(e.datetime)=2012 THEN 1 END) as '2012',
SUM(CASE WHEN YEAR(e.datetime)=2013 THEN 1 END) as '2013',
SUM(CASE WHEN YEAR(e.datetime)=2014 THEN 1 END) as '2014',
SUM(CASE WHEN YEAR(e.datetime)=2015 THEN 1 END) as '2015',
SUM(CASE WHEN YEAR(e.datetime)=2016 THEN 1 END) as '2016'
FROM entries e, users u
WHERE e.user_id = u.user_id
GROUP BY e.user_id

有没有办法动态创建年份列,并使用mysql动态求和它们?我当然可以用一些php来做,但想知道它是否可能在纯mysql中。

当前查询输出如下内容:

Name    Total 2012 2013 2014 2015 2016
Smith   568   186  124  162  75   21
Jones   579   188  156  160  68   7

1 个答案:

答案 0 :(得分:1)

你可以像这样循环结果

$d = 2016;
$string = '';
for($i = 2012; $i <= $d; $i ++) {
    $string .= "SUM(CASE WHEN YEAR(e.datetime)=$i THEN 1 END) as '$i'";
}

然后将其添加到查询

SELECT u.last_name as 'Name', 
COUNT(e.user_id) as 'Total',
    '.$string.'
FROM entries e, users u
WHERE e.user_id = u.user_id
GROUP BY e.user_id