【问题标题】:list the month with no data from database列出没有数据库数据的月份
【发布时间】:2015-04-02 18:53:38
【问题描述】:

当前查询完美,问题是当前月份(4 月)没有数据,因此它没有将月份列为 0,我如何让它将月份列为有 0 个干预?

查询

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>

输出

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

不要以为不是每个月都会有面试,所以不会只是当月(第一个月) 任何关于我如何让没有面试的月份出现在名单上的帮助都会很棒。

【问题讨论】:

  • 您可能想要一个 month 表,其中包含 Jan-Dec,然后在查询中加入。虽然如果当前的 month 列也包含年份,那可能会很混乱。
  • 所以您对过去 6 个月的数据感兴趣,包括当前月份?
  • 是包括当前月份,注意interv_date列是一个纪元时间戳

标签: php html mysql sql


【解决方案1】:

我在这个 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2015-06-18
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多