简体   繁体   English

SQL —仅选择具有特定多个值的列

[英]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). 我需要对A列中所有在B列中同时具有'F'和'G'的值进行计数。在这种情况下,我的结果应为2(A和B都具有F和G-C和D不)。

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'.) 我还需要获取B列中仅具有'G'的A中所有值的计数。我在该方案中的结果应为1(A和B都具有'G',但它们还有其他值好吧,E只有一个“ 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 您应该检查不同的B

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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