2

I have a table with two columns: ColumnA, ColumnB, with rows:

| A | 1 |
| B | 1 |
| B | 2 |
| C | 1 |
| C | 1 |
| C | 1 |
| A | 2 |
| B | 1 |
| A | 2 |
| A | 1 |

I would like to write a query that would return all unique values for ColumnB, for each unique value of ColumnA, where ColumnA has more than 1 value in ColumnB i.e.

| A | 1 |
| A | 2 |
| B | 1 |
| B | 2 |

C 1 should be omitted because there is only one distinct value for ColumnA = 'C'

2 Answers2

3

There might be a simpler approach but this works:

SELECT t.ColumnA, t2.ColumnB
FROM ( select ColumnA 
       from dbo.TableName t 
       group by t.ColumnA
       having count(distinct t.ColumnB) > 1) t
CROSS APPLY ( select distinct t2.ColumnB 
              from dbo.TableName t2 
              where t.ColumnA=t2.ColumnA ) t2

The first subquery returns all unique ColumnA values that have multiple (different) ColumnB values. The 2nd subquery returns all distinct ColumnB values of those ColumnA-values with CROSS APPLY.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2
SELECT DISTINCT * FROM x WHERE ColumnA IN(
    SELECT xd.ColumnA
    FROM (
        SELECT DISTINCT ColumnA, ColumnB FROM x
    ) xd
    GROUP BY xd.ColumnA HAVING COUNT(*) > 1 
)

SELECT y.ColumnA, y.ColumnB
FROM (
    SELECT ColumnA, ColumnB, COUNT(*) OVER (PARTITION BY  ColumnA) m
    FROM x 
    GROUP BY ColumnA, ColumnB
) y
WHERE m > 1
IvanP
  • 263
  • 7
  • 21