我有一张名为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。 感谢
答案 0 :(得分:2)
在大多数SQL版本中,您将使用窗口/分析函数:
select ProductId, ProductName, ProductType, ProductSize,
count(*) over (partition by producttype, productsize)
from products p
您的查询的问题是您没有给表名别名。因此,ProductSize=(products.productSize)
之类的表达式与外部查询无关。它实际上相当于内部查询的ProductSize = ProductSize
。你可以通过在内部查询中添加from Products p
来解决这个问题。但是,窗口函数方法在支持它的数据库(大多数)中更好。
答案 1 :(得分:0)
您可以使用子查询来获取结果,以获取匹配的每个producttype
和productsize
的计数:
select producttype, productsize, count(*) TotalProduct
from product
group by producttype, productsize;
然后,您可以将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