来自在线订购而不是在线订购的客户群

时间:2017-03-06 14:42:04

标签: sql

我有一个客户表(固定数量的客户)。这些客户通过在线或访问商店来购买商品。

我希望获得所有客户的列表,其中包含额外的列表。填写列(如果在线订购cutomer)1或(如果没有在线订购)0。

每位客户可以获得更多订单(通过电话,电子邮件或访问商店)。如果在线订购了该客户的部分订单,则在线订单列标记为X

我有订单表和客户表,标识符是客户ID。在订单表中,有一个标有X的列。我需要以某种方式转换X to 1和另一个0

我的表格如下:

Customer ID| Order ID| Order 1 |1 | - 1 |2 | 1 |3 |X 2 |4 | - 2 |5 | - 2 |6 | - 3 |7 |X 3 |8 |X 3 |9 |X

结果表应如下所示:

|Customer ID|Oredered Online |Customer1 |1 |Customer2 |0 |Customer3 |1

我不确切知道条件是否有效,我试过CASE,然后那样,没有按照我的意愿工作。

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以在subselect上使用not in子句

仅在店内订购的客户

select customer_id from my_table 
where customer_id not (select customer_id 
              from my_table where ordered_online = 1)

仅在线订购的客户

select customer_id from my_table 
where customer_id not (select customer_id 
            from my_table where ordered_online = 0)

如果您需要我可以使用相同的选择

select distinct  t1.customer_id , t2.check as only_shop,  t3.check as only_online, 
from my_table t1
left join (
    select distinct customer_id, 'X' as check  from my_table 
    where customer_id not (select customer_id 
                  from my_table where ordered_online = 1)
) t2 on t1.customer_id = t2.customer_id
left join (
    select distinct customer_id, 'X' as check from my_table 
    where customer_id not (select customer_id 
                from my_table where ordered_online = 0)
) t3 on  t1.customer_id = t3.customer_id

查看您的样本应

  select distinct customer_id, 1 as ordered_on_line  from my_table 
      where customer_id not (select customer_id 
                    from my_table where ordered_online = 1)
  union 
  select distinct customer_id, 0  from my_table 
      where customer_id not (select customer_id 
                  from my_table where ordered_online = 0)
  order by customer_id

答案 1 :(得分:0)

我希望这会奏效。如果没有,则订单列中的数据可能存在一些问题。也许你看不到空格或其他角色。

select customer_id
      ,order_number
      ,case when order = 'x' then 1
            else 0 end as ordered_online
from orders