x

Comparing rows in same column SQL Server

Hi How would I get the result (last table) from the above data sets. Displays all T2 where no barcodes appeared in T6.

alt text

aa.jpg (45.7 kB)
more ▼

asked Apr 12 at 04:11 AM in Default

avatar image

lomas
1

So you want to select items where transcode is T3 and barcode isn't in the list of barcodes where transcode = T6?

Apr 12 at 09:18 AM ThomasRushton ♦♦

Yes absolutely right. Thanks

Apr 12 at 09:26 AM lomas
(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

There are many ways of getting the desired results. One way is to use a correlated subquery:

 select
     a.[Date], a.TransCode, a.BarCode
     from YourTable a
     where a.TransCode = 'T3' and not exists (
         select 1
             from YourTable
             where TransCode = 'T6' and BarCode = a.BarCode
     );
 go

The other way is to use the left join:

 select
     a.[Date], a.TransCode, a.BarCode
     from YourTable a left join YourTable b
         on a.BarCode = b.BarCode and b.TransCode = 'T6'
     where a.TransCode = 'T3' and b.TransCode is null;
 go

Which of the 2 queries will perform better is not possible to tell without knowing the details about the data (indexes, record count, cardinalityof values etc., but is easy to check by highlighting both queries and hitting Ctrl + L in SSMS query window to display the estimated plans for both. These should reveal which query is better.

Hope this helps.

Oleg

more ▼

answered Apr 12 at 01:36 PM

avatar image

Oleg
20.6k 3 7 29

Thanks Mate. Its perfectly working.

Apr 16 at 05:12 AM lomas
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x87

asked: Apr 12 at 04:11 AM

Seen: 42 times

Last Updated: Apr 16 at 05:12 AM

Copyright 2018 Redgate Software. Privacy Policy