2

我有一个包含 3 列的表idval1val2

对于 val2 的每个不同值,我想选择存在多个不同值 val1 的所有行。

例子:

| id | val1 | val2 |
|------------------|
| 1  | A1   |  a2  |
| 2  | A1   |  a2  |
| 3  | A1   |  b2  |
| 4  | B1   |  b2  |
| 5  | A1   |  c2  |
| 6  | A1   |  c2  |
| 7  | A1   |  c2  |
| 8  | A1   |  d2  |
| 9  | C1   |  d2  |
| 10 | A1   |  d2  |

期望的结果:

| id | val1 | val2 |
|------------------|
| 3  | A1   |  b2  |
| 4  | B1   |  b2  |
| 8  | A1   |  d2  |
| 9  | C1   |  d2  |
| 10 | A1   |  d2  |

我没有设法提出任何允许我这样做的查询,也许其他人对如何解决这个问题有想法。

4

4 回答 4

6

您可以使用having子句搜索val2具有多个不同值的val1. 例如:

select  yt.*
from    YourTable yt
join    (
        select  val2
        from    YourTable
        group by
                val2
        having  count(distinct val1) > 1
        ) as filter
on      yt.val2 = filter.val2
于 2012-05-25T10:27:14.523 回答
2

使用聚合窗口函数,您也可以这样做:

SELECT
  id,
  val1,
  val2
FROM (
  SELECT
    *,
    MIN(val1) OVER (PARTITION BY val2) AS minval1,
    MAX(val1) OVER (PARTITION BY val2) AS maxval1
  FROM atable
) s
WHERE minval1 <> maxval1
于 2012-05-25T13:15:53.830 回答
2

试试这个查询:

SELECT * from tbl where val2 in (SELECT  val2 FROM `tbl`  group by val2 having  
 count(distinct(val1)) > 1)
于 2012-05-25T11:02:45.537 回答
2
SELECT * 
FROM   TABLE_2 
WHERE  EXISTS (SELECT 1 
               FROM   (SELECT val2, 
                              val1, 
                              Count(*) AS Number 
                       FROM   TABLE_2 
                       GROUP  BY val2, 
                                 val1 
                       HAVING Count(*) = 1) a 
               WHERE  TABLE_2.val2 = a.val2) 
ORDER  BY ID 
于 2012-05-25T10:24:40.950 回答