如何运行此查询?

时间:2017-04-15 07:09:38

标签: sql database

我有下表

MID IID

1   23

1   24

1   25

2   32

2   54

3   11

4   55

5   67

我希望找到所有MID的计数(IID)> 1 即结果应该是

MID count(IID)

1   3

2   2

P.S - 我试过但是我得到了所有MID的结果。这是我的查询

select distinct a.MID,count(a.IID) from Item_attribute as a group by a.MID

4 个答案:

答案 0 :(得分:1)

添加如下的子句:

having count(a.IID)>1

答案 1 :(得分:0)

在SELECT语句中使用HAVING子句:

SELECT a.MID,count(a.IID) 
FROM Item_attribute as a 
GROUP BY a.MID
HAVING COUNT(a.IID) > 1

答案 2 :(得分:0)

请尝试以下方法......

SELECT MID,
       COUNT( IID ) as CountIID
    FROM Item_attribute
    GROUP BY MID
HAVING COUNT( IID ) > 1;

如有其他疑问,请尝试以下操作...

SELECT MID,
       CountIID
FROM
(
    SELECT MID,
           COUNT( IID ) as CountIID
    FROM Item_attribute
    GROUP BY MID
    HAVING COUNT( IID ) > 1
) AS limitedCountIIDFinder
WHERE CountIID =  ( SELECT MAX( CountIID ) AS MaxCountIID
                    FROM
                    (
                        SELECT MID,
                               COUNT( IID ) as CountIID
                        FROM Item_attribute
                        GROUP BY MID
                    ) AS countIIDFinder
                  )

(以下说明......)

如果您有任何问题或意见,请随时发表评论。

答案 3 :(得分:0)

如果您希望在聚合字段中拥有条件,则需要使用having 如果您使用group by,也不需要使用distinct 在你的情况下:

select a.MID,count(a.IID) from Item_attribute as a group by a.MID having count(a.IID)>1 

如果您想获得最大计数值,请按降序排序并获得前1:

select top 1 a.MID,count(a.IID) 
from Item_attribute as a 
group by a.MID 
having count(a.IID)>1 
order by count(a.IID) desc