1

我有一张名为 products 的表。

ProductId| ProductName| ProductType| ProductSize
1        | a          | yellow     |  12
2        | b          | green      |  13
3        | c          | yellow     |  12
4        | d          | yellow     |  15
________________________________________________

我想将每个产品的计数作为最后的一列,其中 productType 和 ProductSize 匹配,这是我想要的例外结果..

ProductID|ProductName|ProductType|ProductSize|TotalProduct
1        | a         | yellow    | 12        | 2
2        | b         | green     | 13        | 1
3        | c         | yellow    | 12        | 2
4        | d         | yellow    | 15        | 1
_________________________________________________________

一些我尝试过的,但失败的是看起来像这样。

select ProductId, ProductName, ProductType, ProductSize,
(select count(*) from Product where ProductType=(Products.ProductType) and ProductSize=(products.productSize)) as [TotalProduct] from Products

对于所有记录,它的返回 totalProduct = 4。谢谢

4

2 回答 2

2

在大多数 SQL 版本中,您将使用窗口/分析函数:

select ProductId, ProductName, ProductType, ProductSize,
       count(*) over (partition by producttype, productsize)
from products p

您的查询的问题是您没有为表名提供别名。因此,like 表达式ProductSize=(products.productSize)与外部查询不相关。它实际上等价ProductSize = ProductSize于内部查询。您只需from Products p输入内部查询即可解决此问题。但是,窗口函数方法在支持它的数据库(大多数)中更好。

于 2013-06-11T14:17:23.433 回答
0

producttype您可以通过使用子查询来获取每个productsize匹配项的计数来获得结果:

select producttype, productsize, count(*) TotalProduct
from product
group by producttype, productsize;

请参阅SQL Fiddle with Demo

然后你可以将你的product表加入到这个子查询中以获得最终结果:

select p1.productid,
  p1.productname,
  p1.producttype,
  p1.productsize,
  p2.totalProduct
from product p1
inner join
(
  select producttype, productsize, count(*) TotalProduct
  from product
  group by producttype, productsize
) p2
  on p1.producttype = p2.producttype
  and p1.productsize = p2.productsize;

请参阅SQL Fiddle with Demo。这给出了一个结果:

| PRODUCTID | PRODUCTNAME | PRODUCTTYPE | PRODUCTSIZE | TOTALPRODUCT |
----------------------------------------------------------------------
|         1 |           a |      yellow |          12 |            2 |
|         2 |           b |       green |          13 |            1 |
|         3 |           c |      yellow |          12 |            2 |
|         4 |           d |      yellow |          15 |            1
于 2013-06-11T14:27:56.427 回答