Get row which matched in each group

时间:2017-11-13 06:09:29

标签: sql sql-server

I am trying to make a sql query. I got some results from 2 tables below. Below results are good for me. Now I want those values which is present in each group. for example, A and B is present in each group(in each ID). so i want only A and B in result. and also i want make my query dynamic. Could anyone help?

| ID | Value |
|----|-------|
|  1 |     A |
|  1 |     B |
|  1 |     C |
|  1 |     D |
|  2 |     A |
|  2 |     B |
|  2 |     C |
|  3 |     A |
|  3 |     B |

3 个答案:

答案 0 :(得分:3)

In the following query, I have placed your current query into a CTE for further use. We can try selecting those values for which every ID in your current result appears. This would imply that such values are associated with every ID.

WITH cte AS (
    -- your current query
)

SELECT Value
FROM cte
GROUP BY Value
HAVING COUNT(DISTINCT ID) = (SELECT COUNT(DISTINCT ID) FROM cte);

enter image description here

Demo

答案 1 :(得分:2)

The solution is simple - you can do this in two ways at least. Group by letters (Value), aggregate IDs with SUM or COUNT (distinct values in ID). Having that, choose those letters that have the value for SUM(ID) or COUNT(ID).

select Value from MyTable group by Value
having SUM(ID) = (SELECT SUM(DISTINCT ID) from MyTable)

select Value from MyTable group by Value
having COUNT(ID) = (SELECT COUNT(DISTINCT ID) from MyTable)

答案 2 :(得分:0)

Use This

WITH CTE
AS
(
    SELECT
      Value,
  Cnt = COUNT(DISTINCT ID)
  FROM T1
  GROUP BY Value
)
SELECT
Value
FROM CTE
WHERE Cnt = (SELECT COUNT(DISTINCT ID) FROM T1)