سؤال

I have order management system in which I have a table. There can be a request for which there should be a response. For example:-

There are 2 columns UniqueNumber and Type as below:-

A Request
A Response
B Request
C Request
D Request
E Request
E Response
C Response

I want to query those unique numbers in the table which has request but do not have a response. For example in above case B and D

هل كانت مفيدة؟

المحلول 2

Use a left self join with a condition that filters out matches:

select t1.UniqueNumber
from mytable t1
left join mytable t2 on t2.UniqueNumber = t1.UniqueNumber
  and t2.type = 'Response'
where t1.type = 'Request'
and t2.type is null

This query works because the join condition attempts to find the response by putting the test for type in the join condition and missed joins return nulls for the values and the where clause seeks those.

As long as there's an index on UniqueNumber, this query will out-perform all other forms due to the efficiencies of joins.

نصائح أخرى

You can select all Requests and the remove those that have a Response:

SELECT t1.UniqueNumber
FROM your_table t1
WHERE t1.Type = 'Request'
  AND NOT EXISTS
  (
    SELECT 1
    FROM your_table t2
    WHERE t2.UniqueNumber = t1.UniqueNumber
    AND t2.Type = 'Response'
  )

Performance could be improved with a composite index on (Type, UniqueNumber).

SELECT UniqueNumber, Type FROM table
WHERE UniqueNumber IN
(SELECT  UniqueNumber, COUNT( UniqueNumber)
FROM table
GROUP BY UniqueNumber
HAVING COUNT( UniqueNumber)=1) 

...... By the way .....

Your Unique number is not a unique number if it can be repeated twice, I hope you have a primary key for index and performance purposes although the combination of UniqueNumber and Type makes a concatenated primary key which is unique.

You also could try a minus:

  select t1.uniqueNumber
    from myTable t1
   where t1.type = 'Request'
  minus
  select t1.uniqueNumber
    from myTable t1
   where t1.type = 'Response'

This way is generally fast and, IMO, easy to read.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top