SQL查询计算不同的记录并在1行中打印

时间:2018-05-16 16:23:17

标签: sql firebird

我有下表,我正在寻找一个SQL查询,它计算每个名字的奖励,并打印获得特定奖励类型的最后日期。

这是我的表:

   NAME   |   REWARD    |    DATE
----------+-------------+------------
  Chris   |    small    |  18.05.2014
  Chris   |    small    |  27.08.2015
  Chris   |    big      |  01.07.2014
  Tom     |    big      |  10.10.2016
  Tom     |    big      |  30.11.2017

结果应如下所示:

   NAME   | BIG_REWARDS | SMALL_REWARDS | LAST_BIG_REWARD | LAST_SMALL_REWARD
----------+-------------+---------------+-----------------+-------------------
  Chris   |      1      |       2       |    01.07.2014   |    27.08.2015
  Tom     |      2      |       0       |    30.11.2017   |        

我正在使用Firebird

1 个答案:

答案 0 :(得分:5)

您可以使用条件聚合:

SELECT name,  
      SUM(CASE WHEN reward = 'big'   THEN 1 ELSE 0 END) AS BIG_REWARDS,
      SUM(CASE WHEN reward = 'small' THEN 1 ELSE 0 END) AS SMALL_REWARDS,        
      MAX(CASE WHEN reward = 'big'   THEN "DATE" END) AS LAST_BIG_REWARD,
      MAX(CASE WHEN reward = 'small' THEN "DATE" END) AS LAST_SMALL_REWARD
FROM tab
GROUP BY name;