MySQL:使用同一行上的列值进行计数

时间:2015-06-15 11:59:29

标签: mysql

如何使用其他列的值,以便我可以使用所有相同类型的总和创建另一列。

e.g。

+---------+------+
|  name   | team |
+---------+------+
| Michael | red  |
| Lebron  | blue |
| Ben     | red  |
| Tiger   | red  |
| John    | blue |
+---------+------+

输出:

+---------+------+----------------+
|  name   | team | member_counter |
+---------+------+----------------+
| Michael | red  |              3 |
| Lebron  | blue |              2 |
| Ben     | red  |              3 |
| Tiger   | red  |              3 |
| John    | blue |              2 |
+---------+------+----------------+

你可以看到3个红色和2个蓝色。那么我还能使用之前列的值吗? count(团队=上一栏)?作为member_counter?

4 个答案:

答案 0 :(得分:1)

您应该使用所有球队的子选择进行join

select name, team, teams.count 
 from names
 join (select team, count(1) as count from names group by team) as teams
using (team);

sqlfiddle

答案 1 :(得分:1)

您可以JOIN到包含team的派生表计数:

SELECT m.name, m.team, t.cnt AS  member_counter
FROM mytable AS m
INNER JOIN (
   SELECT team, COUNT(*) AS cnt
   FROM mytable
   GROUP BY team ) t
ON m.team = t.team

这可能比相关的子查询表现得更好。

Demo here

答案 2 :(得分:1)

  1. 如果你只想要这样的结果,你可以这样做:

    SELECT T1.name,T1.team,T2.member_count
    FROM TableName T1 JOIN
      (SELECT name,team,count(team) as member_count
       FROM TableName
       GROUP BY team) T2 ON T1.team=T2.team
    

    结果:

    name    team    member_count
    ----------------------------
    Michael red     3
    Lebron  blue    2
    Ben     red     3
    Tiger   red     3
    John    blue    2
    

    SQL Fiddle

  2. 中的示例
  3. 如果您要在表格中添加一列member_counter,可以执行以下操作:

    ALTER TABLE TableName
    ADD member_counter INT NULL
    
    
    UPDATE TableName a 
       JOIN 
       (SELECT name,team,COUNT(team) as member_counter
        FROM TableName b
        GROUP BY team) b ON a.name = b.name  AND a.team=b.team
    SET a.member_counter = b.member_counter
    

    SQL Fiddle

  4. 中的示例

答案 3 :(得分:-1)

只做一个子查询:

        [HttpPost]
    public ActionResult Edit(ContactsEditViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            var Contacts = TheContactContext.tblContacts.Find(viewModel.ID);
            Contacts.Company = viewModel.Company;
            Contacts.Contact = viewModel.Contact;
            Contacts.Contact2 = viewModel.Contact2;
            Contacts.Email1 = viewModel.Email1;
            Contacts.Email2 = viewModel.Email2;
            Contacts.IsSupplier = viewModel.IsSupplier;
            Contacts.Telephone = viewModel.Telephone;
            Contacts.Link = viewModel.Website;
            Contacts.Notes = viewModel.Notes;

            TheContactContext.SaveChanges();
            return RedirectToAction("~/Contacts/Index");
        }
        return View(viewModel);
    }

修改

我检查了100万行。此查询的执行计划和已接受答案的查询具有99%的相同性。通过时间统计,两个查询的执行完全相同。使用IO统计信息,两个查询执行完全相同。而现在我无法理解为什么我被投票。唯一的区别是我的版本更短,更容易理解。

<强> EDIT2:

这是工作小提琴:

select *, (select count(*) from table t2 where t1.team = t2.team) as member_counter 
from table t1