2013-02-05 86 views
2

我正在嘗試創建一個查詢,以爲我提供幾分鐘的測試數據行的週轉時間。SQL Server與多個條件計數的不同查詢

表的簡潔版本是:

測試名,的startDateTime,EndDateTime

我要尋找一個查詢,可以給我一個輸出類似:

Distinct TestName 
, StartDate[not time] 
, Count(rows) as Total 
, Count(rows where datediff(minute, StartDateTime, EndDateTime) <=60) as NonBreach 
, Count(rows where datediff(minute, StartDateTime, EndDateTime) >60) as Breach 
, Count(rows where datediff(minute, StartDateTime, EndDateTime) >60)/Count(rows) as BreachRate 

這是原理甚至可能?

任何方向將不勝感激。

+0

您也可以隨時加入結果形成的測試名不同查詢 – Techmonk

回答

4

你可以使用這樣的事情:

SELECT TestName, 
     CAST(StartdateTime AS DATE) AS StartDate, 
     COUNT(*) AS Total, 
     COUNT(CASE WHEN DATEDIFF(MINUTE, StartDateTime, EndDateTime) <= 60 THEN 1 END) AS NonBreach, 
     COUNT(CASE WHEN DATEDIFF(MINUTE, StartDateTime, EndDateTime) > 60 THEN 1 END) AS Breach, 
     1.0 * COUNT(CASE WHEN DATEDIFF(MINUTE, StartDateTime, EndDateTime) > 60 THEN 1 END)/COUNT(1) AS BreachRate 
FROM YourTable 
GROUP BY TestName, CAST(StartdateTime AS DATE) 

雖然這取決於你的DBMS,您可能需要使用不同的方法從日期中刪除時間


從日期刪除時間:


SQL-Server 2008及更高版本:

SELECT CAST(CURRENT_TIMESTAMP AS DATE) 

SQL-Server 2005和此前

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0) 

MySQL & SQLite

SELECT DATE(CURRENT_TIMESTAMP) 

Oracle

SELECT TRUNC(CURRENT_TIMESTAMP) 

Postgresql

SELECT CURRENT_TIMESTAMP::DATE 

+1

+1爲您的1.0 *轉換爲十進制的方法。但是在OP中有兩個'Startdate'列名是'StartDateTime'。 –

+0

@BernhardHofmann謝謝。編輯並更改爲'StartDateTime'。 – GarethD

+1

感謝您在日期操作上的additioanl位。 – user2044096

2

使用SQL Server 2008的語法(其它數據庫有稍微不同的方法datediffcast(... as date)

select TestName 
,  cast(StartDateTime as date) as StartDate 
,  count(*) as Total 
,  sum(case when datediff(minute, StartDateTime, EndDateTime) <= 60 
      then 1 end) as NonBreach 
,  sum(case when datediff(minute, StartDateTime, EndDateTime) > 60 
      then 1 end) as Breach 
,  1.0 * sum(case when datediff(minute, StartDateTime, EndDateTime) > 60 
      then 1 end)/count(*) as BreachRate 
from YourTable 
group by 
     TestName 
,  cast(StartDateTime as date) 
+0

感謝這麼多 - 什麼是布偶 - 所以簡單;我的頭因爲需要獨特的測試而被抓住了。 – user2044096

0

據我所知,這是不可能做到這一點是這樣的。 也許你可以做這樣的事情:

Select TestName 
    , StartDate[not time] 
    , Count(rows) as Total 
    , SUM(CASE WHEN datediff(minute, StartDateTime, EndDateTime) <=60 THEN 1 ELSE 0 END) as NonBreach 
    , SUM(CASE WHEN datediff(minute, StartDateTime, EndDateTime) >60 THEN 1 ELSE 0 END) as Breach 
+1

您不能在同一個查詢中使用不同的聚合(如總和或計數) – Andomar

+0

您的權利,我只是複製了問題,並沒有改變它。抱歉 –