Solved

SQL Statement to select Distinct from Audit Table

Posted on 2010-11-19
2
248 Views
Last Modified: 2012-05-10
I have that is being populated by a trigger.  The action field will contain an "I' (Insert), "U" (Update), or "D" (Delete).  I need to perform a select on that table. and display the last I, U, and D in that table.  So, no matter how many rows there are in there, only 3 should be displayed by the select statement.

Any ideas?
AuditTable.jpg
0
Comment
Question by:CipherIS
  • 2
2 Comments
 
LVL 32

Accepted Solution

by:
bhess1 earned 125 total points
Comment Utility
This code should do what you need:


SELECT *

FROM AuditTable

WHERE TestCpkid in (

    SELECT Max(TestCpkid) FROM AuditTable Where Action = 'I'

    UNION

    SELECT Max(TestCpkid) FROM AuditTable Where Action = 'U'

    UNION

    SELECT Max(TestCpkid) FROM AuditTable Where Action = 'D'

    )

Open in new window

0
 
LVL 32

Expert Comment

by:bhess1
Comment Utility
Of course, you may want to create an index by Action and TestCpkid Desc.  In that case, you could use the UNION of three TOP 1 select statements, e.g.

CREATE INDEX ix_Action_pkid ON AuditTable (Action, TestCpkid Desc)

SELECT TOP 1 * FROM AuditTable
WHERE Action = 'I'
ORDER BY TestCpkid DESC
UNION
SELECT TOP 1 * FROM AuditTable
WHERE Action = 'U'
ORDER BY TestCpkid DESC
UNION
SELECT TOP 1 * FROM AuditTable
WHERE Action = 'D'
ORDER BY TestCpkid DESC
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

by Mark Wills Attending one of Rob Farley's seminars the other day, I heard the phrase "The Accidental DBA" and fell in love with it. It got me thinking about the plight of the newcomer to SQL Server...  So if you are the accidental DBA, or, simp…
INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

744 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now