简体   繁体   中英

SQL — Selecting only columns that have specific multiple values

I am drawing a major blank here. Please help me out. Here's my scenerio:

************************
| Column A  | Column B |
|    A      |     C    |
|    A      |     D    |
|    A      |     E    |
|    A      |     F    |
|    A      |     G    |
|    A      |     H    |
|    B      |     C    |
|    B      |     D    |
|    B      |     E    |
|    B      |     F    |
|    B      |     G    |
|    B      |     H    |
|    C      |     C    |
|    C      |     D    |
|    C      |     E    |
|    C      |     F    |
|    C      |     H    |
|    C      |     I    |
|    D      |     C    |
|    D      |     D    |
|    D      |     I    |
|    E      |     G    |
************************

I need to get a count of all the values in column A that have BOTH a 'F' AND a 'G' in column B. My Result in this scenario should be a 2 (A and B have BOTH F and G -- C and D do not).

I also need to get a count of all the values in A that have ONLY a 'G' in column B. My Result in the scenario should be a 1 (A and B both have a 'G', but they have other values as well. E ONLY has a 'G'.)

The only thing I can come up with is the following -- I am sure I am WAY off the mark on this one:

    SELECT COUNT(C.A)
    FROM (
          SELECT C.A
          FROM T
          WHERE C.B = 'F'
          OR C.B = 'G'
          GROUP BY C.A
          HAVING COUNT(*) > 1
         ) AS CNT

You shoud chech for distinct Bs

SELECT COUNT(*) As CountOfAs
    FROM (
          SELECT C.A
          FROM T
          WHERE C.B = 'F'
          OR C.B = 'G'
          GROUP BY C.A
          HAVING COUNT(DISTINCT(B)) > 1
         ) AS CNT

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