首页 > 解决方案 > 有没有办法逐月显示记录?

问题描述

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

例如,

    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
....
....

标签: sqloracleoracle-sqldeveloper

解决方案


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

   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');

推荐阅读