2017-09-05 33 views
0

我有這個查詢工作在一個捏,但它需要更好。我正在學習sqlsrv,並且正在努力解決時間問題。在sql server語句中添加時間變量組

基本上我需要拉所有獨特的到來(這是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>" 
?> 
+0

SCHTM和DURATION是否不作爲日期時間存儲?這裏需要鑄造什麼? – Simon

+0

他們都是時間(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和持續時間爲DATETIME,增加了工作時間,並打印成列到達。我把它放在CTE中,只顯示TIME並將其正確分組。

+0

我沒有跟隨CTE1 - 你如何得到CTE1?我把它放在sql中,它打破了一切。 –

+0

這就是我所擁有的。我的網頁上沒有任何結果。如果我直接在服務器上查詢,我會得到結果。 (HOUR,DATEPART(HOUR,CAST(SCHTM AS DATETIME)),DATEPART(HOUR,CAST(DURATION AS DATETIME)))AS到達admissions.patientinfo WHERE SCHDT ='$ currentdate ') SELECT CONVERT(VARCHAR(8),Arrivals,108)FROM CTE1 GROUP BY Arrivals「; \t \t $ stmt = sqlsrv_query($ conn,$ sql); \t \t \t \t \t \t echo「 $ Arrivals」; \t \t而($行= sqlsrv_fetch_array($語句,SQLSRV_FETCH_ASSOC)){ \t \t \t $貨品= $行[ '到達']; –