oracle 如何编写查询来显示一周中哪一天的约会请求最少?

m3eecexj  于 2023-01-04  发布在  Oracle
关注(0)|答案(3)|浏览(119)

APPOINTMENT表中的数据示例

APP_ID A_DATE_TI     PET_ID      VN_ID
---------- --------- ---------- ----------
         1 20-JAN-23      10001        801
         2 20-JAN-23      10002        803
         3 20-JAN-23      10003        804
         4 20-JAN-23      10004        803
         5 15-JAN-23      10005        801
         6 14-JAN-23      10006        803
         7 13-JAN-23      10007        804
         8 12-JAN-23      10008        803
         9 01-FEB-23      10009        801
        10 02-FEB-23      10010        803
        11 03-FEB-23      10011        804
SELECT 
APP_ID, 
TO_CHAR(A_DATE_TIME, 'DAY MONTH YYYY DD hh:mi') App_Date_Time, 
PET_ID, 
VN_ID
FROM APPOINTMENT
qhhrdooz

qhhrdooz1#

SELECT TO_CHAR(a_date_time,'FMDay') day_of_week
      ,COUNT(*) number_of_appointments
  FROM appointment
 GROUP BY TO_CHAR(a_date_time,'FMDay')
 ORDER BY number_of_appointments ASC
 FETCH FIRST ROW WITH TIES

| 星期几|任命人数|
| - ------|- ------|
| 星期日|1个|
| 星期三|1个|
| 星期六|1个|

yeotifhr

yeotifhr2#

您可以生成一周中所有日期的列表,然后对约会表执行LEFT OUTER JOIN,然后按约会数对行执行ORDER,并在Oracle 12中执行FETCH FIRST ROW WITH TIES以查找最小值:

WITH days_of_week (day) AS (
  SELECT TO_CHAR(TRUNC(SYSDATE, 'IW') + LEVEL - 1, 'DY')
  FROM   DUAL
  CONNECT BY LEVEL <= 7
)
SELECT d.day,
       COUNT(a.app_id) AS num_appointments
FROM   days_of_week d
       LEFT OUTER JOIN appointment a
       ON d.day = TO_CHAR(a.A_DATE_TI, 'DY')
GROUP BY d.day
ORDER BY
       num_appointments ASC
FETCH FIRST ROW WITH TIES;

其中,对于示例数据:

CREATE TABLE appointment (APP_ID, A_DATE_TI, PET_ID, VN_ID) AS
SELECT  1, DATE '2023-01-20', 10001, 801 FROM DUAL UNION ALL
SELECT  2, DATE '2023-01-20', 10002, 803 FROM DUAL UNION ALL
SELECT  3, DATE '2023-01-20', 10003, 804 FROM DUAL UNION ALL
SELECT  4, DATE '2023-01-20', 10004, 803 FROM DUAL UNION ALL
SELECT  5, DATE '2023-01-15', 10005, 801 FROM DUAL UNION ALL
SELECT  6, DATE '2023-01-14', 10006, 803 FROM DUAL UNION ALL
SELECT  7, DATE '2023-01-13', 10007, 804 FROM DUAL UNION ALL
SELECT  8, DATE '2023-01-12', 10008, 803 FROM DUAL UNION ALL
SELECT  9, DATE '2023-02-01', 10009, 801 FROM DUAL UNION ALL
SELECT 10, DATE '2023-02-02', 10010, 803 FROM DUAL UNION ALL
SELECT 11, DATE '2023-02-03', 10011, 804 FROM DUAL;

输出:
| 日|任命人数|
| - ------| - ------|
| 星期二|无|
| 周一|无|
fiddle

u2nhd7ah

u2nhd7ah3#

您可以使用以下命令从日期列中确定星期几

TO_CHAR(date A_DATE_TI, 'DAY')

因此,您可以使用此查询来查找每个工作日发生了多少约会。

SELECT COUNT(*) appointments, 
       TO_CHAR(A_DATE_TI, 'DAY') weekday
  FROM appointment
 GROUP BY TO_CHAR(A_DATE_TI, 'DAY')

这将查找约会最多的一天。

SELECT COUNT(*) appointments, 
       TO_CHAR(A_DATE_TI, 'DAY') weekday
  FROM appointment
 GROUP BY TO_CHAR(A_DATE_TI, 'DAY')
 ORDER BY COUNT(*) DESC
 LIMIT 1

相关问题