SQL Query result, need a subquery to validate

I have this query:

select datediff(minute,ti.dtupdated, getdate()) as 'Minutes Old',ti.dtCreated,ti.sTicket_Number,ti.dblTotal,
      ve.sPlate,ti.bHouseAccount, ti.Ticket_ID
            from tickets as ti
            inner join vehicles as ve on ve.lVehicleID = ti.lVehicleID
            where datediff(day,dtupdated, getdate()) < 1 and datediff(minute,dtupdated, getdate()) > 15 and bPaid=0 and dbltotal>2 and SUSERNAME is not null
            and (bDeleted=0 or bDeleted is null)

It returns results for unpaid tickets.  However if the ticket vehicleid shows up again in the same day, I don't want to return any records.

Please advise.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Phillip BurtonDirector, Practice Manager and Computing ConsultantCommented:
So, if there is one on a particular day, you want one record to show.

But if there are two on a particular day, you want zero records to show in total?
PortletPaulEE Topic AdvisorCommented:
Do the basic selection of tickets using a  common table expression (CTE), this allows us to re-use that selection because we not only want the details but want to exclude any vehicles that have multiple tickets amongst the details. We can exclude those vehicles by using GROUP BY and a HAVING clause of COUNT(*) = 1 i.e. a vehicle that has two or more records in the selected data will be excluded.

;WITH cte AS (
              SELECT * 
              FROM tickets
              WHERE dtupdated > DATEADD(minute,-15, GETDATE() )
              AND dtupdated < DATEADD(minute, -1, GETDATE() )
              AND bPaid = 0
              AND dbltotal > 2
              AND (bDeleted = 0 OR bDeleted IS NULL)
      DATEDIFF(MINUTE, ti.dtupdated, GETDATE()) AS 'Minutes Old'
    , ti.dtCreated
    , ti.sTicket_Number
    , ti.dblTotal
    , ve.sPlate
    , ti.bHouseAccount
    , ti.Ticket_ID
FROM cte AS ti
INNER JOIN vehicles AS ve ON ve.lVehicleID = ti.lVehicleID
           SELECT lVehicleID FROM cte GROUP BY lVehicleID
           HAVING COUNT(*) = 1
           ) st on ti.lVehicleID = st.lVehicleID

Open in new window

I only recommend CTE's for 2 reasons: when you need recursion or you can re-use. Here we can re-use.
There may be error in this suggestion because it isn't clear which tables all the fields come from (this is why you should prefix fields by their table or alias). If there are fields in the cte not contained in the tickets table please amend the where clause in that cte and add a where clause to the query that follows the cte.

One last comment.

In a where clause it is more efficient to avoid using functions on every row of data. e.g.

instead of this:
                           where datediff(day,dtupdated, getdate()) < 1 and datediff(minute,dtupdated, getdate()) > 15

do this:
              where dtupdated > dateadd(minute,-15, getdate() ) and dtupdated < dateadd(minute, -1, getdate() )

this way [dtupdated] is not changed, instead we alter the criteria to suit the data
You just need to add a NOT EXISTS at the end of the query:

select datediff(minute,ti.dtupdated, getdate()) as 'Minutes Old',
  from tickets as ti
  inner join vehicles as ve 
          on ve.lVehicleID = ti.lVehicleID
  where datediff(day,dtupdated, getdate()) < 1 
   and datediff(minute,dtupdated, getdate()) > 15 
   and bPaid=0 
   and dbltotal>2 
   and SUSERNAME is not null
   and (bDeleted=0 or bDeleted is null)
                    FROM tickets ti2
                   WHERE ti2.lVehicleID = ti.lVehicleID
                     AND CONVERT(varhcar, ti2.dtupdated,112) = CONVERT(varhcar, ti.dtupdated,112)
                     AND ti2.Ticket_ID <> ti.Ticket_ID)

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Vitor MontalvãoMSSQL Senior EngineerCommented:
4eggheads, do you still need help on this question?
4eggheadsAuthor Commented:
yes, i'm evaluating the options...been away this week.
4eggheadsAuthor Commented:
jr2003 yours look the most promising.  I will test it soon.
4eggheadsAuthor Commented:
Thanks everything good except varchar mispelled :-)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.