计算字段的不同出现次数,按另一个字段分组

Count Distinct Occurrences of Field, Group By Another Field

对于给定的 shopId,我正在尝试计算符合与给定的 shop.

关联的所有 coupons 的唯一用户数

我有一个具有以下架构的 table:

id |    type   | orderId | userId | couponId |  status   | shopId |                
----+------------------+---------+--------+---------+-----------+-----
 39 | purchase |      89 |     33 |       1 | qualified |           18 
 43 | purchase |      90 |      5 |       3 | qualified |           18 
  1 | purchase |      68 |     32 |       1 | qualified |           18 
  2 | purchase |      69 |     32 |       3 | qualified  |           18 
  3 | purchase |      70 |     32 |       3 | qualified  |           18 
  4 | purchase |      71 |     38 |       1 | redeemed  |           18 
  5 | purchase |      72 |     39 |       2 | qualified  |           18 
  6 | purchase  |      73 |     30 |      9 | redeemed  |           11 

在下面的数据集上,如果我提供 shopId 18,我想获得结果:

couponId | count 
1           2    (2 unique users (33, 32) qualified for coupon 1)
2           2    (1 unique user (39))
3           2    (2 unique users (5,32)

下面的查询允许我计算有资格获得给定商店优惠券的不同用户总数,但我如何通过优惠券 ID 进一步细分?

SELECT COUNT(*) FROM (SELECT DISTINCT "userId" FROM "table" WHERE "shopId" = 18 AND status = 'qualified') AS temp;

您可以尝试将 COUNTDISTINCT

一起使用
SELECT couponId ,COUNT(DISTINCT userId) count 
FROM "table" 
WHERE "shopId" = 18 AND status = 'qualified'
GROUP BY couponId