0

我正在编写一个程序,我需要对数据库进行查询,询问在给定列中最常出现的字符串。在这个例子中,它的“stringONE”。

----------------------------
|  ID  |  Column (string)  |
----------------------------
|  1   |     stringONE     |
----------------------------
|  2   |     stringTWO     |
----------------------------
|  3   |     stringONE     |
----------------------------
|  4   |     stringONE     |
----------------------------

现在我需要把出现次数最多的字符串的名字放到一个变量字符串中,例如:

string most_appeared_string = sql.ExecuteScalar();

此外,如果没有出现最多的字符串,而是出现相同次数的 2 个或更多字符串,会发生什么情况,如下所示:

----------------------------
|  ID  |  Column (string)  |
----------------------------
|  1   |     stringONE     |
----------------------------
|  2   |     stringTWO     |
----------------------------
|  3   |     stringTWO     |
----------------------------
|  4   |     stringONE     |
----------------------------

提前谢谢。


@KeithS

您是否有查询的 sql-server 版本,因为我在那里尝试时遇到了一些错误。这是我想做的一个表格示例。

------------------------------------------------
|  ID  |  column1 (string) |  author (string)  |
------------------------------------------------
|  1   |     string-ONE    |       John        |
------------------------------------------------
|  2   |     string-TWO    |       John        |
------------------------------------------------
|  3   |     string-ONE    |      Martin       |
------------------------------------------------
|  4   |     string-ONE    |       John        |
------------------------------------------------

SELECT TOP (1) column1, COUNT(*) FROM table WHERE author='John' ORDER BY ID

它应该返回“string-ONE”,因为它对作者 John 出现的次数最多 (2)。但是,在 MS-SQL Management Studio 中尝试查询时,这是我得到的错误:

Column 'table.column1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

没关系编辑。谢谢你。

4

3 回答 3

3

这是一个非常简单的查询(至少在 T-SQL 中):

select top 1 Column, Count(*) from Table group by Column order by Count(*) desc

ExecuteScalar,根据实现细节,将返回字符串值,因为它是结果集中唯一行的第一列,即使有两列。您还可以使用 ExecuteReader 访问该字符串出现的次数。

于 2012-04-11T14:53:26.140 回答
2
select top (1) SomeCol, count(*) as Row_Count
from YourTable
group by SomeCol
order by Row_Count desc

Also, what happens if there is no string that appears the most, rather 2 or more strings that appear the same amount of times, like this:

In that case, using the above query, you will get one arbitrary row. You can add with ties to get all rows that has the same highest value.

select top (1) with ties SomeCol, count(*) as Row_Count
from YourTable
group by SomeCol
order by Row_Count desc
于 2012-04-11T15:10:04.027 回答
1
SELECT max(counted) AS max_counted FROM (
   SELECT count(*) AS counted FROM counter GROUP BY date
 )

这可以解决问题

于 2012-04-11T14:52:55.890 回答