如何根据日期范围和表名称(每季度)从多表中选择数据

时间:2018-07-20 03:50:26

标签: php

我有按季度划分在不同表格中的数据。例如,2017年第一季度,表名称为kreports_first2017(数据来自jan,feb和mar)。 所以我有kreports_second2017,依此类推,直到2017年的kreports_fourth2017。以此类推,下一年。

我的问题是如何从用户单击的日期范围中选择数据。我只设法从“起始日期”和“截止日期”中选择表格。例如,用户选择从2017-04-01到2018-03-01之间选择数据。我设法仅合并了kreports_secondly2017和kreports_first2018中的数据。他们之间的桌子怎么样。 kreports_third2017和kreports_fourth2017?下面是我的代码:

$quar = array
  (
  array("first","01","02","03"),
  array("second","04","05","06"),
  array("third","07","08","09"),
  array("fourth","10","11","12")
  );

$month = substr($date1,5,2);
$year = substr($date1,0,4);
$month2 = substr($date2,5,2);
$year2 = substr($date2,0,4);

for ($row = 0; $row < 4; $row++) {
if(in_array($month,$quar[$row]))
{
  $table1 = "kreports_" . $quar[$row][0] . $year . "";  
}
if(in_array($month2,$quar[$row]))
{
  $table2 = "kreports_" . $quar[$row][0] . $year2 . "";
}
}

$quarter = "(select * from $table1 UNION select * from $table2) AS quarter";

$sql = "SELECT DATE(r_time) AS date,SUM(login_total) AS total, SUM(login_unique) AS uniq FROM $quarter WHERE DATE(r_time) BETWEEN '$date1' AND '$date2' GROUP BY DATE(r_time) ORDER BY date ASC";
$data = $db->fetch_array($sql);

1 个答案:

答案 0 :(得分:2)

您无需循环查找季度。只需将月份除以3即可得出季度。但是,首先,将其转换为int并减去1。

$quarter1 = floor(((int)$month - 1) / 3);
$quarter2 = floor(((int)$month2 - 1) / 3);

之后,您可以将这些结果与年份一起使用以获取表格。

$quarter = "(";
while ($quarter1 <= $quarter2 || $year < $year2) {
    $quarter .= "select * from kreports_" . $quar[$quarter1][0] . $year . " UNION ";
    $quarter1 = ($quarter1 + 1) % 4;
    $year += ($quarter1 == 0) ? 1 : 0; // move to next year once the quarter is set to first.
}
$quarter = substr($quarter, 0, -7); // remove the last " UNION "
$quarter .= ") AS quarter";