MYSQL - 选择MIN和MAX年份并填补空白

时间:2016-04-26 04:13:20

标签: php mysql

我想在我的数据库中使用Highcharts(bar),但我正在努力使用我的选择来使用JSON。

我有三个级别:黄金,白银和白金,我需要获得最低年份和最高年份,并且如果某一年度不存在该水平,则需要弥补差距

我有这个选择:

select B.year, A.level, COUNT(B.id_level) as n_level from level AS A
inner join company_level AS B ON A.id_level = B.id_level 
GROUP BY B.id_level, B.year
ORDER BY B.year

我的结果:

year    level       n_level
2010    Siver       1
2010    Platinum    2
2010    Gold        2
2011    Gold        1
2013    Gold        1
2014    Platinum    1
2015    Silver      1

在我的结果中,我没有2011年的白银和白金,我想将白银和白金放在列表中,但是number_level(n_level)为0。

我的PHP:

$rows = mysqli_query($this->conn, $query);
$bln = array();
$bln['name'] = 'Year';   
$row['name'] = 'Level'; 

$year =""; 
while ($r = mysqli_fetch_array($rows)) {
    if($year !== $r['year']){
        $bln['data'][] = $r['year']; 
    }
    $row['data'][] = $r['n_level']; 
    $year = $r['year']; 

}
$rslt = array();              

array_push($rslt, $bln);
array_push($rslt, $row);

print json_encode($rslt, JSON_NUMERIC_CHECK);

我的PHP结果:

[{"name":"Year","data":[2010,2011,2013,2014,2015]},{"name":"Level","data":[2,2,1,1,1,1,1]}]

但我的目标是:

[{"name":"Year","data":[2010,2011,2013,2014,2015]},{"name":"Gold","data":[2,2,1,1,1]}, {"name":"Silver","data":[1,0,0,0,1]}, {"name":"Platinum","data":[2,2,1,1,1]}]

感谢您的帮助。

@Tin Tran回答后的结果:

$rows = mysqli_query($this->conn, $query);
                $bln = array();
                $bln['name'] = 'Year';   
                $row_gold['name'] = 'Gold'; 
                $row_platinum['name'] = 'Platinum';              
                $row_silver['name'] = 'Silver';                    

                while ($r = mysqli_fetch_array($rows)) {
                $bln['data'][] = $r['year'];
                $row_gold['data'][] = $r['gold'];
                $row_platinum['data'][] = $r['platinum'];              
                $row_silver['data'][] = $r['silver']; ''; 

                }
                $rslt = array();              

                array_push($rslt, $bln);
                array_push($rslt, $row_gold);
                array_push($rslt, $row_platinum);              
                array_push($rslt, $row_silver);             
                print json_encode($rslt, JSON_NUMERIC_CHECK);

此代码适用于Highcharts。再次感谢@Tin Tran。

1 个答案:

答案 0 :(得分:1)

我不熟悉php,但我认为根据你的JSON目标, 此查询可能会为您提供结果。

SELECT B.year,
       SUM(A.level = 'Gold') as Gold,
       SUM(A.level = 'Silver') as Silver,
       SUM(A.level = 'Platinum') as Platinum
FROM level AS A
INNER JOIN company_level AS B ON A.id_level = B.id_level
GROUP BY B.year
ORDER BY B.year;

结果:

year    Gold    Silver  Platinum
2010    2       1       2
2011    1       0       0
2013    1       0       0
2014    0       0       1
2015    0       1       0

sqlfiddle - > http://sqlfiddle.com/#!9/59893/3