开发者

MySQL Retrieve Records Where Criteria is Unique and True i.e. No other records exist

I have a legacy database that I am working with a basic column layout as such:

SampleID
CompanyID
CompanyApplication
CompanyTest1
...
CompanyTest25

Not normalized in the least, this is causing a bit of a data mining issue.

I need to get the CompanyIDs (Grouped By) where the CompanyApplication field = "Registration" but this company has none of the CompanyTest(n) fields selected for any SampleID.

The problem is, there are CompanyIDs that have both CompanyApplication and CompanyTest(n) records (multiple rows), but I开发者_如何学Python want to get CompanyIDs that only have a CompanyApplication of Registration.

Data to help illustrate:

SampleID | CompanyID | CompanyApplication | CompanyTest1 | ... | CompanyTest25
------------------------------------------------------------------------
1         | 1        | Registration       |              |     |
------------------------------------------------------------------------
2         | 1        |                    | True         |     |
------------------------------------------------------------------------
3         | 2        | Registration       |              |     |
------------------------------------------------------------------------
4         | 2        | Registration       |              |     |
------------------------------------------------------------------------
5         | 3        |                    | True         |     |
------------------------------------------------------------------------
6         | 3        |                    |              |     | True

I only want to retrieve rows 3 and 4 because they ONLY have Registration and no other testing.


We could start by selecting all of the rows that you are trying to exclude, and then use a NOT EXISTS to skip over CompanyIDs that are in that query.

SELECT DISTINCT ct1.company_id
FROM company_table AS ct1
WHERE ct1.CompanyApplication = "Registration"
  AND NOT EXISTS(
        SELECT 1
        FROM company_table AS ct2
        WHERE ct1.company_id = ct2.compnay_id
          AND (ct2.CompanyTest1 IS NOT NULL
               OR ct2.CompanyTest2 IS NOT NULL
               ...
               OR ct2.CompanyTest25 IS NOT NULL)
        )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜