Sql 如何将此查询从周一第一个排序到周五最后一个?

Sql 如何将此查询从周一第一个排序到周五最后一个?,sql,oracle,oracle-apex,Sql,Oracle,Oracle Apex,我想订购此查询并获取本周每天的票款金额,结果如下: WEEK_DAY CREATED_TICKETS MONDAY 3 TUESDAY 5 WEDNESDAY 0 FRIDAY 2 我建议: select to_char(created_at, 'day') as week_day, count(*) as created_tickets from freshdesk_api where created_at >= trunc(

我想订购此查询并获取本周每天的票款金额,结果如下:

WEEK_DAY      CREATED_TICKETS
MONDAY        3
TUESDAY       5
WEDNESDAY     0
FRIDAY        2

我建议:

select to_char(created_at, 'day') as week_day, count(*) as created_tickets
from freshdesk_api
where created_at >= trunc(sysdate, 'iw') and created_at < trunc(sysdate, 'iw') + 7
group by to_char(created_at, 'day')
order by min(created_at)
选择将字符(在“天”创建)作为星期,将(*)作为创建的票据计数
来自freshdesk_api
其中在>=trunc(sysdate,'iw')处创建,在
诀窍是在
orderby
子句中使用一个聚合函数,该函数应用于
date

对查询的其他更改:

  • 我优化了
    where
    子句,因此在被过滤的列上没有应用日期函数;这更有效(有人说谓词是可搜索的)

  • 可能称为
    id
    的东西不可为空,因此
    count(*)
    等同于
    count(id)
    (更有效,因为数据库不需要
    null
    -检查每个值)

  • 无需将
    trunc()
    嵌套到_char()
    to_char()
    在这里就足够了,因为您只关心白天的部分

select to_char(created_at, 'day') as week_day, count(*) as created_tickets
from freshdesk_api
where created_at >= trunc(sysdate, 'iw') and created_at < trunc(sysdate, 'iw') + 7
group by to_char(created_at, 'day')
order by min(created_at)