表格列的说明 -
TYPE:VARCHAR
STATUS:VARCHAR
ORDER_DATE:TIMESTAMP WITH TIMEZONE
请查看下表结构和所需输出。
在所需的结果中 -
0TO30DAYS:过去30天的类型计数
30TO60DAYS:之前31到60天的类型计数
60TO90DAYS:61至90天的类型计数
请注意,我使用Oracle DB无法根据不同的日期范围创建三个不同的计数列。请告诉我如何在ORACLE中为此创建SQL。
答案 0 :(得分:1)
count
会忽略null
,因此您可以使用您的逻辑count
case
表达式:
SELECT type,
COUNT(CASE WHEN day_diff BETWEEN 0 AND 31 THEN 1 ELSE NULL END)
AS "0TO30DAYS",
COUNT(CASE WHEN day_diff BETWEEN 31 AND 61 THEN 1 ELSE NULL END)
AS "30TO60DAYS",
COUNT(CASE WHEN day_diff BETWEEN 61 AND 91 THEN 1 ELSE NULL END)
AS "60TO90DAYS"
FROM (SELECT type, CAST (order_date AS DATE) - SYSDATE AS day_diff
FROM my_table)
GROUP BY type
答案 1 :(得分:0)
SELECT TYPE,
CASE
WHEN order_date >= (SYSDATE - 30) AND order_date < SYSDATE THEN
COUNT(TYPE)
END AS count30,
CASE
WHEN order_date >= (SYSDATE - 60) AND order_date < (SYSDATE - 30) THEN
COUNT(TYPE)
END AS count60,
CASE
WHEN order_date >= (SYSDATE - 90) AND order_date < (SYSDATE - 60) THEN
COUNT(TYPE)
END AS count90
FROM TABLE
GROUP BY TYPE, order_date