UserControlName.Dispatcher.Invoke(() => { UserControlName.Message = "some text !"; });
我有这张桌子,平均而言,我想知道用户在首次购买之前的次数。
所以平均值为(2 + 3)/ 2 = 2.5
知道如何编写这样的查询?
答案 0 :(得分:2)
select avg(cnt)
from
(
select user_id, 1 + count(*) as cnt
from tablename t1
where purchases = 0
and exists (select 1 from tablename t2
where t2.user_id = t1.user_id
and t2.purchases = 1)
and not exists (select 1 from tablename t3
where t3.user_id = t1.user_id
and t3.purchases = 1
and t3.came_to_site < t1.came_to_site)
group by user_id
)
子查询计算已完成购买(EXISTS
)但未在当前行(NOT EXISTS
)之前的每个user_id。
在主要级别,执行AVG()
以获得平均数。
或许,根据dbms,您需要执行avg(cnt * 1.0)
以避免整数结果。
答案 1 :(得分:0)
查找进行购买的所有用户的第一个购买日期,然后加入:
select avg(visits)
from (select t.user_id, count(*) visits
from (select user_id, min(came_to_site) first
from mytable
where purchases > 0
group by user_id) fpd
join mytable t on t.user_id = fpd.user_id and t.came_to_site < fpd.came_to_site) x
使用user_id
上的索引,这将表现得非常好。
答案 2 :(得分:0)
你可以这样做:
SELECT AVG(cpt) FROM (
SELECT sales_user.user_id, COUNT(*) AS cpt
FROM (
SELECT *
FROM users
WHERE purchases=1) sales_user
JOIN users ON sales_user.user_id=users.user_id
WHERE users.came_to_site < sales_user.came_to_site
GROUP BY sales_user.user_id);