如何计算列内的相同名称?

How to count the same name inside a column?

这是我的专栏,显示用户投票的总统姓名:

我需要清点这些名字才能显示选举结果。如何使用 select count() 和分组依据进行计数?

以下 SQL 应该可以解决问题。

SELECT President, COUNT(*)
FROM tbl_voter
GROUP BY President

Select v.President, count(v.President) from tbl_voter v group by v.President;

您需要在计数函数中输入要计数的列的名称,并在同一列中使用分组依据。

如果你想为此使用 LINQ,你需要有一个 IQueryable 作为你的记录。之后就很简单了:

IQueryable<VotingRecord> votingRecords = ...
votingRecords.GroupBy(votingRecord => votingRecord.President)
.Select(presidentGroup => new
{
    President = presidentGroup.Key,
    VoteCount = presidentGroup.Count(),
});

GroupBy 将投票给同一位总统的 VotingRecords 组。群的Key是会长的名字。小组中的所有 VotingRecords 都投票给了这位 Key 总统。

Select取每个组,从每个组中取Key,也就是总统,以及这个组的VotingRecords数,也就是选票数总裁。

结果是包含 Presidents 和这位总统得票数的记录序列。

顺便说一下,我们希望适当的民主国家不要使用这个数据库,因为这样很容易找出谁投票给了谁。