1

Confusing title, I know. Ii couldn't think of a better way to word it. Basically, I have a table like this:

OwnerID | LotID | CurrentOwner

The OwnerID is the unique key for the table. This value is never repeated.
The LotID IS repeated. This table stores historical owner records for lots.
The CurrentOwner column simply contains a Y or NULL for each row. It is possible for one LotID to have multiple owners.

What I need is basically just for reporting. I need to know which LotIDs DO NOT have a "Y" for CurrentOwner in any of their rows. If I had the following data:

1, 1, Y  
2, 1, NULL  
3, 1, NULL  
4, 2, NULL  
5, 2, NULL  
6, 3, Y  
7, 3, NULL

Then I would need to know that LotID #2 does not have any owners currently.

2 Answers 2

2

I was able to solve my problem with the following query:

SELECT SUM(CASE 
             WHEN o.CurrentOwner IS NULL THEN 1
             ELSE 0
           END) AS numNull,
       COUNT(*) AS total,
       LotID
         FROM owner o GROUP BY LotID HAVING numNull=total
2
  • Yes, the SUM(CASE WHEN o.CurrentOwner IS NULL THEN 1 ELSE 0 END) is correct. You could also write it with COUNT(o.CurrentOwner) AS NotNull and HAVING NotNull = 0. By the way, both methods work only if the allowed values in that column are only NULL and 'Y'. If there are other allowed values, it would have to be a bit more complicated. Commented Dec 29, 2017 at 19:05
  • Eg, COUNT(CASE WHEN o.CurrentOwner = 'Y THEN 1 END) AS NumberOfY or SUM(o.CurrentOwner = 'Y') AS NumberOfY and HAVING NumberOfY = 0 Commented Dec 29, 2017 at 19:08
0

Redesign the schema. Have a separate table with PRIMARY KEY(lotID) that has a column OwnerID. This eliminates the chance of having two owners for one lot.

It does not, however, eliminate the issue of a lot with no owner. But the solution is pretty simple with either LEFT JOIN or NOT EXISTS.

Meanwhile, with the current schema, this should be a concise solution:

SELECT LotID
    FROM owner
    GROUP BY LotID
    HAVING  COALESCE(CurrentOwner) IS NULL;
1
  • This schema is being imported from some random other system into our system (new client acquisition). That's why I need to get good data from their stuff in the first place. Thanks for the suggestion though.
    – Kevin
    Commented Jan 1, 2018 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.