【问题标题】:SQLite - How to perform COUNT() with a WHERE condition?SQLite - 如何使用 WHERE 条件执行 COUNT()?
【发布时间】:2015-07-29 14:51:40
【问题描述】:

我有一个 products 表,其中包含以下字段:_idproduct_namepriorityshelf_id

我有一个 shelves 表,其中包含以下字段:_idshelf_name

目前,我有这个 SQL,它返回一个结果集,显示每个货架的名称以及每个货架中的产品数量:

SELECT
    shelves._id AS _id,
    shelves.shelf_name AS shelf_name,
    COUNT(products._id) AS total_num_products_in_shelf
    
FROM
    shelves

INNER JOIN
    products ON shelves._id = products.shelf_id
    
GROUP BY
    shelves._id
    
HAVING
    COUNT(products._id) > 0
    
ORDER BY
    shelf_name ASC

我想要实现的是在结果集中创建一个附加列,该列将显示每个货架中priority 值大于零的产品数量。类似的东西......

SELECT
    shelves._id AS _id,
    shelves.shelf_name AS shelf_name,
    COUNT(products._id) AS total_num_products_in_shelf,
    COUNT(products._id WHERE products.priority > 0) AS num_products_in_shelf_with_priority
...

...但当然有效。

我搜索了 sqlite 子查询,找到了this tutorial,但它似乎不是我想要的。

有人可以帮助我朝着正确的方向前进,或者更好的是,修改我的 SQL 查询,使其返回有效的num_products_in_shelf_with_priority 数据。

【问题讨论】:

  • 这不是Android相关的问题。
  • 好的,很公平。我已经删除了 Android 标签。

标签: sql sqlite subquery


【解决方案1】:
SELECT
shelves._id AS _id,
shelves.shelf_name AS shelf_name,
COUNT(products._id) AS total_num_products_in_shelf,
sum(case when products.priority > 0 Then 1 else 0 end) 
as num_products_in_shelf_with_priority
FROM shelves INNER JOIN products
ON shelves._id = products.shelf_id
GROUP BY shelves._id, shelves.shelf_name
HAVING COUNT(products._id) > 0
ORDER BY shelf_name ASC

您可以包含case 条件,然后包含sum 它。此外,group by 子句中还包括 shelf_name

【讨论】:

    【解决方案2】:

    由于其他人已经展示了如何使用 SUM 来做到这一点,我将使用 COUNT 来展示它。我猜 products 表与shelf 表是分开的,这意味着您需要某种连接或其他东西。

    SELECT shelves._id AS _id
          ,shelves.shelf_name AS shelf_name
          ,(SELECT COUNT(products._id) FROM products b WHERE a._id = b.shelf_id) total_num_products_in_shelf
          ,(SELECT COUNT(products._id) FROM products b WHERE a._id = b.shelf_id AND b.priority > 0) AS num_products_in_shelf_with_priority
    FROM shelves a
    ORDER BY a.shelf_name ASC
    

    如果每个产品 ID 或其他内容有多行,请将 COUNT 更改为 COUNT(DISTINCT。如果每个架子有多行,则将SELECT 更改为SELECT DISTINCT。希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      您可以为此使用总和和条件:

      SUM(CASE WHEN products.priority > 0 THEN 1 ELSE 0 END) AS num_products_in_shelf_with_priority
      

      【讨论】:

        【解决方案4】:

        在 SQLite v3.32.0 and above 中,您可以使用IIF() 函数只计算优先级大于0 的产品:

        SUM(IIF(products.priority > 0, 1, 0))
        

        使用COUNT()的另一种选择:

        COUNT(IIF(products.priority > 0, 1, NULL))
        

        【讨论】:

          猜你喜欢
          • 2011-09-07
          • 1970-01-01
          • 2011-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多