SQLite - 如何使用WHERE条件执行COUNT()?

时间:2015-07-29 14:51:41

标签: sql sqlite subquery

我有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数据。

3 个答案:

答案 0 :(得分:5)

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条件。此外,还包括shelf_name子句中的group by

答案 1 :(得分:1)

您可以使用总和和条件:

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

答案 2 :(得分:0)

由于其他人已经展示了如何使用SUM执行此操作,我将使用COUNT显示它。我猜测产品表是与货架表分开的,这意味着你需要某种联系或其他东西。

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。希望有所帮助。