在这里我需要动态地执行group by子句,在这里如何实现大小写切换
"newProjectRoot": "dashboards",
答案 0 :(得分:0)
您需要使SELECT
子句中的所有表达式成为聚合函数或GROUP BY
子句:
DECLARE
p_cursor SYS_REFCURSOR;
p_start_units VARCHAR2(10) := 'YEAR';
p_year NUMBER := 2019;
p_month NUMBER := 2;
p_out_month VARCHAR2(10);
p_out_count NUMBER;
BEGIN
OPEN p_cursor FOR
SELECT COUNT(*) noofrecords,
TO_CHAR(
CASE p_start_units
WHEN 'YEAR' THEN TRUNC( start_date, 'MM' )
END,
'month'
) AS value
FROM tab_name
WHERE EXTRACT(YEAR FROM start_date) = p_year
AND CASE 'MONTH'
WHEN 'MONTH' THEN EXTRACT(MONTH FROM start_date)
END = p_month
GROUP BY
CASE p_start_units
WHEN 'YEAR' THEN TRUNC( start_date, 'MM' )
END
ORDER BY
CASE p_start_units
WHEN 'YEAR' THEN TRUNC( start_date, 'MM' )
END;
LOOP
FETCH p_cursor INTO p_out_count, p_out_month;
EXIT WHEN p_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( p_out_month || ': ' || p_out_count );
END LOOP;
END;
/
测试数据:
CREATE TABLE tab_name ( start_date ) AS
SELECT DATE '2019-01-01' FROM DUAL UNION ALL
SELECT DATE '2019-01-01' FROM DUAL UNION ALL
SELECT DATE '2019-02-01' FROM DUAL UNION ALL
SELECT DATE '2019-02-01' FROM DUAL UNION ALL
SELECT DATE '2019-02-01' FROM DUAL UNION ALL
SELECT DATE '2019-03-01' FROM DUAL;
输出:
february : 3
db <>提琴here
答案 1 :(得分:0)
我建议您使用子查询根据变量定义列,然后使用它们进行汇总和排序。
类似这样的东西:
SELECT COUNT(*) as noofrecords, order_by, value
FROM (SELECT t.*,
TO_CHAR(TO_DATE(EXTRACT(MONTH FROM start_date), 'MM'), 'month') as value
EXTRACT(MONTH FROM start_date) as order_by
(CASE 'YEAR' ----- getting this value from a variable
WHEN 'YEAR' THEN EXTRACT(MONTH FROM start_date)
END) as grouping_var
END
(CASE 'MONTH' ----- getting this value from a variable
WHEN 'MONTH' THEN EXTRACT(MONTH FROM start_date)
END) as filter_criteria
FROM tab_name
WHERE EXTRACT(YEAR FROM start_date) = 2019
) t
WHERE filter_column = 2 ----- setting this value from a
GROUP BY grouping_var, order_by, value
ORDER BY order_by;
该查询完全没有意义。但是我怀疑当您将其应用于实际问题时,您会看到这种方法的帮助。