有没有办法按月显示记录?

Is there way to display record month by month?

所以..我正在尝试按月显示记录。

例如,

    select X, Y, Z, (X + Y + Z) as total
from (
  select
    (select count(x) from table1 a, table2 b where date between '2020-01-01' and '2020-05-01') as X,
    (select count(y) from table3 a, table4 b where date between '2020-01-01' and '2020-05-01') as Y,
    (select count(z) from table5 a, table6 b where date between '2020-01-01' and '2020-05-01') as Z
  from dual
);

这将显示这些日期范围之间的 x 计数,但如果我将其显示为 2 列,例如第一列显示月份,第二列显示 X 并逐月显示。所以结果会像下面这样。这在 sql 中可行吗?

Month    ||     X      ||     Y     ||     Z     ||   Total
January  ||    125     ||    133    ||    155    ||    413
February ||    150     ||    123    ||    129    ||    402
March    ||    170     ||    177    ||    155    ||    502
....
....

你只需要按月分组

Select count(X), TO_CHAR(PDATE , 'MONTH') AS Month_name

From TableA

Where PDATE between '2020-01-01' to '2020-01-31'
group by TO_CHAR(PDATE , 'MONTH')

如果您希望能够按月份按时间顺序排序,并假设 pdate 是实际的日期数据类型,则需要将其以数字格式包含在您的排序方式中。所以像这样:

   select to_char(pdate,'Month') month, 
          count(*)
     from TableA
    where pdate between to_date('2019-01-01','YYYY-MM-DD') 
                    and to_date('2020-08-31','YYYY-MM-DD')
 group by to_char(pdate,'Month')
 order by to_char(pdate,'MM');
Select
To_char(trunc(pdate, 'mm' ), 'month' ), count(X)
From TableA
Group by trunc(pdate, 'mm' ) 
Order by trunc(pdate, 'mm' )

将您的日期转换为所需的显示格式,'Month',但按日期排序

我假设您不关心您的记录关联的年份,因此我将日期转换为与记录月份关联的字符串。

接下来,我按记录的月份进行聚合,并通过将记录的月份转换回日期来执行排序,如下所示:

--sample data---------------       
WITH smple ( record_month ) AS (
    SELECT
        to_char(last_ddl_time, 'Month') record_month
    FROM
        all_objects
)
--end sample data-----------  
SELECT
    record_month,
    COUNT(1)
FROM
    smple
GROUP BY
    record_month
ORDER BY
    to_date(record_month || '-01-2020', 'MONTH-DD-YYYY') ASC;