oracle TO_CHAR(v_date,'MON-YYYY')NEW_DATE,我已经使用了指定的格式,但我不想ORDER BY MON BT,因为它转换为字符串,我不能这样做

4xrmg8kj  于 2023-04-20  发布在  Oracle
关注(0)|答案(1)|浏览(137)
SELECT br_code,TO_CHAR(v_date,'MON-YYYY') NEW_DATE,min(bill_amt) new_bill 
from pos_hdr 
GROUP BY br_code,v_date
UNION
SELECT br_code,TO_CHAR(v_date,'MON-YYYY') NEW_DATE,min(bill_amt) AS new_bill 
from pos_prv_hdr 
GROUP BY br_code,v_date 
ORDER BY NEW_DATE;

我想得到按月份排序的数据,但是由于它已经转换为字符串,它以字符串格式排序,如何使用月份按它排序,使用相同的选择查询?
我尝试了很多方法,但在oracle中没有任何帮助。

o0lyfsai

o0lyfsai1#

假设你想按br_code和月份对行进行分组,然后将日期截短到月份的开始并按其分组,然后将其格式化为字符串并在外部查询中按截短的日期排序:

SELECT br_code,
       TO_CHAR(month,'MON-YYYY') AS new_date,
       new_bill
FROM   (
  SELECT br_code,
         TRUNC(v_date, 'MM') AS month,
         min(bill_amt) AS new_bill
  from   pos_hdr
  GROUP BY
         br_code,
         TRUNC(v_date, 'MM')
UNION
  SELECT br_code,
         TRUNC(v_date, 'MM'),
         min(bill_amt)
  from   pos_prv_hdr
  GROUP BY 
         br_code,
         TRUNC(v_date, 'MM')
)
ORDER BY
       month;

或者,根据您是否希望将两个表聚合在一起(而不是将它们分开并使用UNION丢弃重复项),然后:

SELECT br_code,
       TO_CHAR(month,'MON-YYYY') AS new_date,
       MIN(bill_amt) AS new_bill
FROM   (
  SELECT br_code,
         TRUNC(v_date, 'MM') AS month,
         bill_amt
  from   pos_hdr
UNION ALL
  SELECT br_code,
         TRUNC(v_date, 'MM') AS month,
         bill_amt
  from   pos_prv_hdr
)  
GROUP BY
       br_code,
       month
ORDER BY
       month;

fiddle

相关问题