SELECT语句来计算元素

时间:2010-12-21 15:16:44

标签: sql database

我有一个SQL表:

[title]
ElementA
ElementA
ElementB
ElementC
ElementA
ElementA

我试图找到一种方法来计算最多出现的元素;在这个例子中,那将是 4因为ElementA已发生过4次。问题是,这个表是动态的,所以我不能只说SELECT COUNT(*) WHERE title = 'ElementA';

有没有人知道如何撰写SELECT语句来执行此操作?从概念上讲,它看起来很简单,但我无法让它发挥作用。

非常感谢, 布雷特

6 个答案:

答案 0 :(得分:4)

SELECT TOP 1 Title, COUNT(*) FROM table GROUP BY Title ORDER BY 2 DESC

SELECT Title, COUNT(*) FROM table GROUP BY Title ORDER BY 2 DESC LIMIT = 1

取决于您使用的产品。

(编辑以更正ORDER BY子句)。

答案 1 :(得分:3)

Select TOP 1 Title

FROM


(

Select 
   Count(title) k, title
FROM
    titles
GROUP BY 
   TITLE

) Count

 ORDER BY
      k Desc

答案 2 :(得分:2)

试试这个以获得完整列表

SELECT Title, Count (*) as NumOccurences
FROM MyTable
GROUP BY Title
Order BY NumOccurences

要获得顶级狗,请使用以下内容进行一些风味更改以适合您的SQL语法

SELECT TOP 1 Title, NumOccurences
FROM 
(
    SELECT Title, Count (*) NumOccurences
    FROM MyTable
    GROUP BY Title
    Order BY Count (*) DESC
) AS Titles

答案 3 :(得分:1)

Sql Server:

SELECT TOP 1 
    Title, COUNT(*) AS Count
FROM tbl
GROUP BY Title
ORDER BY Count DESC

Postgresql,MySQL等:

SELECT 
    Title, COUNT(*) AS Count
FROM tbl
GROUP BY Title
ORDER BY Count DESC
LIMIT 1

答案 4 :(得分:0)

使用group by对元素进行分组,然后按相应的最大数量进行分组。使用嵌套查询使解决方案更简单..:)

答案 5 :(得分:0)

WITH CTE (Title, Counter) as
 (SELECT Title, Count(*) Counter FROM #Test GROUP BY Title) 

SELECT Top 1 Title, Counter FROM CTE order by Counter Desc