SQL:添加列并将其分类到类别中

时间:2014-11-04 17:52:10

标签: sql sql-server join

我有一个以transaction_id为主键的表,还包含customer_id这是一个外键。

现在有一个列type有两个值:'Card''cash'

现在一些客户已经使用了这两种付款方式。我想添加一个新列并将客户分类为"只有卡" "只有现金"和"两者"。

Transaction id      Customer id Type
1                   100         Card   
2                   101         Cash 
3                   102         Card 
4                   103         Cash
5                   101         Card

因此,在此表中我想要一个新列'付款方式'由于他使用了两种付款方式,因此将客户101分类为两者。

4 个答案:

答案 0 :(得分:1)

您可以使用窗口功能:

select t.*,
       (case when min(type) over (partition by customerid) = max(type) over (partition by customerid)
             then 'Only ' + min(type) over (partition by customerid)
             else 'both'
        end)
from transactions t;

答案 1 :(得分:1)

你可以做得更好并删除一些重新融合(仅限现金,卡只会在表格中重复,在这种情况下,我们更喜欢重复ID)。因此,您可以创建一个表格,例如payement_methods,其中包含两列,例如idmethod,您将使用刚才提到的三个选项填充它(仅限现金,仅限卡片,两者都有,例如,您在transaction table列中payment_method_id(而不是您使用的类型列)。

例如

|id     | method       |
|1      | Cash only    |
|2      | Card Only    |
|3      | Both         |

交易表

|id     | other columns ...|payement method  |
|1      | other columns ...|1                |
|2      | other columns ...|3                |
//...
抱歉我的英语,祝你好运。

答案 2 :(得分:0)

Create table tran1(Transactionid int ,   Customerid int  , Type varchar(100))

insert into tran1(Transactionid ,   Customerid , Type ) values
(1         ,          100    ,     'Card ' ),
(2         ,          101    ,     'Cash' ),
(3         ,          102    ,     'Card ' ),
(4         ,          103    ,     'Cash ' ),
(5         ,          101    ,     'Card ' )

alter table tran1 add NewType varchar(100)



Update tran1 set NewType ='Only card' where Customerid IN  (
select d.custid from (
 select Customerid as custid,SUM(case when [Type]='Card' then 1 else 0 end) card
 ,SUM(case when [Type]='Cash' then 1 else 0 end) cash
 from tran1
 group by Customerid)d
 where d.card=1  
 )


Update tran1 set NewType ='Only Cash' where Customerid IN  (
select d.custid from (
 select Customerid as custid,SUM(case when [Type]='Card' then 1 else 0 end) card
 ,SUM(case when [Type]='Cash' then 1 else 0 end) cash
 from tran1
 group by Customerid)d
 where d.cash=1  
 )

Update tran1 set NewType ='Both' where Customerid IN  (
select d.custid from (
 select Customerid as custid,SUM(case when [Type]='Card' then 1 else 0 end) card
 ,SUM(case when [Type]='Cash' then 1 else 0 end) cash
 from tran1
 group by Customerid)d
 where d.card=1 and cash=1
 )

答案 3 :(得分:0)

如果你想要做的是分析付款方式,而不是在表中添加一列,那么做这样的事情可能会更好:

SELECT DISTINCT Table1.[Customer ID], T1.*
FROM Table1
CROSS APPLY (SELECT SUM(CASE WHEN [Type] = 'Cash' THEN 1 ELSE 0 END) AS Cash,
           SUM(CASE WHEN [Type] = 'Card' THEN 1 ELSE 0 END) AS Card
          FROM Table1 T WHERE T.[Customer ID] = Table1.[Customer ID]) T1

给你这样的结果:

CUSTOMER ID CASH    CARD
100          0       1
101          1       1
102          0       1
103          1       0