我根据要求编写了以下查询
SQL> SELECT mon."months",
2 COUNT (DECODE (e1.ename, 'RAVI', 1, DECODE (e1.ename, 'KIRAN', 1, NULL))
3 ) AS "num-review"
4 FROM (SELECT TO_CHAR (ADD_MONTHS (SYSDATE, LEVEL - 7),
5 'MON-YYYY'
6 ) "months"
7 FROM DUAL
8 CONNECT BY LEVEL <= 18
9 ORDER BY LEVEL) mon, (select ename, hiredate, to_char(hiredate,'MON-YYYY') "Month" from emp_copy) e1
10 WHERE mon."months"=e1."Month"(+)
11 GROUP BY "months";
months num-review
-------- ----------
APR-2013 0
AUG-2013 0
DEC-2012 1
DEC-2013 0
FEB-2013 2
FEB-2014 0
JAN-2013 1
JAN-2014 0
JUL-2013 0
JUN-2013 0
MAR-2013 0
months num-review
-------- ----------
MAY-2013 0
NOV-2012 0
NOV-2013 0
OCT-2012 1
OCT-2013 0
SEP-2012 1
SEP-2013 0
18 rows selected.
这里我必须得到像
这样的输出Sep-2012
Oct-2012
Nov-2012
Dec-2012
Jan-2013
Feb-2013
Mar-2013
Apr-2013
May-2013
Jun-2013
Jul-2013
Aug-2013
Sep-2013
Oct-2013
Nov-2013
Dec-2013
Jan-2014
Feb-2014
但我以不同的方式获得输出。任何人都可以帮我解决问题。
答案 0 :(得分:1)
因为你在日期上使用to_char
来获得“月”,所以按顺序排序只会按字母顺序给你几个月(正如你所看到的)。您需要为自己提供另一个按时间顺序排序的字段,您可以使用“YYYYMM”进行排序,例如并按此顺序。这是一个基于您的查询的示例(简化为删除您的特定表)。这有帮助吗?
select "months", count(*) "num", "sort_months" from
(
SELECT TO_CHAR (ADD_MONTHS (SYSDATE, LEVEL - 7), 'MON-YYYY') "months",
TO_CHAR (ADD_MONTHS (SYSDATE, LEVEL - 7), 'YYYYMM') "sort_months"
FROM DUAL
CONNECT BY LEVEL <= 18
ORDER BY LEVEL
)
group by "months", "sort_months"
order by "sort_months";
答案 1 :(得分:1)
如果您根据MON-YYYY
对日期进行排序,则会从APR,AUG..
开始给出o / p
因为MON-YYYY
会像APR-2013
那样,它会按字母顺序对数据进行排序,
因此,您还需要提取月份的numeric
值,即MM-YYYY
以及“MON-YYYY and sort with
MM-YYYYY”,然后结果将是您的预期结果,即排序方式的日期。
SELECT mon."months",COUNT (DECODE (e1.ename, 'RAVI', 1, DECODE (e1.ename, 'KIRAN', 1, NULL))) AS "num-review"
FROM (SELECT TO_CHAR(ADD_MONTHS(SYSDATE, LEVEL - 7),'MON-YYYY') "months",TO_CHAR(ADD_MONTHS(SYSDATE, LEVEL - 7),'MM-YYYY') "months_num"
FROM DUAL CONNECT BY LEVEL <= 18 ORDER BY LEVEL) mon,
(select ename, hiredate, to_char(hiredate,'MON-YYYY') "Month" from emp_copy) e1
WHERE mon."months"=e1."Month"(+)
GROUP BY "months" order by "months_num";