简体   繁体   中英

SQL Server Distinct query with multiple conditional counts

I am trying to create a query to provide me with the turnaround time in minutes of a number of rows of testing data.

A succinct version of the table is:

TestName, StartDateTime, EndDateTime

And I am looking for a query that can give me a output something like:

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

Is this principle even possible?

Any direction would be greatly appreciated.

You could use something like this:

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)

Although depending on your DBMS you may need to use a different method of removing the time from the date.


Removing time from date:


SQL-Server 2008 and later:

SELECT  CAST(CURRENT_TIMESTAMP AS DATE)

SQL-Server 2005 and Earlier

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

Using SQL Server 2008 syntax (other databases have slightly different methods for datediff and 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)

As far as I know, it's not possible to do it like this. Perhaps you could do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM