如何计算在不同产品之后销售某种产品​​的每个实例? SQL或DAX

时间:2017-06-20 19:48:48

标签: sql count dax

如果标题看起来令人困惑,我很抱歉,这是我能想到的最好的。

我可以使用excel(Dax,因为它是一个强大的查询)和sql:

我的情况是购买了两种产品类型,Type_A和Type_B。

我想计算一个唯一的Loc_ID已经购买了多少" Type_A"产品类型,购买" Type_B"产品类型。

在我的示例中,总共有3个唯一的Loc_ID属于此过滤器:Loc_01,Loc_02和Loc_04

非常感谢任何帮助enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个(如果每个loc_id都购买了两种类型的产品,那么效果很好。

select count(*)
from
(select loc_id , max(date_purchased) dt
from table t where product_type = 'type_a'
group by loc_id) a,
(select loc_id , max(date_purchased) dt
from table t where product_type = 'type_b'
group by loc_id) b
where a.loc_id=b.loc_id and a.dt>b.dt;

答案 1 :(得分:1)

即使某些loc_id未购买两种类型的products

,这也会有效

试试这个: -

Select count(a.loc_id) as cnt_locations
from
your_table_name a
inner join
(
    Select a.loc_id,b.date_purchased,b.Product_type 
    from
    (
    Select loc_id, min(date_purchased) as date_purchased 
    from
    your_table_name 
    group by loc_id
    ) a
    inner join
    your_table_name b
    on a.loc_id=b.loc_id and a.date_purchased =b.date_purchased 
    where Product_type ='Type_B'
) b
on
a.loc_id=b.loc_id 
where a.date_purchased >b.date_purchased and a.Product_type ='Type_A'
相关问题