2015-04-02 20 views
1

當前查詢工作完美的問題是當前月份(4月)沒有數據,因此它不會將月份列爲0,我如何獲取它以列出月份有0個interivews?列出當月沒有來自數據庫的數據

QUERY

select distinct from_unixtime(interv_date,'%M %Y') AS month, count(*) as totals 
from " . TABLE_PREFIX . "interviews 
group by month 
order by interv_date desc 
limit 6 

注意,interv_date列是一個劃時代的時間戳(例如:1428003691)

PHP

<table class=\"highchart\" data-graph-container=\"#graphcontainer\" data-graph-type=\"column\" data-graph-legend-disabled=\"1\"> 
<caption>Interviews by Month</caption> 
<thead> 
<tr> 
<th>Month</th> 
<th>Totals</th> 
</tr> 
</thead> 
<tbody> 
<?php 
for ($i = 0; $i < $stat_logs["count"]; $i++) { 
    echo "<tr>\n"; 
    echo "<td>" . $stat_logs[$i]["month"] . "</td>\n"; 
    echo "<td>" . $stat_logs[$i]["totals"] . "</td>\n"; 
    echo "</tr>\n"; 
} 
?> 
echo "</tbody> 
echo "</table> 

OUTPUT

Month   Totals 
March 2015  7 
February 2015 5 
January 2015 12 
December 2014 18 
November 2014 19 
October 2014 5 

我需要它輸出是這樣的:

Month   Totals 
April 2015  0 
March 2015  7 
February 2015 5 
January 2015 12 
December 2014 18 
November 2014 19 

拿不出,並不是每個月都會有面試,所以它不會只是當前月份(第一個月) 我如何能拿到個月,沒有采訪任何人的幫助出現在名單上會很棒。

+0

您可能想要一個具有Jan-Dec的'month'表,然後在查詢中加入JOIN。儘管如果當前的「月份」列也包含年份,那可能會很麻煩。 – AbraCadaver 2015-04-02 18:55:20

+0

所以你有興趣過去6個月的數據包括當前月份? – 2015-04-02 19:04:20

+0

是包括當前月份,請注意interv_date列是紀元時間戳 – Manvaril 2015-04-02 19:39:23

回答

0

我一直在WAAAAAYYYY上工作太久。但這是一個開始... http://sqlfiddle.com/#!9/23389/2

它工作得很好,但它有點笨重,有兩個臨時表。儘管沒有硬編碼日期!這些表應該實際上是臨時表,儘管sqlfiddle不適用於臨時表,所以我使它們成爲真正的表。

-- Get a table with the months of interest in it 
SET @RightNow = curdate(); 
create table LastSixMonths (dateVal datetime); 
Insert into LastSixMonths values(@RightNow); 
Insert into LastSixMonths values(@RightNow - INTERVAL 1 MONTH); 
Insert into LastSixMonths values(@RightNow - INTERVAL 2 MONTH); 
Insert into LastSixMonths values(@RightNow - INTERVAL 3 MONTH); 
Insert into LastSixMonths values(@RightNow - INTERVAL 4 MONTH); 
Insert into LastSixMonths values(@RightNow - INTERVAL 5 MONTH); 

-- Summarize the recent interviews 
create table Totals (monthAndYear varchar (20), interviews int); 
Insert into Totals 
select distinct from_unixtime(intv.interv_date,'%M %Y') as monthAndYear, 
       count(*) 
from interviews intv 
group by from_unixtime(intv.interv_date,'%M %Y') 
order by interv_date desc 
limit 6 

-- Do a left join on recent months and summarized interviews 
select date_format(six.dateval, '%M %Y'), 
    IF (interviews IS NULL, 0, Interviews) as totalInterviews 
from LastSixMonths six 
left join Totals tot 
    on date_format(six.dateval, '%M %Y') = tot.monthAndYear 
order by six.dateval desc 
limit 6;