简体   繁体   中英

SQL count across 2 tables with composite primary key

I want to return the rows from Table1 where the composite key from Table1 exists more than say 2 times in Table 2.

My attempt which fails:

 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

Expected rows returned:

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

Tables:

Table1

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

Table2

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

You can get the combinations that appear more than twice using group by :

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

You can get the corresponding rows from table1 using various techniques. Here is the exists method:

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
             );

EDIT:

In Oracle, you can use window functions. That is the simplest way:

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;

Take a look at this simplified fiddle , I've changed the join.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM