sql - 有没有办法逐月显示记录?
问题描述
所以..我正在尝试逐月显示记录。
例如,
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
....
....
解决方案
如果您希望能够按月份按时间顺序排序,并假设 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');
推荐阅读
- php - 使用 _id 作为值的 PHP 从 MongoDB 中的两个集合中检索数据
- android - CardView角落显示白色像素?
- visual-studio-code - /Users/homedir/.zshrc:export:1:在此上下文中无效:Code.app/Contents/Resources/app/bin
- macos - 如何让 julia.app 在 iTerm 而不是 macOS 的 Terminal.app 中启动?
- python - urwid 如何处理按键层次结构?
- node.js - 在不修改 C 库的情况下构建 nodejs 插件
- sql - 查询:使用多个具有相同名称但来自不同表的列作为 WHERE 子句的条件?
- sql - 一对多查询和 row_number() 和条件聚合?
- servicestack - ServiceStack 消息 API:在 OnAfterInit 中使用 HostContet.AppHost.ExecuteMessage 会产生 NullReferenceException
- python - 关闭根窗口时,Tkinter 消息框失败