我有一个ID,将ID设置为年份和月份。
例如:ID:201706其中“2017”是年份,“06”是月份,月份和年份随着新数据添加到表格而变化。
我想设置一个变量,以便查询中的where子句从当前月份的数据中提取数据。还想比较去年/月的金额。
如何在同一列中编写声明年度(201706)的查询?
答案 0 :(得分:0)
如果您需要从一行检索结果
DECLARE
l_month NUMBER; // declaring variable of type number;
BEGIN
SELECT SUBSTR(column, 5) //will return last 2 digits, which is month
INTO l_month // getting value from select clause
FROM table
WHERE ...;
END;
如果您需要检索多行
DECLARE
TYPE l_month_type IS TABLE OF NUMBER; // collection of type NUMBER
l_month l_month_type; // instance of collection
BEGIN
SELECT SUBSTR(column, 5) //will return last 2 digits, which is month
BULK COLLECT INTO l_month // getting data into collection
FROM table
WHERE ...;
END;
答案 1 :(得分:0)
希望下面的代码段有用。
WITH TEMP_DATA AS
( SELECT '201601' ID,100 QTY FROM DUAL
UNION ALL
SELECT '201601' ID,200 QTY FROM DUAL
UNION ALL
SELECT '201602' ID,101 QTY FROM DUAL
UNION ALL
SELECT '201603' ID,102 QTY FROM DUAL
UNION ALL
SELECT '201604' ID,103 QTY FROM DUAL
UNION ALL
SELECT '201605' ID,104 QTY FROM DUAL
)
SELECT TO_DATE(ID,'YYYYMM'),
COUNT(1)
FROM TEMP_DATA
GROUP BY TO_DATE(ID,'YYYYMM')
ORDER BY TO_DATE(ID,'YYYYMM');
-----------------------Comparing data Reporting Purpose--------------------------------
SELECT *
FROM
(WITH TEMP_DATA AS
( SELECT '201601' ID,100 QTY FROM DUAL
UNION ALL
SELECT '201601' ID,200 QTY FROM DUAL
UNION ALL
SELECT '201602' ID,101 QTY FROM DUAL
UNION ALL
SELECT '201603' ID,102 QTY FROM DUAL
UNION ALL
SELECT '201604' ID,103 QTY FROM DUAL
UNION ALL
SELECT '201605' ID,104 QTY FROM DUAL
)
SELECT ID,QTY FROM TEMP_DATA
) PIVOT (COUNT(QTY) FOR ID IN ('201601','201602','201603','201604','201605') );