带有COUNT条件的嵌套SELECT查询



我有两个表。我有一个简单的内部连接查询,其中字段从两个表Deals和Deals_Country中选择。

两个表共享一个名为Id的字段。这是Deals中的主键。Deals_Country中的外键。所以id在Deals中总是唯一的,但在Deals_Country中并不总是唯一的。

我想在我的简单内部连接查询中添加一个进一步的条件。我想只返回MA_DEALS_COUNTRY中有多个id的记录。请看下面的例子。

 select DEALS.id, DEALS.field_b, DEALS_COUNTRY.field_c DEALS_COUNTRY.field_d, 
 from DEALS
 inner join DEALS_COUNTRY
 on DEALS.id = DEALS_COUNTRY.id
 where 
 (
    select id
    from DEALS_COUNTRY
    group by id
    having count(id) > 1
 ) 
 order by id

DEALS
id
AA11
AB34
AN21
BN44
DEALS_COUNTRY
id      some_code
AA11    4506
AB34    5052
AB34    6161
AB34    0124
AN21    6322
AN21    9548
BN44    0012
结果

Deal.id    Deal_Country.some_code
AB34       5052
AB34       6161
AB34       0124
AN21       6322
AN21       9548   
select DEALS.id, DEALS.field_b, DEALS_COUNTRY.field_c DEALS_COUNTRY.field_d, 
 from DEALS
 inner join DEALS_COUNTRY
 on DEALS.id = DEALS_COUNTRY.id
 where  exists
 (
    select x.id
    from DEALS_COUNTRY x
    where  x.id = DEALS.id
    group by x.id
    having count(x.id) > 1
 ) 
 order by deal_id

另一种方法是使用count() over()

SELECT
      id
    , field_b
    , field_c
    , field_d
FROM (
            SELECT
                  DEALS.id
                , DEALS.field_b
                , DEALS_COUNTRY.field_c
                , DEALS_COUNTRY.field_d
                , COUNT(*) OVER (PARTITION BY DEALS_COUNTRY.id) AS cnt
            FROM DEALS
                  INNER JOIN DEALS_COUNTRY
                              ON DEALS.id = DEALS_COUNTRY.id
      ) AS sq
WHERE cnt > 1

最新更新