1

你能帮我在下面吗?

我根据要求编写了以下查询

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

但我以不同的方式获得输出。谁能帮我解决这个问题。

4

2 回答 2

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";
于 2013-03-31T16:06:33.943 回答
1

如果您根据MON-YYYY它对日期进行排序,则会给出从开始的 o/p,APR,AUG.. 因为它MON-YYYYAPR-2013按字母顺序对数据进行排序,因此您还需要提取numeric月份的值,即MM-YYYY连同 'MON-YYYY and sort withMM-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";
于 2013-04-01T06:23:36.753 回答