从表中的事务类型创建列

时间:2010-09-01 02:21:26

标签: sql

我有一个SQL查询按事务类型分组,然后对金额求和,但希望总计金额在每个事务类型的列中

我有这个:

select Job, 
       sum(amount) as Amount, 
       transaction_type 
 from JCT_CURRENT__TRANSACTION
WHERE transaction_date >= {?Start Date} 
  and transaction_date <= {?End Date}
GROUP BY Job, transaction_type
ORDER BY Job ASC

但是想:

Job  | TransType1AmountSum  | TransType2AmountSum  |  TransType3AmountSum

所以我每个工作只能有一行。

3 个答案:

答案 0 :(得分:1)

使用:

  SELECT t.job,
         SUM(CASE WHEN t.transaction_type = 'TransType1' THEN t.amount ELSE NULL END) AS TransType1AmountSum,
         SUM(CASE WHEN t.transaction_type = 'TransType2' THEN t.amount ELSE NULL END) AS TransType2AmountSum,
         SUM(CASE WHEN t.transaction_type = 'TransType3' THEN t.amount ELSE NULL END) AS TransType3AmountSum
    FROM JCT_CURRENT_TRANSACTION t
   WHERE transaction_date BETWEEN {?Start Date} 
                              AND {?End Date}
GROUP BY t.job

答案 1 :(得分:0)

select Job, 
       sum(IF(transaction_type = 'transtype1', amount, 0)) as TransType1AmountSum, 
       ...,
       transaction_type 
 from JCT_CURRENT__TRANSACTION
WHERE transaction_date >= {?Start Date} 
  and transaction_date <= {?End Date}
GROUP BY Job

答案 2 :(得分:0)

这是另一种方法,它应该更快(特别是如果你有一个关于事务类型的索引并且正在进行多个操作 - 比如avg和count。)

这是在TSQL中

SELECT Job.Job, 
       sum(T1.amount) as TransType1AmountSum, count(T1.amount) as Count1, avg(T1.amount) as Avg1
       sum(T2.amount) as TransType2AmountSum, count(T2.amount) as Count2, avg(T2.amount) as Avg2
       sum(T3.amount) as TransType3AmountSum, count(T3.amount) as Count3, avg(T3.amount) as Avg3
 FROM JCT_CURRENT__TRANSACTION AS Job
 JOIN JCT_CURRENT__TRANSACTION T1 ON Job.Job = T1.Job AND T1.TransactionType = 'TransType1'
 JOIN JCT_CURRENT__TRANSACTION T2 ON Job.Job = T2.Job AND T2.TransactionType = 'TransType2'
 JOIN JCT_CURRENT__TRANSACTION T3 ON Job.Job = T3.Job AND T3.TransactionType = 'TransType3'
WHERE Job.transaction_date >= {?Start Date} 
  and Job.transaction_date <= {?End Date}
GROUP BY Job.Job