SQL创建一个表

时间:2014-06-25 08:30:57

标签: sql oracle

CST_ID | TRC_TYPE | COLL_TYPE
2      | SH       |  NO
4566   | KA       |  WE
4566   | KA       |  TH
888    | EF       |  BV
44     | SC       |  BV    
44     | SC       |  BV
44     | KA       |  BV

我希望表1能够形成表2,以便TRC_TYPE(事务类型)和COLL_TYPE(并列类型)中的单元格成为列,计算客户执行了多少次而没有重复CST_ID(客户ID)。

CST_ID | SH | KA | EF | SC | NO | WE | TH | BV
2      | 1  | 0  | 0  | 0  | 1  | 0  | 0  | 0
4566   | 0  | 2  | 0  | 0  | 0  | 1  | 1  | 0 
888    | 0  | 0  | 1  | 0  | 0  | 0  | 0  | 1
44     | 0  | 1  | 0  | 2  | 0  | 0  | 0  | 3  

表2表示单个客户从表1中获取的信息所进行的交易和抵押品数量。

1 个答案:

答案 0 :(得分:0)

这是一个简单的PIVOT,但首先你应该创建一个子查询,使用UNION将两个类型的列合并为一个:

SELECT CST_ID,
   SUM(CASE WHEN Type='SH' THEN 1 ELSE 0 END) as SH,     
   SUM(CASE WHEN Type='KA' THEN 1 ELSE 0 END) as KA,
   SUM(CASE WHEN Type='EF' THEN 1 ELSE 0 END) as EF,
   SUM(CASE WHEN Type='SC' THEN 1 ELSE 0 END) as SC,
   SUM(CASE WHEN Type='KA' THEN 1 ELSE 0 END) as KA,
   SUM(CASE WHEN Type='NO' THEN 1 ELSE 0 END) as NO,
   SUM(CASE WHEN Type='WE' THEN 1 ELSE 0 END) as WE,
   SUM(CASE WHEN Type='TH' THEN 1 ELSE 0 END) as TH,
   SUM(CASE WHEN Type='BV' THEN 1 ELSE 0 END) as BV

FROM
(
  SELECT CST_ID,TRC_TYPE as Type FROM T
   UNION ALL
  SELECT CST_ID,COLL_TYPE as Type FROM T
) T1
GROUP BY CST_ID

SQLFiddel demo