与MULTITAB的枢轴表

时间:2014-10-11 05:08:24

标签: sql

我正在处理一组类似于以下内容的数据。

NAME    SALETYPE    UNITS   
AMBREEN SALE    98  
AMBREEN REFUND  4   
ASIF    SALE    80  
ASIF    REFUND  12  
ASIF    SALE    56  
FARHAN  REFUND  15  
FARHAN  SALE    124 
FARIHA  SALE    45  
FARIHA  REFUND  21  
JABEEN  SALE    120 
JABEEN  REFUND  72  
JABEEN  SALE    85  
JUNAID  SALE    69  
JUNAID  REFUND  8   
MUNEEB  SALE    25  
MUNEEB  REFUND  45  
MUNEEB  SALE    12  
MUSHTAQ SALE    15  
MUSHTAQ REFUND  25  
NASIRA  SALE    87  
NASIRA  REFUND  23  
SADAF   SALE    70  
SADAF   REFUND  14  
SADAF   SALE    45  
RAO SALE    100 
RAO REFUND  2   
SOHAIL  REFUND  20  
SOHAIL  SALE    123 

我需要将结果与以下内容相似。

NAME    SALE    REFUND  TOTAL
AMBREEN 98  4   102
ASIF    80  12  92
FARHAN  45  21  66
FARIHA  205 72  277
JABEEN  69  8   77
JUNAID  37  45  82
MUNEEB  25  15  40
MUSHTAQ 87  23  110
NASIRA  115 14  129
SADAF   100 2   102
RAO 0   20  20
SOHAIL  123 20  143

1 个答案:

答案 0 :(得分:1)

这个(条件聚合)应该适用于所有主要的RDBMS

SELECT name, sale, refund, sale + refund total
  FROM
(
  SELECT name, 
         SUM(CASE WHEN saletype = 'SALE'   THEN units ELSE 0 END) sale,
         SUM(CASE WHEN saletype = 'REFUND' THEN units ELSE 0 END) refund
    FROM table1
   GROUP BY name
) q
 ORDER BY name

输出:

|    NAME | SALE | REFUND | TOTAL |
|---------|------|--------|-------|
| AMBREEN |   98 |      4 |   102 |
|    ASIF |  136 |     12 |   148 |
|  FARHAN |  124 |     15 |   139 |
|  FARIHA |   45 |     21 |    66 |
|  JABEEN |  205 |     72 |   277 |
|  JUNAID |   69 |      8 |    77 |
|  MUNEEB |   37 |     45 |    82 |
| MUSHTAQ |   15 |     25 |    40 |
|  NASIRA |   87 |     23 |   110 |
|     RAO |  100 |      2 |   102 |
|   SADAF |  115 |     14 |   129 |
|  SOHAIL |  123 |     20 |   143 |

这是 SQLFiddle 演示