多个计数和分组

时间:2012-12-10 15:25:36

标签: sql sql-server-2008 tsql

我的表格如下:

ID ProductName ProductCode
1  abc         123
2  abc         123
3  abc         456
4  def         789
5  ghi         246
6  jkl         369
7  jkl         369
8  jkl         369
9  jkl         468
10 jkl         468

我希望创建一个如下所示的汇总表:

ProductName ProductCode Total
abc         123         2
abc         456         1
jkl         369         3
jkl         468         2

换句话说,我对产品“def”和“ghi”不感兴趣,因为它们只出现在原始表中一次。对于其他一切我想通过ProductName和ProductCode进行分组并显示计数。

我尝试过使用group by子句以及在哪里(选择...),但我刚刚结束了圆圈。

该表有大约50,000行,位于SQL Server 2008 R2上。

4 个答案:

答案 0 :(得分:3)

就是这样:

SELECT
      ProductName,
      ProductCode,
      COUNT(*) as Total
 FROM Table1
 WHERE ProductName IN (SELECT ProductName FROM Table1 GROUP BY ProductName HAVING COUNT(*) > 1)
 GROUP BY ProductName, ProductCode

http://www.sqlfiddle.com/#!3/c79ad/9

答案 1 :(得分:0)

要过滤聚合,您需要使用HAVING子句:

SELECT
  ProductName,
  ProductCode,
  COUNT(*) as Total
FROM T
GROUP BY ProductName, ProductCode
HAVING COUNT(*) > 1

答案 2 :(得分:0)

;WITH cte AS
 (
  SELECT ID, ProductName, ProductCode,
         COUNT(*) OVER (PARTITION BY ProductName, ProductCode) AS Total,
         COUNT(*) OVER (PARTITION BY ProductName) AS PCount,
         ROW_NUMBER() OVER (PARTITION BY ProductName, ProductCode ORDER BY ID) AS rn
  FROM Products
  )
  SELECT ID, ProductName, ProductCode, Total
  FROM cte
  WHERE PCount > 1 AND rn = 1

答案 3 :(得分:-1)

您无法在汇总的列上使用WHERE。您需要改为使用HAVING

SELECT   ProductName,
         ProductCode,
         COUNT(*) AS Total
FROM     Products p
GROUP BY p.ProductName, 
         p.ProductCode
HAVING   COUNT(p.ProductName) > 1