简体   繁体   中英

Returning value where all rows match criteria

I'm working on an SQL query to return a list of users who have access to the same store. Stores are setup to require a Region, and a State. If Store, State, and Region are NULL, and the 'Access' is NOT Null, then user has full access to all stores. Example...

LocationID  |  UserID  |   StoreID   |   State   |   RegionID   |   Access   |
    1            1          NULL         NULL          NULL           1

Now, if the user has full access, EXCEPT at store 123, then they would have this for their table entries....

LocationID  |  UserID  |   StoreID   |   State   |   RegionID   |   Access   |
    1            1          NULL         NULL          NULL           1
    2            1          123          NULL          NULL          NULL

So this tells the software that they have full access, but at store 123, they have NULL (No) access.

What I'm trying to do is select all users that have access to a particular store. I have it right now so that it pulls all userId's where...

StoreID IN (SELECT StoreID FROM @tblStores) 
OR RegionID IN (SELECT RegionID FROM @tblStores)
OR StateID IN (SELECT State FROM @tblStores)

And this works fine for pulling all users where the StoreID, State, or RegionID match (there's also a check for Access IS NOT NULL)

My issue comes in for the people that have full access EXCEPT somewhere. How would I be able to select a user where the StoreId/State/RegionID are null, unless they have another entry where it matches the store/state/regionid and access is null?

So right now if i ran my query trying to find all users at store 123, it returns UserID 1, because UserID 1 has a row where everything is NULL and Access is not null. I need to check if UserID1 has NULL access to storeid 123, State (whatever), or RegionID (whatever)....

Any ideas on a fast way to do this? Is there a way you can say to only pull UserID's where ALL of the criteria match, is there?

You need to add something like this:

AND NOT userid in (select from where storeid=... and access is null)

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