通过在sql server语句中添加时间变量进行分组

时间:2017-09-05 21:42:39

标签: sql sql-server

我有这个查询正在紧张但它需要更好。我正在学习sqlsrv并且正在努力解决时间问题。

基本上我需要拉出所有独特的到达(这是schtm +持续时间)并显示每小时的预期数量。有人能指出我正确的方向吗?

此查询显示每个唯一的时间,如5:30,5:45,6:00,6:15等。我需要按小时分组,以便显示5 - 6 - 7 - 8等然后低于它。

<?PHP
$currentdate = date('mdy');
    $this_time = date ("D, M j, Y H:i");
    $current_date = date('n-d-y');
    $this_time = date ("M j, Y H:i");

    echo"<table width=\"100%\" border=\"1\"><tr>";
$sql =  "SELECT DISTINCT cast(cast(SCHTM as datetime)+cast(DURATION as datetime) as time) as Arrivals FROM admissions.patientinfo WHERE SCHDT ='$currentdate' GROUP BY cast(cast(SCHTM as datetime)+cast(DURATION as datetime) as time)";

        $stmt = sqlsrv_query( $conn, $sql );

        while( $row = sqlsrv_fetch_array( $stmt , SQLSRV_FETCH_ASSOC) ) {
            $Arrivals=$row['Arrivals']->format('H:i');

            echo"<td align=\"center\">$Arrivals ";
        $sql = "SELECT DISTINCT PATNUM as Count FROM admissions.patientinfo WHERE SCHDT ='$currentdate' AND cast(cast(SCHTM as datetime)+cast(DURATION as datetime) as time) = '$Arrivals:00' ";
            $query = sqlsrv_query($conn, $sql, array(), array( "Scrollable" => 'static' ));

$row_count = sqlsrv_num_rows($query);

            echo"<br />$row_count</td>";
        }

    echo"</tr></table>"
?>

1 个答案:

答案 0 :(得分:0)

$sql =  "WITH CTE1
         AS 
         (SELECT DATEADD(HOUR, DATEPART(HOUR, CAST(SCHTM AS DATETIME)), 
         DATEPART(HOUR, CAST(DURATION AS DATETIME))) AS Arrivals FROM 
         admissions.patientinfo WHERE SCHDT ='$currentdate')
         SELECT CONVERT(VARCHAR(8), Arrivals, 108) FROM CTE1
         GROUP BY Arrivals";

此查询应将SCHTM和DURATION同时作为DATETIME,添加其小时数并打印为列到达。我把它放在一个CTE中,只显示TIME和正确的它。