具有复合主键的2个表中的SQL计数

时间:2015-01-13 21:21:14

标签: sql oracle

我想从Table1返回行,其中表1中的复合键在表2中存在的次数多于2次。

我的尝试失败了:

 SELECT 
     t 
 FROM 
     Table1 t, Table2 m
 WHERE 
     t.brand = m.brand AND t.model = m.model
 GROUP BY 
     m.brand, m.model 
 HAVING 
     COUNT(m.brand) > 2

返回预期的行:

--------------------------------
brand  | model | color | price | 
--------------------------------
toyota |   R   |   r   |  25   |

表格:

表1

--------------------------------------
brand     |  model    | color | price | 
--------------------------------------
toyota    |     R     |   r   |  25   |
ford      |     T     |   y   |  40   |
chevy     |     X     |   b   |  10   |

表2

------------------------
brand      | model     |
------------------------
toyota     |     R     |
ford       |     T     |
chevy      |     X     |
toyota     |     R     |
toyota     |     R     |
chevy      |     X     |

2 个答案:

答案 0 :(得分:1)

您可以使用group by获得两次以上的组合:

SELECT m.brand, m.model
FROM Table1 t 
GROUP BY m.brand, m.model 
HAVING COUNT(m.brand) > 2;

您可以使用各种技术从table1获取相应的行。这是exists方法:

SELECT t.*
FROM Table1 t
WHERE EXISTS (SELECT 1
              FROM table2 m
              WHERE t.brand = m.brand AND t.model = m.model
              GROUP BY m.brand, m.model
              HAVING COUNT(*) > 2
             );

编辑:

在Oracle中,您可以使用窗口函数。这是最简单的方法:

SELECT *
FROM (SELECT t.*, COUNT(*) OVER (PARTITION BY t.brand, t.model) as cnt
      FROM Table1 t JOIN
           Table2 m
           ON t.brand = m.brand AND t.model = m.model
     ) tm
WHERE cnt > 2;

答案 1 :(得分:0)

看看这个简化的fiddle,我已经改变了联接。

SELECT m.brand, m.model  
 FROM T1 t INNER JOIN T2 m
 ON t.brand = m.brand AND t.model = m.model
 GROUP BY m.brand, m.model 
 HAVING COUNT(*) > 2