如何在sql中选择季度数据

时间:2015-03-18 08:21:17

标签: php sql codeigniter

如何按季度获取数据?我有这个html让用户选择他/她想要的季度。

<select name="quarterly">
  <option value="2015-01">Quarter1</option>
  <option value="2015-04">Quarter2</option>
  <option value="2015-07">Quarter3</option>
  <option value="2015-10">Quarter4</option>
</select>

我应该如何使用QUARTER()函数并在一年中的季度之前返回我的数据?

这是我使用CI的查询。

$quarter_val = $this->input->get('quarterly');
$this->db->select('ainoheads, aittlperweight, aittlperclass')
         ->from('main_data')
         ->where('QUARTER(ai_ordDate)', $quarter_val);

5 个答案:

答案 0 :(得分:3)

QUARTER返回1到4之间的整数。您可能想要这样:

<select name="quarterly">
  <option value="1">Quarter1</option>
  <option value="2">Quarter2</option>
  <option value="3">Quarter3</option>
  <option value="4">Quarter4</option>
</select>

答案 1 :(得分:1)

如果我在http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_quarter上正确阅读,那么你必须这样做

SELECT ainoheads, aittlperweight, aittlperclass FROM main_data WHERE QUARTER(ai_ordDate) = "$quarter_val";

答案 2 :(得分:0)

您可以转换所选的季度选项,然后从中提取数字季度:

$quarter_val = $this->input->get('quarterly');
$newformat = date('Y-m',$quarter_val);
$currMonth = date("m", $newformat);
$currQuarter = ceil($currMonth/3);

$this->db->select('ainoheads, aittlperweight, aittlperclass')
         ->from('main_data')
         ->where('QUARTER(ai_ordDate)', $currQuarter);

你的SQL查询看起来很好,我没有改变它。

答案 3 :(得分:0)

获取特定年份的季度我这样做

首先我改变这个值

<select name="quarterly">
   <option value="1,2015">Quarter1</option>
   <option value="2,2015">Quarter2</option>
   <option value="3,2015">Quarter3</option>
   <option value="4,2015">Quarter4</option>
</select>

(我循环选择以获得其他年份)

然后在后端我做这个代码。

$quarter_val = $this->input->get('quarterly');
$explode_quar = explode(",",$quarter_val); //returns Array ( [0] => 1 [1] => 2015 )

$this->db->select('ainoheads, aittlperweight, aittlperclass')
         ->from('main_data')
         ->where('YEAR(ai_ordDate)', $explode_quar[1])
         ->where('QUARTER(ai_ordDate)', $explode_quar[0])
         ->get();

感谢@ hans,@ pi和@sg ..

的帮助

答案 4 :(得分:0)

quarter_val 1将带来一月,二月和三月 $quarter_val = 1; $query=mysqli_query($link,"SELECT DATE_FORMAT(Starting_Date,'%M %Y') as month FROM student WHERE QUARTER(Starting_Date)='$quarter_val' AND YEAR(Starting_Date)='$year'") or die(mysqli_error($link));