4

我的表如下所示:

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 子句和 where in (select...),但我最终还是绕了一圈。

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

4

4 回答 4

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

于 2012-12-10T15:37:09.753 回答
0

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

SELECT
  ProductName,
  ProductCode,
  COUNT(*) as Total
FROM T
GROUP BY ProductName, ProductCode
HAVING COUNT(*) > 1
于 2012-12-10T15:30:13.810 回答
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
于 2012-12-10T15:52:48.960 回答
-1

您不能WHERE在要聚合的列上使用。你需要HAVING改用。

SELECT   ProductName,
         ProductCode,
         COUNT(*) AS Total
FROM     Products p
GROUP BY p.ProductName, 
         p.ProductCode
HAVING   COUNT(p.ProductName) > 1
于 2012-12-10T15:36:00.410 回答