PHP按每周天数对数据mysql进行排序

时间:2019-01-22 22:11:22

标签: php mysql mysqli

我一直在寻找解决此问题的方法。所以在这里我举一个例子:

 date       item
-------------------
1-Jan-19    aaa
2-Jan-19    bbb
3-Jan-19    ccc
4-Jan-19    ddd
5-Jan-19    eee
6-Jan-19    fff
7-Jan-19    ggg
8-Jan-19    hhh
9-Jan-19    iii
10-Jan-19   jjj
11-Jan-19   kkk

到目前为止,我尝试使用此代码,但这仅显示每行7个数据分隔的数据。我使用的这段代码,

 <?php

$i     = 0;
$limit = 7;

$query = mysqli_query("SELECT * FROM mytable");
foreach ($query as $query) {
    if ($i >= $limit) {
        echo "<tr></tr>";
        $i = 0;
    }
    $i++;
?>   
<td><?php echo $query['item'];?></td> <?php } ?>

显示

 #monday #tuesday #wednesday #thursday #friday #saturday #sunday
   aaa      bbb       ccc       ddd      eee      fff       ggg     
   hhh      iii       jjj       kkk

我想显示这样的数据,

#monday #tuesday #wednesday #thursday #friday #saturday #sunday
  ---     aaa      bbb         ccc     ddd      eee       fff
  ggg     hhh      iii         jjj     kkk    

如何解决此问题?无需显示日期名称,例如在上面

1 个答案:

答案 0 :(得分:1)

如评论中所述,这可以通过纯SQL来完成。

您可以使用条件聚合来调整一周中各天的数据,并按一年中的几周进行分组。我使用子查询来避免在外部查询中重复进行转换(并键入...)。

// Write Name in NameSaved Section of AppSettings
public void WriteNameToAppSettings(string nameToSave)
{
    // Open Config File
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); // ConfigurationUserLevel.None (local) is working just fine...

    // Add or Update NameSaved Section of AppSettings
    if ((configuration.AppSettings.Settings["NameSaved"]?.Value) == null)
        configuration.AppSettings.Settings.Add("NameSaved", nameToSave);
    else
        configuration.AppSettings.Settings["NameSaved"].Value = nameToSave;

    //  Save and Refresh Config File            
    configuration.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name);
}

// Set LastEnteredName Property from NameSaved Section of AppSettings
public void ReadNameFromAppSettings()
{
    // Read Config File and then Get Name LastEntered Section of AppSettings
    LastEnteredName = ConfigurationManager.AppSettings["NameSaved"]?.ToString() ?? ""; // If null default to ""
}

提示:

  • 日期格式说明符SELECT t.week_year, MAX(CASE WHEN t.week_day = 1 THEN t.item END) monday, MAX(CASE WHEN t.week_day = 2 THEN t.item END) tuesday, MAX(CASE WHEN t.week_day = 3 THEN t.item END) wednesday, MAX(CASE WHEN t.week_day = 4 THEN t.item END) thursday, MAX(CASE WHEN t.week_day = 5 THEN t.item END) friday, MAX(CASE WHEN t.week_day = 6 THEN t.item END) saturday, MAX(CASE WHEN t.week_day = 0 THEN t.item END) sunday FROM ( SELECT date, item, DATE_FORMAT(date, '%w') week_day, DATE_FORMAT(date, '%Y-%v') week_year FROM mytable ) t GROUP BY t.week_year ORDER BY t.week_year 是星期几,其中0是星期日,而6是星期六
  • '%w'是一年中的星期几,其中 Monday 是一周中的第一天

此答案假定%v列的日期数据类型为dateDATEDATETIME。如果没有,则需要使用TIMESTAMP在子查询中添加一个转换。