我们有一个这样的表:
+----+--------+
| Id | ItemId |
+----+--------+
| 1 | 1100 |
| 1 | 1101 |
| 1 | 1102 |
| 2 | 2001 |
| 2 | 2002 |
| 3 | 1101 |
+----+--------+
我们想要计算每个人有多少物品,并向他们展示2件或更多物品。像这样:
+----+-----------+
| Id | ItemCount |
+----+-----------+
| 1 | 3 |
| 2 | 2 |
+----+-----------+
我们没有计算Id = 3的人,因为他只有1项。
我们如何在SQL中执行此操作?
答案 0 :(得分:3)
SELECT id, COUNT(itemId) AS ItemCount
FROM YourTable
GROUP BY id
HAVING COUNT(itemId) > 1
答案 1 :(得分:1)
SELECT id,
count(1)
FROM YOUR_TABLE
GROUP BY id
HAVING count(1) > 1;
答案 2 :(得分:1)
使用此查询
SELECT *
FROM (
SELECT COUNT(ItemId ) AS COUNT, Id FROM ITEM
GROUP BY Id
)
my_select
WHERE COUNT>1
答案 3 :(得分:0)
select Id, count(ItemId) as ItemCount
from table_name
group by Id
having ItemCount > 1