从sysdate开始,获取前12个月的数据计数

时间:2016-10-19 08:19:24

标签: sql oracle datetime pivot

我有这样的场景:我有桌子有日期field.like

id | date     |name |
1  |1/12/2012 |new  |
1  |1/12/2012 |renew  |
1  |1/09/2012 |new  |
1  |1/12/2012 |renew  |

我需要像|

一样计算
  name |Jan-12| Feb-12 | Mar-12| ....... |Dec-12|
   |new  |0     | 0      | ............... |1     |
   |renew|0     | 0      | ............... |2     |

如果我今天给出了每月最后12个月需要显示条件数的日期。如果我今天输入日期是动态的日期输出将显示在sysdate之前的12个月

请给我一些解决方案。

3 个答案:

答案 0 :(得分:2)

您将获得显示为行的结果(每个月一行)而不是列。

Select to_char(YOUR_DATE, 'YYYY-MM'), count(id)
FROM table_name a
WHERE YOUR_DATE BETWEEN ADD_MONTHS(SYSDATE, -12) AND SYSDATE
GRoup by to_char(YOUR_DATE, 'YYYY-MM')
order by 1;

如下所示: -

2015-10 79
2015-11 223
2015-12 193
2016-01 182

使用PIVOT: -

Select * FROM
(Select to_char(YOUR_DATE, 'YYYY-MM') AS "TDATE"
FROM table_name a
WHERE YOUR_DATE BETWEEN ADD_MONTHS(SYSDATE, -12) AND SYSDATE) 
PIVOT ( count (TDATE) for (TDATE) IN ('2015-10', '2015-11', '2015-12', '2016-01', '2016-02',
'2016-03','2016-04','2016-05','2016-06''2016-07','2016-08','2016-09', '2016-10'));  

请注意,IN子句是强制性的,它必须存在于列标题中。

答案 1 :(得分:0)

在日期添加条件为" dateadd(mm,-12,@ YourDate)和@ YourDate&#34之间的日期;

答案 2 :(得分:0)

You need to use PIVOT operator. PIVOT运算符将数据分成不同的行,汇总并根据需要将其转换为列。

以下是可用于将数据从行转移到列的查询。

with test_tbl AS
(
select 1 id,  '01/12/2012' i_date, 'new' name from dual
union all
select 1 id,  '01/12/2012' i_date, 'renew' name from dual
union all
select 1 id,  '01/09/2012' i_date, 'new' name from dual
union all
select 1 id,  '01/12/2012' i_date, 'renew' name from dual
)
select * from 
(select name, count(id) as count_id, extract(MONTH FROM to_date(i_date,'DD-MM-YYYY') ) as MONTH  from test_tbl group by name, extract(MONTH FROM to_date(i_date,'DD-MM-YYYY')))
PIVOT ( count(count_id) count_id FOR  MONTH IN (9,12) );

-----结果---------------------------

NAME  9_COUNT_ID 12_COUNT_ID
----- ---------- -----------
renew          0           1 
new            1           1