您好我有这两个指标到目前为止运作良好:
-- --------------------------------------------
-- Nb Unique Accounts
-- -------------------------------------------
select count(distinct(O.user_id))
from DB.order O LEFT JOIN DB.orderCompleted OrC
ON O.id = OrC.order_id
where reason in ('2')
-- --------------------------------------------
-- Nb Accounts that are eighter deactivated or invalid
-- -------------------------------------------
select count(distinct(O.user_id))
from DB.order O JOIN DB.orderCompleted OrC
ON O.id = OrC.order_id
where reason (0,1)
问题#1:我们现在需要一个第三个指标,它将计算已被停用或无效的帐户的nb百分比。我们怎么能实现这一点呢?
问题#2:我们还希望只有一个大的SQL执行上面的所有3个小查询,然后使用这个联合或加入的大sql到商业智能报告工具,允许使用sql编码以显示它在crossTab
答案 0 :(得分:1)
试试这个:
SELECT
count(distinct CASE WHEN reason = 2 THEN O.user_id ELSE NULL END) AS "Nb Unique Accounts",
count(distinct CASE WHEN OrC.Oder_id IS NOT NULL AND reason in (1,2) THEN O.user_id ELSE NULL END) AS "Nb Accounts deactivated/invalid",
count(distinct CASE WHEN OrC.Oder_id IS NOT NULL AND reason in (1,2) THEN O.user_id ELSE NULL END) / count(distinct O.user_id) As "Percent deactived/invalid"
FROM DB.order O
LEFT JOIN DB.orderCompleted OrC ON O.id = OrC.order_id
答案 1 :(得分:0)
在
select count(distinct(O.user_id))
from DB.order O LEFT JOIN DB.orderCompleted OrC
ON O.id = OrC.order_id
where O.reason in ('2')
您正在计算表order
中的用户ID,无论他们是否有相关的orderCompleted
记录。您可以将其简化为:
select count(distinct user_id)
from DB.order
where reason = 2;
在查询中
select count(distinct(O.user_id))
from DB.order O JOIN DB.orderCompleted OrC
ON O.id = OrC.order_id
where reason (0,1)
你想要orderCompleted
中的匹配。你可以简单地把它变成:
select count(distinct user_id)
from DB.order
where reason in (0, 1)
and id in (select order_id from ordercompleted);
要获得两个计数,请使用条件聚合。你也可以做数学:
select
count(distinct case when reason = 2 then user_id end),
count(distinct case when reason in (0, 1) and id in (select order_id from ordercompleted) then user_id end),
count(distinct case when reason in (0, 1) and id in (select order_id from ordercompleted) then user_id end) /
count(distinct user_id)
from DB.order
where reason in (0, 1, 2);
或者将子查询移动到FROM
子句:
select
count(distinct case when o.reason = 2 then o.user_id end),
count(distinct case when o.reason in (0, 1) and oc.id is not null then o.user_id end),
count(distinct case when o.reason in (0, 1) and oc.id is not null then o.user_id end) /
count(distinct user_id)
from DB.order o
left join (select distinct order_id from ordercompleted) oc using (order_id)
where o.reason in (0, 1, 2);
答案 2 :(得分:-1)
嗨,这个伟大论坛的所有人。
请参阅rhis post消息的末尾,看看正确的MySql代码片段,我只能在一个大查询中找到。
另外,我正在进行LEFT JOIN的原因是因为订单O表中的数据可能在OrderCompleted OrC表中没有相应的数据。
@HLGEM:你的意思是
SELECT (col1/col2) AS Percent...
From ( Select col1, col2 from ...)
Where ...
- Nb独立帐户
select count(distinct(O.user_id))
from DB.order O LEFT JOIN DB.orderCompleted OrC ON O.id = OrC.order_id where O.reason in (2)
- Nb已停用或无效的帐户
select count(distinct(O.user_id))
from DB.order O JOIN DB.orderCompleted OrC ON O.id = OrC.order_id
where O.reason in (0,1)