【问题标题】:How to write this SQL without duplicating the customer?如何在不复制客户的情况下编写此 SQL?
【发布时间】:2023-03-08 22:05:01
【问题描述】:

我有一张表,每个月都会列出带有 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

【问题讨论】:

  • 标记使用的 dbms(MySQL 还是 MS SQL Server?)。列date的数据类型?
  • 除非你聚合它,否则假设有两行符合日期条件,你将得到两行。

标签: sql sql-server


【解决方案1】:

很确定您正在寻找类似的东西。

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

【讨论】:

  • 嗯,是的,我应该知道试试这个。谢谢!
  • 如果这对你有用,那么你应该考虑接受这个作为答案。
  • 大声笑我不知道说实话。我从来没有在这里问过问题。 :) 我认为有一个按钮或只有你能看到的东西才能接受这个答案。
  • 是的,我正在寻找。我看到一个“回答你的问题”按钮,但没有任何东西可以接受你的答案作为答案。也许我必须点击“回答您的问题”按钮。让我试试……顺便说一句,谢谢你的帮助:)。我懂了。这是upvote 和downvote 箭头下的复选标记 - 它是一种浅灰色,一开始我看不到它。
猜你喜欢
  • 2016-04-02
  • 1970-01-01
  • 2019-10-23
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
相关资源
最近更新 更多