计算字段的不同出现次数,按另一个字段分组
对于给定的 shopId
,我正在尝试计算有资格获得与给定商店关联的所有
优惠券
的唯一用户数量。
我有具有以下架构的表:
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;
For a given shopId
I'm trying to compute the number of unique users who qualified for all the coupons
associated with a given shop.
I have a table with the following schema:
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
On the below data set, if I supply the shopId
18, I want to obtain the result:
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)
The below query allows me to compute total number of distinct users who qualified for coupon for a given shop, but how can I further break this down by coupon id?
SELECT COUNT(*) FROM (SELECT DISTINCT "userId" FROM "table" WHERE "shopId" = 18 AND status = 'qualified') AS temp;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试将
COUNT
与DISTINCT
一起使用You can try to use
COUNT
withDISTINCT