如何在不重复客户的情况下编写此SQL?

时间:2016-03-10 15:03:17

标签: sql sql-server

我有一个表,每月都有客户列出和active_indicator。对于每个客户,我想将活动指标拉出两个月(2014年12月和2015年12月),但是当我写下面的代码时,我会得到一个表格,其中每个客户都列出两次。我知道我可以使用max将表扩展到客户级别,但是在一个简单的SQL查询中是否仍然可以执行此操作?

select distinct
     customer
    ,case when date='2015-12-01' then active_indicator else 0 end as Dec2015_active_ind
    ,case when date='2014-12-01' then active_indicator else 0 end as Dec2014_active_ind
from monthly_account_cust
where date in ('2015-12-01', '2014-12-01')
order by customer

1 个答案:

答案 0 :(得分:5)

很确定你正在寻找这样的东西。

select 
    customer
    , max(case when date = '2015-12-01' then active_indicator else 0 end) as Dec2015_active_ind
    , max(case when date = '2014-12-01' then active_indicator else 0 end) as Dec2014_active_ind
from monthly_account_cust 
where date in ('2015-12-01','2014-12-01')
group by customer
order by customer