按计数分组

时间:2010-06-14 08:40:04

标签: sql

让我们说我们有这样的行:

MyTable

ID Name  Product
------------------
1  Adam  x
2  Adam  y
3  Adam  z
4  Peter a
5  Peter b

使用类似的查询:

Select Name, Count(Product) from MyTable
group by Name

结果将是:

Adam 3
Peter 2

但我希望结果如下:

1 Adam x 3
2 Adam y 3
3 Adam z 3
4 Peter a 2
5 Peter b 2

我希望Ypu知道我的意思 你能帮我解决这个问题, 感谢帮助, 再见

5 个答案:

答案 0 :(得分:3)

您可以使用表上的子查询运行来连接表以选择计数:

SELECT a.ID as ID, a.Name as Name, a.Product as Product, ISNULL(b.cnt,0) as Cnt
FROM MyTable a
LEFT JOIN (SELECT Name, COUNT(*) as Cnt FROM MyTable GROUP BY Name) b
ON a.Name = b.Name

答案 1 :(得分:2)

怎么样?

Select *, Count() OVER(PARTITION BY Name) As C
from MyTable

答案 2 :(得分:1)

Select a.Id, 
       a.Name, 
       a.Product, 
       IsNull(b.CountOfUsers,0) as CountOfUsers

From MyTable a
Left Join (Select Name, Count(Product) as CountOfUsers from MyTable
          group by Name)b on a.Name = b.Name

答案 3 :(得分:0)

;WITH c AS (SELECT Name, COUNT(Product) CountOfProduct
            FROM MyTable
            GROUP BY Name)
SELECT t.Id, t.Name, t.Product, c.CountOfProduct
FROM MyTable t
INNER JOIN c ON c.Name = t.Name

答案 4 :(得分:0)

使用:

   SELECT x.id, 
          x.name, 
          x.product, 
          COALESCE(y.name_count, 0) AS num_instances
     FROM MyTable x
LEFT JOIN (SELECT t.name, 
                  COUNT(*) AS name_count
             FROM MyTable t 
         GROUP BY t.name) y ON y.name = x.name

COALESCE是ANSI标准处理NULL值的方法,并且受MySQL,SQL Server,Oracle,Postgre等支持。