简体   繁体   English

如何在 sql 中检索当年有记录的月份名称列表?

[英]How do I retrieve a list of month names where there are records within a current year in sql?

How do you retrieve a list of Months where there are records for a specific client by a specific year?您如何检索特定年份的特定客户记录的月份列表?

My table table name is called Date that has entries as DATE: 2019-11-21.我的表表名称为日期,其条目为 DATE:2019-11-21。

I've tried grouping by Month by I think I need to use something with AS to get the month name?我已经尝试按月份分组,我认为我需要使用 AS 来获取月份名称?

$sql = "SELECT * FROM Requests WHERE Client_id = ? GROUP BY MONTH";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();   
$data = $stmt->get_result();
$stmt->close();

if(mysqli_num_rows($data) === 0){
    echo "<br>no results";
}else{
    echo "<br>Results<br>";
}

while($row=mysqli_fetch_array($data)){
?>
     /* Desired Output:
         Each Month Name
     */
<?php
}

month is a function in mysql. month是 mysql 中的 function。 So unless you have a column named month (not a good idea), then you need to use it properly.因此,除非您有一个名为month的列(不是一个好主意),否则您需要正确使用它。 If your date column is named date , then you would pass that to the month function.如果您的日期列名为date ,那么您会将其传递给月份 function。

$sql = "SELECT MONTH(`date`), * 
        FROM Requests 
        WHERE Client_id = ? 
        GROUP BY MONTH(`date`)";

If you want to restrict it to a specific year, add that to the where request:如果要将其限制为特定年份,请将其添加到 where 请求中:

$sql = "SELECT MONTH(`date`), * 
        FROM Requests 
        WHERE Client_id = ? 
        AND YEAR(`date`) = '2019' 
        GROUP BY MONTH(`date`)";

(as placeholder) (作为占位符)

$sql = "SELECT MONTH(`date`), * 
        FROM Requests 
        WHERE Client_id = ? 
        AND YEAR(`date`) = ? 
        GROUP BY MONTH(`date`)";
$stmt = $db->prepare($sql);
$stmt->bind_param("ii", $id, $year);

Note that this will actually group the results together (one row per month), not order them, so you may not be getting what you want.请注意,这实际上会将结果组合在一起(每月一行),而不是对它们进行排序,因此您可能无法得到想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM