PostgreSQL 分组查询计数字段作为 smth 的一部分和总计数字段

PostgreSQL grouping query for count field as part of smth and the total count field

我有 table: table 1(product_id,purchase_date,城市,市场,类别)

类别 = ('bread','soap','vegetables','fruits')

我需要一个结果 table(以下列): purchase_date、城市、市场、蔬菜数量table 产品、所有产品数量

按前三个字段进行分组,以便可以将前三个字段作为过滤器

如果不需要,请禁用 where 子句。

-- PostgreSQL
SELECT purchase_date
     , city
     , market
     , SUM(CASE WHEN category = 'vegetables' THEN 1 END) "count of vegetable products"
     , COUNT(1) "count of all products"
FROM table1
WHERE market = ? AND city = ? AND purchase_date = ?
GROUP BY purchase_date;
     , city
     , market

您需要条件聚合。在 Postgres 中,我推荐 filter:

SELECT purchase_date, city, market
       COUNT(*) FILTER (WHERE category = 'vegetables') as cnt_vegetables,
       COUNT(*) as cnt
FROM table1
WHERE market = ? AND city = ? AND purchase_date = ?
GROUP BY purchase_date, city, market;