sql - 从一张表中计算多个时间戳的总计
问题描述
我有一个表,它有大约 5000 条记录,有 4 种类型的订单在多个时间戳,我一直在尝试计算多个时间戳的订单数,比如 00 到 04hrs,04hrs 到 24hrs。我只能获得 1 个时间戳中的任何一个的结果。感谢您的帮助:)
SELECT
DECODE(order_type,1,'Multi Sim',2,'Single Sim',3,'Sim Replacement',7,'Data SIM with Router') AS order_type,
COUNT(order_type) AS total0hrs_4hrs,
COUNT(order_type) AS total4hrs_24hrs,
COUNT(order_type) AS grand_total
FROM
sids
WHERE
order_time >= to_timestamp('2020-09-01 00:00:00.0000','YYYY-MM-DD HH24:MI:SS.FF4')
AND order_time <= to_timestamp('2020-09-01 03:59:59.9999','YYYY-MM-DD HH24:MI:SS.FF4')
AND order_type IN (
1,
2,
3,
7
)
GROUP BY
order_type
HAVING
COUNT(order_type) > 0
ORDER BY
1;
解决方案
CASE
在聚合函数中使用表达式:
SELECT DECODE(
order_type,
1, 'Multi Sim',
2, 'Single Sim',
3, 'Sim Replacement',
7, 'Data SIM with Router'
) AS order_type,
COUNT(
CASE
WHEN order_time - TRUNC( order_time ) < INTERVAL '4' HOUR
THEN 1
ELSE NULL
END
) AS total0hrs_4hrs,
COUNT(
CASE
WHEN order_time - TRUNC( order_time ) < INTERVAL '4' HOUR
THEN NULL
ELSE 1
END
) AS total4hrs_24hrs,
COUNT(order_type) AS grand_total
FROM sids
WHERE order_time >= TIMESTAMP '2020-09-01 00:00:00.0000'
AND order_time < TIMESTAMP '2020-09-02 00:00:00.0000'
AND order_type IN ( 1, 2, 3, 7 )
GROUP BY
order_type
ORDER BY
1;
推荐阅读
- argparse - 你如何为 python 模块的 argparse 编写 unittest?
- python - Gradient Boosting 分类器 - scikit 中训练数据的准确性
- django - 如何在 Django 中使用相同的 url
- java - 使用循环接受额外的用户输入,直到用户输入一个结束输入的值
- docker - 在 Laradock 中 Ghostscript 版本没有变化
- ruby - 安装 ruby-2.0.0 时出错
- webpack - webpack 中的 main.js 路径自动注入错误
- android - 使用分屏创建 Android 视频流应用
- javascript - Mailchimp API /列出merge_fields的日期类型参数格式
- processing - 你能在处理中制作柔和的调色板吗