我的桌子:
Year Month Value1 Value2
2020 1 100 100
2020 2 100 100
2020 3 100 100
2020 4 100 100
2020 5 100 100
2020 6 100 100
2020 7 100 100
2020 8 100 100
2020 9 100 100
2020 10 100 100
2020 11 100 100
2020 12 100 100
我的输出应如何显示:
Year Quarter Value1 Value2
2020 Q1 300 300
2020 Q2 300 300
2020 Q3 300 300
2020 Q4 300 300
我尝试了什么:
select year,sum(value1),sum(value2),sum(value3)
from table
where month=1 or month=2 or month=3
group by year;
但是我只有第一季度...如何编写sql查询
预先感谢... !!!
答案 0 :(得分:1)
在此处使用条件聚合。我们可以先在CTE中生成四分之一列,然后按年份和季度进行汇总以获得总和。
WITH cte AS (
SELECT
Year, Value1, Value2,
CASE WHEN Month BETWEEN 1 AND 3 THEN 'Q1'
WHEN Month BETWEEN 4 AND 6 THEN 'Q2'
WHEN Month BETWEEN 7 AND 9 THEN 'Q3'
ELSE 'Q4' END AS Quarter
FROM yourTable
)
SELECT
Year,
Quarter,
SUM(Value1) AS Value1,
SUM(Value2) AS Value2
FROM cte
GROUP BY
Year,
Quarter
ORDER BY
Year,
Quarter;
答案 1 :(得分:0)
您可以通过将月份除以3并四舍五入来计算季度:
SELECT Year,
'Q' || CEIL( month / 3 ) AS Quarter,
SUM( Value1 ) AS Value1,
SUM( Value2 ) AS Value2
FROM table_name
GROUP BY
Year,
CEIL( month / 3 )
ORDER BY
Year,
Quarter;
其中的示例数据:
CREATE TABLE table_name ( Year, Month, Value1, Value2 ) AS
SELECT 2020, 1, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 2, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 3, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 4, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 5, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 6, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 7, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 8, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 9, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 10, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 11, 100, 100 FROM DUAL UNION ALL
SELECT 2020, 12, 100, 100 FROM DUAL;
输出:
YEAR | QUARTER | VALUE1 | VALUE2 ---: | :------ | -----: | -----: 2020 | Q1 | 300 | 300 2020 | Q2 | 300 | 300 2020 | Q3 | 300 | 300 2020 | Q4 | 300 | 300
db <>提琴here