【问题标题】:count with where clause multiple condition on same table用where子句在同一张表上计算多个条件
【发布时间】:2013-06-11 14:09:17
【问题描述】:

我有一个名为 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。 谢谢

【问题讨论】:

  • 请通过添加适当的标签(Oracle、SQL Server、MySQL 等)来指定您的目标关系数据库管理系统。可能有一些答案利用了不受普遍支持的语言或产品功能。此外,通过使用特定的 RDBMS 对其进行标记,您的问题可能会受到更适合回答的人的关注。
  • 我使用的是 sql server 2008

标签: sql join count subquery where


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-08
      • 2016-11-18
      • 2015-09-29
      • 2018-06-04
      • 2021-10-20
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多