简体   繁体   中英

Return a SQL query where field doesn't contain specific text

I will setup a quick scenario and then ask my question: Let's say I have a DB for my warehouse with the following fields: StorageBinID, StorageReceivedDT, StorageItem, and StorageLocation.

Any single storage bin could have multiple records because of the multiple items in them. So, what I am trying to do is create a query that only returns a storage bin that doesn't contain a certain item, BUT, I don't want the rest of the contents. For example lets say I have 5000 storage bins in my warehouse and I know that there are a handful of bins that do not have "ItemX" in them, listed in the StorageItem field. I would like to return that short list of StorageBinID's without getting a full list of all of the bins without ItemX and their full contents. (I think that rules out IN, LIKE, and CONTAIN and their NOTS)

My workaround right now is running two queries, usually within a StorageReceivedDT. The first is the bins received with the date and then the second is the bins containing ItemX. Then import both .csv files into Excel and use a ISNA(MATCH) formula to compare the two columns.

Is this possible through a query? Thank you very much in advance for any advice.

You can do this as an aggregation query, with a having clause. Just count the number of rows where "ItemX" appears in each bin, and choose the bins where the count is 0 :

select StorageBinID
from table t
group by StorageBinID
having sum(case when StorageItem = "ItemX" then 1 else 0 end) = 0;

Note that this only returns bins that have some items in them. If you have completely empty bins, they will not appear in the results. You do not provide enough information to handle that situation (although I can speculate that you have a StorageBins table that would be needed to solve this problem).

What flavour of SQL do you use ? From the info that you gave, you could use:

select distinct StorageBinID
from table_name
where StorageBinID not in (
    select StorageBinID
    from table_name
    where StorageItem like '%ItemX%'
)

You'll have to replace table_name with the name of your table. If you want only exact matches (the StorageItem to be exactly "ItemX"), you should replace the condition

where StorageItem like '%ItemX%'

with

where StorageItem = 'ItemX'

Another option (should be faster):

select StorageBinID
from table_name
minus
select StorageBinID
from table_name
where StorageItem like '%ItemX%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM