跨两个表的SQL计数

时间:2015-01-07 16:30:31

标签: sql

我想返回Base表中具有超过特定计数的库存的行。

这样的事情,但有困难......

SELECT b 
FROM Base b, Inventory i
WHERE COUNT(b.brand = i.brand) > 2  

应该返回:

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

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

Inventory
---------
brand  |
---------
toyota |
ford   |
ford   |
ford   |
toyota |
chevy  |
chevy  |
chevy  |

修改历史记录

  • 我已更新Base表以包含所需的更多行

4 个答案:

答案 0 :(得分:2)

从您的查询中,您似乎正在尝试进行加入,然后进行计数。

类似的东西:

SELECT *
FROM Base b
INNER JOIN Inventory I
ON (b.brand = i.brand)
GROUP BY i.brand
HAVING COUNT(i.brand) > 2

另一种选择(我能想到的)是使用嵌套选择:

SELECT * 
FROM Base
WHERE brand IN (
        SELECT brand
        FROM Inventory
        GROUP BY brand
        HAVING COUNT(*) > 2
              )

答案 1 :(得分:1)

使用group byhaving子句过滤brand count >2试用此内容。

select * from base b where exists(SELECT 1
FROM Inventory i
where b.brand=i.brand
group by brand
having COUNT(1) > 2  )

答案 2 :(得分:1)

您可以使用GROUP BY对记录进行分组,并使用HAVING过滤这些群组:

SELECT b.brand, b.model
FROM Base b
JOIN Inventory i 
ON b.brand = i.brand
GROUP BY b.brand, b.model 
HAVING COUNT(i.brand) > 2  

答案 3 :(得分:1)

只有一个GROUP BY HAVING可以做到这一点。 你可以这样做:

SQL Fiddle

SELECT b.*
FROM Inventory i
INNER JOIN base b 
ON b.brand = i.brand
GROUP BY i.brand
HAVING COUNT(i.brand) > 2

<强> Results

| BRAND | MODEL |
|-------|-------|
| chevy |     X |
|  ford |     T |