选择具有多个不同列值组合的行

时间:2012-05-25 10:10:51

标签: sql postgresql select postgresql-9.1

我有一个包含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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 

答案 2 :(得分:2)

尝试此查询:

SELECT * from tbl where val2 in (SELECT  val2 FROM `tbl`  group by val2 having  
 count(distinct(val1)) > 1)

答案 3 :(得分: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