1

我在 sql Fiddler 中制作了一个演示实体。我的桌子有以下专栏

displayId | displaytime | campaignId

现在我想要的是为特定的campaignId选择最后7天的条目(我的意思是campaignId =“”)在同一日期应该有多个条目具有相同的campaign id..所以我想显示总campaignId的总和他们的日期

所以如果日期 2013-3-8 和其他日期有 7 条记录,那么它会显示我的记录

2013-03-02 | 1
2013-03-03 | 1
2013-03-04 | 0
2013-03-05 | 0
2013-03-06 | 0
2013-03-07 | 2
2013-03-08 | 7

在以下查询中,它仅显示其计数的日期,其计数超过 0...例如,我尝试过的内容如下..但它只给了我一个在数据库中有条目的记录...

 2013-03-08 | 7


SELECT date(a.displayTime) AS `DisplayTime`,
       ifnull(l.TCount,0) AS TCount
FROM a_ad_display AS a
INNER JOIN
  (SELECT count(campaignId) AS TCount,
          displayTime
   FROM a_ad_display
   WHERE CONVERT_TZ(displaytime,'+00:00','-11:00') >= DATE_SUB(CONVERT_TZ(CURDATE(),'+00:00','-11:00') ,INTERVAL 1 DAY)
     AND CONVERT_TZ(displaytime,'+00:00','-11:00') <= CONVERT_TZ(CURDATE(),'+00:00','-11:00')
     AND campaignId = 20747
   GROUP BY DATE(displayTime)) AS l ON date(a.displayTime) = date(l.displayTime)
GROUP BY DATE(a.displayTime)
ORDER BY a.displaytime DESC LIMIT 7

我已经在我的查询中实现了时区,所以如果你可以帮助我进行简单的查询,那么它的 ok..dont 包含Convert_Tz行。

这是我的虚拟实体的http://sqlfiddle.com/#!2/96600c/1链接

4

2 回答 2

4

如果您使用日期表,您的查询可以很简单:

select dates.fulldate, count(a_ad_display.id)
from dates
left outer join a_ad_display ON dates.fulldate = a_ad_display.displaytime
    [AND <other conditions here>]
where dates.fulldate BETWEEN date_add(curdate(), interval -6 day) AND curdate()
group by dates.fulldate

http://sqlfiddle.com/#!2/51e17/3


在不使用日期表的情况下,这是一种方法。这很丑陋,而且性能可能很糟糕:

select displaytime, sum(c)
from
(
  select displaytime, count(a_ad_display.id) AS c
  from a_ad_display
  where displaytime BETWEEN date_add(curdate(), interval -6 day) AND curdate()
  group by displaytime
  union all
  select curdate(), 0
  union all
  select date_add(curdate(), interval -1 day), 0
  union all
  select date_add(curdate(), interval -2 day), 0
  union all
  select date_add(curdate(), interval -3 day), 0
  union all
  select date_add(curdate(), interval -4 day), 0
  union all
  select date_add(curdate(), interval -5 day), 0
  union all
  select date_add(curdate(), interval -6 day), 0
) x
group by displaytime
order by displaytime

http://sqlfiddle.com/#!2/96600c/16

于 2013-03-08T08:16:27.407 回答
0

简单!您可以通过 PHP 完成。首先创建日期数组,如

date = date('Y-m-d'); $date1 = date('Y-m-d', strtotime('-1 days')); $date2 = date('Y-m-d', strtotime('-2 days'));$date3 = date('Y-m-d', strtotime('-3 days'));$date4 = date('Y-m-d', strtotime('-4 days'));$date5 = date('Y-m-d', strtotime('-5 days'));$date6 = date('Y-m-d', strtotime('-6 days')); 
                $dt_arr = array($date6,$date5,$date4,$date3,$date2,$date1,$date);

从今天开始的最后 7 天,然后使用 foreach 并使用 foreach 中的 where 日期字段运行查询,例如

 foreach ($dt_arr as $value) 
    {
     $qry = mysqli_fetch_array(mysqli_query($link,"select * from table where dt_field = $value"));
       if($qry['value'] == '')
         {
           $valfield = 0;
          $dtfiled = $value;

     }
于 2020-03-03T12:18:50.973 回答