如何在sql中计算count?

时间:2009-10-10 12:31:14

标签: sql sql-server sql-server-2005 tsql aggregate

我有下表:

memberid  
2
2
3
4
3

...我希望得到以下结果:

memberid    count
2           2
3           1    ---Edit by gbn: do you mean 2?
4           1

我试图使用:

  SELECT MemberID, 
         COUNT(MemberID) 
    FROM YourTable 
GROUP BY MemberID

...但现在我想找到哪个记录有最大数量。 IE:

memberid   count
2          2

10 个答案:

答案 0 :(得分:12)

SELECT memberid, COUNT(*) FROM TheTable GROUP BY memberid

虽然,它对你想要的输出不起作用,因为你有两次“memberid = 3”。

编辑:在更新后更新问题......

SELECT TOP 1 WITH TIES    --WITH TIES will pick up "joint top". 
    memberid, COUNT(*)
FROM
    TheTable 
GROUP BY 
    memberid
ORDER BY
    COUNT(*) DESC

答案 1 :(得分:1)

SELECT MemberID, COUNT(MemberID) FROM YourTable GROUP BY MemberID

答案 2 :(得分:1)

如果最大值达到平局(或更多)怎么办?您要显示一个还是全部?

我就是这样做的

SELECT memberid, COUNT(1)
FROM members
GROUP BY memberid
HAVING COUNT(1) = (
            SELECT MAX(result.mem_count)
            FROM (  
                SELECT memberid, COUNT(1) as mem_count
                FROM members
                GROUP BY memberid
            ) as result
          )

我希望看到一种更有效的方法。

答案 3 :(得分:0)

这样做:

SELECT memberid, COUNT(memberid) AS [count] FROM [Table] GROUP BY memberid

答案 4 :(得分:0)

这应该可以完成,不需要子选择:

select top 1 memberid, COUNT(*) as counted 
from members
group by memberid
order by counted desc

答案 5 :(得分:0)

可以很容易地完成:

SELECT TOP 1 MemberId, COUNT(*) FROM YourTable GROUP BY MemberId ORDER By 2 DESC

答案 6 :(得分:0)

我相信原始海报要求2个结果集。

我知道获得此功能的唯一方法(在SQL Server中)是将原始记录转储到临时表中,然后对其执行SELECT和MAX。我欢迎一个需要更少代码的答案!

-- Select records into a temp table
SELECT
    Table1.MemberId
    ,CNT = COUNT(*)
INTO #Temp
FROM YourTable AS Table1
GROUP BY Table1.MemberId
ORDER BY Table1.MemberId

-- Get original records
SELECT * FROM #Temp

-- Get max. count record(s) 
SELECT 
    Table1.MemberId
    ,Table1.CNT
FROM #Temp AS Table1
INNER JOIN (
    SELECT CNT = MAX(CNT)
    FROM #Temp
) AS Table2 ON Table2.CNT = Table1.CNT

-- Cleanup 
DROP TABLE #Temp

答案 7 :(得分:0)

这个查询怎么样:

SELECT TOP 1 MemberID, 
       COUNT(MemberID) 
FROM YourTable 
GROUP BY MemberID
ORDER by count(MemberID) desc

答案 8 :(得分:-1)

SELECT count(column_name) 来自your_table;

答案 9 :(得分:-1)

您需要使用子选择:

SELECT MemberID, MAX(Count) FROM
    (SELECT MemberID, COUNT(MemberID) Count FROM YourTable GROUP BY MemberID)
GROUP BY MemberID

第二组by需要返回count和MemberID。