Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

sql query for selecting conditionally

Posted on 2014-04-07
Last Modified: 2014-04-17
I've been staring at this for too long and I can't get my head wrapped around this.

To simplify this, let's say I have a table that holds computer name, status, timestamp.  For example:

computer1 | ERROR | 4/7/2014 4:21 PM
computer1 | OK | 4/7/2014 4:22 PM
computer2 | OK | 4/7/2014 4:22 PM
computer2 | ERROR | 4/7/2014 4:23 PM

From this I want a list of computer that have a current status of ERROR.  If that computer has a more recent record with a status of OK then I don't want to see it.
Question by:bigbigpig
  • 3
  • 2
  • 2
  • +4
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 39984534
select 'c1' computer, 'ERROR' stat, '4/7/2014 4:21:00 PM' dt into #temp

insert into #temp
select 'c1' computer, 'OK' stat, '4/7/2014 4:22:00 PM'

insert into #temp
select 'c2' computer, 'OK' stat, '4/7/2014 4:22:00 PM'

insert into #temp
select 'c2' computer, 'ERROR' stat, '4/7/2014 4:23:00 PM'

;with cte as
(select row_number() over(partition by computer order by dt desc) rowNm, *
 from #temp
 select * from cte
 where RowNm = 1 and stat = 'ERROR'
LVL 35

Assisted Solution

by:Terry Woods
Terry Woods earned 166 total points
ID: 39984671
I'd write it like this:

select computer_name, timestamp
from my_table as blah
where status = 'ERROR'
and timestamp = (select max(timestamp) from my_table where computer_name = blah.computer_name)

Open in new window

LVL 48

Expert Comment

ID: 39984692
no points pl.
I'd go with using row_number() as proposed by Kyle Abrahams, however it isn't necessary to use a CTE, this would do the same:
    , timestamp
                , timestamp
                , ROW_NUMBER() OVER (PARTITION BY computer ORDER BY dt DESC) rowNm
            FROM #temp
      ) AS x
WHERE RowNm = 1
      AND stat = 'ERROR'

Open in new window

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.


Expert Comment

ID: 39984733

You can do like this but it's a little bit tricky, anyway for the tests i made it works:

SELECT Computer as XComputer, Max(DateZ+Status) AS MaxDateZ
group by Computer
HAVING substring(Max(DateZ+Status),14,50)='ERROR';

The idea here is to join the date and the satus to get something like this:
20140408231010OK  - or -

this way you can use the MAX to get the last Status for that PC and then check if in that string exists the word "ERROR" with the function HAVING.

You will need to work the "Datez"  and format it in someting like "yyyyMMddhhmmss", check your regional options.

Fields: Computer, Status (ERROR/OK), DateZ (date)

Hoper this help
LVL 69

Accepted Solution

Scott Pletcher earned 167 total points
ID: 39986226
The method below avoids any second reads of the original table:

SELECT [computer name]
FROM dbo.tablename
GROUP BY [computer name]
    MAX(CASE WHEN status = 'ERROR' THEN timestamp END) =
LVL 32

Assisted Solution

awking00 earned 167 total points
ID: 39986301
I don't think the proposed solutions necessarily cover other potential scenarios, such as a single computer having a status of 'ERROR' or three rows in which the chronological statuses are 'ERROR','OK','ERROR'.
I think the following should work -
select computer_name, status, timestamp from
(select computer_name, status, timestamp,
 row_number() over (partition by computer_name order by timestamp desc) dt_rn,
 rank() over (partition by computer_name order by status desc) stat_rnk
 from tbl) as x
where dt_rn > 1 and stat_rnk = 2;
LVL 10

Author Closing Comment

ID: 40006598
Thanks everyone for the comments.  Apparently lots of ways to work this these all worked.
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40006860
>> I don't think the proposed solutions necessarily cover other potential scenarios, such as a single computer having a status of 'ERROR' or three rows in which the chronological statuses are 'ERROR','OK','ERROR'. <<

My code would handle either/both of those conditions.
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40007545
As would mine . . . I was surprised it wasn't excepted as a solution.
LVL 32

Expert Comment

ID: 40007610
My apologies. I misread the question to mean show only those records with a status of 'ERROR' where a previous status was 'OK' and not just where the curent status was 'ERROR'. Forgive me.
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40007965
No issues awking :-)

Featured Post

Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Virtual SQL Server 2014 Standard 35 89
sql, case when & top 1 14 26
Help with Oracle IF statment 5 24
Query for timesheet application 3 17
Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how the fundamental information of how to create a table.

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question