我正在尝试创建一个查询,以便在几分钟内为我提供多行测试数据的周转时间。
该表的简洁版本是:
TestName,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 :(得分: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)
SELECT DATE(CURRENT_TIMESTAMP)
<强> Oracle 强>
SELECT TRUNC(CURRENT_TIMESTAMP)
<强> Postgresql 强>
SELECT CURRENT_TIMESTAMP::DATE
答案 1 :(得分:2)
使用SQL Server 2008语法(其他数据库对datediff
和cast(... 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)
答案 2 :(得分: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