【问题标题】:Get the number of rows inserted in the database per hour获取每小时插入数据库的行数
【发布时间】:2021-03-31 03:24:03
【问题描述】:

我知道已经有类似的问题,但我找不到一个清晰简单的答案。

我有这个问题:

"SELECT dbo.tbTransaction.dateHeure, dbo.tbTransaction.Etat, dbo.tbPoste.nomPoste
        FROM dbo.tbTransaction 
        INNER JOIN dbo.tbPoste ON dbo.tbTransaction.ID_poste = dbo.tbPoste.ID_POSTE
        WHERE dbo.tbPoste.id_site LIKE 47 
        AND dbo.tbPoste.nomPoste LIKE '0909_CLIENT'
        AND dateHeure >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
        ORDER BY dateHeure DESC";

它使我能够获取特定帖子 (0909_CLIENT) 上 day(>= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)) 的所有数据库插入,按最近插入时间排序 (ORDER BY dateHeure DESC)。

我希望能够检索每小时的插入次数,目标是能够每小时生成实时图形。

我设法通过以下方式获得了白天的总插入次数:

$params = array();
    $options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
    $result = sqlsrv_query( $conn, $sql , $params, $options );
    $row_count = sqlsrv_num_rows( $result ). PHP_EOL;
    echo '<br>';
     if ($row_count === false)
     echo "Error in retrieveing row count;
    else {
      echo $row_count;
     } 

我可以看到在特定时间输入数据库的行:

$five = "05:";
$six = "06:";
$seven = "07:";


if ($result === false) {
    die(print_r(sqlsrv_errors(), true));
} else {
    while ($row = sqlsrv_fetch_array($result)) {
        $heureformate = $row["dateHeure"]->format('H:i');
        
        if (strpos($heureformate, $five) !== false) {
            echo $heureformate;
            echo '<br>';
            //count(array($heureformate));
        } elseif (strpos($heureformate, $six) !== false) {
            echo $heureformate;
            echo '<br>';
        } elseif (strpos($heureformate, $seven) !== false) {
            echo $heureformate;
            echo '<br>';
        } 
    } 
}

但正如我告诉你的,我无法获得每小时输入的行数,正是这个数字让我感兴趣来创建图形。

如果您对如何在SQLPHP 中获取此号码有任何想法,请帮助我。

【问题讨论】:

  • 尝试将group by hour(your_datetime_column) 添加到您的查询中。
  • 我试过但我有“小时不是一个公认的内置函数名”
  • 抱歉,我以为这是mysql。
  • 别担心,谢谢你的建议;)

标签: php sql sql-server count date-arithmetic


【解决方案1】:

你想要聚合吗?

select  datepart(hour, t.dateheure), count(*) as cnt
from dbo.tbtransaction t
inner join dbo.tbposte p on t.id_poste = p.id_poste
where p.id_site = 47 and p.nomposte = '0909_client' and t.dateheure >= cast(gedate() as date)
group by datepart(hour, dateheure)

这会过滤数据集中dateheure 属于当天的行,并计算每小时有多少条记录。

请注意,我简化了日期过滤逻辑,并将like 条件转换为等式(因为不涉及通配符,所以两者是等价的)。

【讨论】:

  • 您好先生,您知道是否可以在此查询中添加其他限制?例如,指定时间段或限制到最后十个小时?我渴望学习,如果你有这个,请不要犹豫与我分享一些关于这个主题的教程或网站(除了 microsoft 文档)。
猜你喜欢
  • 2016-07-10
  • 2020-07-04
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多