[英]Count how many rows have the same value but if the ID are different count it separate
Here's my query,这是我的查询,
Select r.coupon_id, c.who_added, c.coupon_name, r.when_added
From redeemed_coupons r
JOIN coupon c on r.coupon_id = c.coupon_id AND c.who_added = 1
AND r.when_added BETWEEN 1602827745 AND 1613084678 ORDER BY r.when_added
How do I get the count of a row with same value of when_added
but if the coupon_id
is different you have to count it separately even if you have same when_added
我如何获得具有相同
when_added
值的行的计数,但如果coupon_id
不同,即使您具有相同的when_added
您也必须单独计算它
the result go like this:结果是这样的:
|coupon_id|who_added|coupon_name|when_added| total_count|
|---------|---------------------------------------------|
| 1 | 1 |Free Appe. |1602827745| 1 |
| 2 | 1 |Free Appe. |1602835586| 1 |
| 3 | 1 |10% off |1603084636| 1 |
| 4 | 1 |50% off |1603084678| 2 |
Do you just want a count using a window function?你只想使用窗口函数进行计数吗?
select r.coupon_id, c.who_added, c.coupon_name, r.when_added,
count(*) over (partition by r.coupon_id, r.when_added) as cnt
from redeemed_coupons r join
coupon c
on r.coupon_id = c.coupon_id and
c.who_added = 1 and
r.when_added BETWEEN 1602827745 AND 1613084678
order by r.when_added ;
EDIT:编辑:
In older versions of MySQL, you can use a correlated subquery:在旧版本的 MySQL 中,您可以使用相关子查询:
select r.coupon_id, c.who_added, c.coupon_name, r.when_added,
(select count(*)
from redeemed_coupons r2 join
coupon c2
on r2.coupon_id = c2.coupon_id and
c2.who_added = 1 and
r2.when_added BETWEEN 1602827745 AND 1613084678
where r2.when_added = r.when_added
)
from redeemed_coupons r join
coupon c
on r.coupon_id = c.coupon_id and
c.who_added = 1 and
r.when_added BETWEEN 1602827745 AND 1613084678
order by r.when_added ;
Note that this is much less efficient than using window functions.请注意,这比使用窗口函数效率低得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.