我试图减去两列,然后计算有多少具有相同的差异并将这些总和放入列中。总和的数量是按日期分组的-3或更多,-2,-1,0,1,2,3或更多的差异。
必须对DB2数据库执行查询。
数据...
------------------------------
| Date | Num 1 | Num 2 |
------------------------------
| 2014-02-11 | 19872 | 19873 |
| 2014-02-11 | 19873 | 19873 |
| 2014-02-12 | 19875 | 19873 |
| 2014-02-13 | 19870 | 19873 |
| 2014-02-13 | 19872 | 19873 |
| 2014-02-14 | 19877 | 19869 |
| 2014-02-14 | 19873 | 19873 |
期望的输出......
-----------------------------------------------------------------------
| Date | <= -3 | -2 | -1 | 0 | +1 | +2 | >= +3 |
-----------------------------------------------------------------------
| 2014-02-11 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
| 2014-02-12 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
| 2014-02-13 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
| 2014-02-14 | 1 | 0 | 0 | 1 | 9 | 0 | 0 |
答案 0 :(得分:2)
试试这个:
select Date,
sum(case when diff <= -3 then 1 else 0 ) AS [<=-3],
sum(case when diff = -2 then 1 else 0 ) AS [-2],
sum(case when diff = -1 then 1 else 0 ) AS [-1],
sum(case when diff = 0 then 1 else 0 ) AS [0],
sum(case when diff = 1 then 1 else 0 ) AS [+1],
sum(case when diff = 2 then 1 else 0 ) AS [+2],
sum(case when diff >= 3 then 1 else 0 ) AS [>=+3]
from
(select Date, Num1, Num2, (Num1-Num2) diff from TableA)TableB
group by Date