假設我有這個查詢:
select count(*), extract(month from my_table_date), extract(year from my_table_date)
from my_table
group by extract(year from my_table_date), extract(month from my_table_date)
order by extract(year from my_table_date), extract(month from my_table_date);
我有這樣的結果:
75 11 2020
56 12 2020
91 1 2021
102 2 2021
我想在同一個查詢中添加所有 count(*)(第 1 列)值。那可能嗎 ?
謝謝你
uj5u.com熱心網友回復:
使用ROLLUP:
SELECT count(*),
extract(month from my_table_date) AS month,
extract(year from my_table_date) as year
FROM my_table
GROUP BY
ROLLUP(
extract(year from my_table_date),
extract(month from my_table_date)
)
HAVING GROUPING_ID(
extract(year from my_table_date),
extract(month from my_table_date)
) IN (0,3)
ORDER BY
year, month;
其中,對于樣本資料:
CREATE TABLE my_table (my_table_date) AS
SELECT DATE '2020-11-01' FROM DUAL CONNECT BY LEVEL <= 75 UNION ALL
SELECT DATE '2020-12-01' FROM DUAL CONNECT BY LEVEL <= 56 UNION ALL
SELECT DATE '2021-01-01' FROM DUAL CONNECT BY LEVEL <= 91 UNION ALL
SELECT DATE '2021-02-01' FROM DUAL CONNECT BY LEVEL <= 102;
輸出:
數數(*) 月 年 75 11 2020年 56 12 2020年 91 1 2021年 102 2 2021年 324
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331625.html
