我如何根据日期sql进行排序/分组

时间:2015-08-03 08:49:19

标签: sql oracle

什么是对以下查询进行分组或排序的最佳方式,也可以通过任何方式来改进查询。

SELECT TO_CHAR(B.EVENTDATE,'Month YYYY') Month_Year,
       LP_TOOLS.P_GETCODEDESCR_F('SomeOrgId', 'SomeOrgId','MSTS', TRIM(B.OLDSTATUS),'en') OLDSTATUS ,
       LP_TOOLS.P_GETCODEDESCR_F('SomeOrgId', 'SomeOrgId','MSTS', TRIM(B.NEWSTATUS),'en')  NEWSTATUS, 
       COUNT(*) STATUSCOUNT 
       FROM PTCIS_PRODUCTMEMBER A, PTLOY_STATUSCHANGE B 
        WHERE A.ORGID = 'SomeOrgId'
            AND A.PRODUCTID ='SomeOrgId'
            AND A.STATUS  NOT IN (SELECT STATUS 
                                  FROM PTGEN_STATUSVAL 
                                  WHERE INCLUDEGENREPORTS != 'Y' 
                                  AND ORGID=A.ORGID AND PRODUCTID=A.PRODUCTID)
            AND A.MEMBERTYPE IN ('INDV','COPM')
            AND A.ORGID=B.ORGID
            AND A.PRODUCTID=B.PRODUCTID
            AND A.MPACC = B.MPACC
            GROUP BY TO_CHAR(B.EVENTDATE,'Month YYYY'),B.OLDSTATUS,B.NEWSTATUS
            ORDER BY Month_Year DESC,OLDSTATUS,NEWSTATUS

这将给我错误的值示例2014年1月,2014年2月,2015年2月,2014年4月等

1 个答案:

答案 0 :(得分:0)

这很简单 - 在您的order by子句中,您需要将month_year列转换回日期。以下是希望向您解释的内容:

with sample_data as (select sysdate dt, 1 val from dual union all
                     select sysdate - 31.53 dt, 10 val from dual union all
                     select sysdate + 366 dt, 100 val from dual)
select to_char(dt, 'fmMonth yyyy') my,
       sum(val)
from   sample_data
group by to_char(dt, 'fmMonth yyyy')
order by to_date(my, 'fmMonth yyyy');

MY                                 SUM(VAL)
-------------------------------- ----------
July 2015                                10
August 2015                               1
August 2016                             100

或者,因为order by子句可以接受列别名,只需:

fm

N.B。我在我的格式模型中使用了- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { CLLocation * currentLocation = [locations lastObject]; NSString * latitude = [NSString stringWithFormat:@"%.6f", currentLocation.coordinate.latitude]; NSString * longitude = [NSString stringWithFormat:@"%.6f", currentLocation.coordinate.longitude]; } ,因为没有它,你最终会在月份和年份之间留出额外的空格。如果您希望所有年份都在结果中排​​列,则可能不需要使用它。