简体   繁体   中英

ANSI SQL grouping by (Indian) financial year YTD - (last 5 years YTD)

Can anyone kindly point out how to group data until today (for last 5 years) for Indian fiscal (Apr-Mar). Say for example I need to extract 'field1','field2' from table 'aaa' from 01-Apr to today date for the last 5 years. My current solution can work safe until Dec, but later will run into error

SELECT
         "Date",
         "Daily data",
         "ID",
         "GA%",
         "MA%"
FROM  "table" 
WHERE    month("Date")  >= 4
 AND    month("Date")  <= month(today())
 AND    date("Date")  < date(today())
Expected result format grouped by fiscal years:
FY-1 sum(daily data during the period) sum(GA) sum(MA)
FY-2 sum(daily data during the period) sum(GA) sum(MA)
SELECT
         "Date",
         "Daily data",
         "ID",
         "GA%",
         "MA%"
FROM  "table" 
WHERE    
"Date" between '2021-04-01' and '2021-11-29'
OR
"Date" between '2020-04-01' and '2020-11-29'
OR
"Date" between '2019-04-01' and '2019-11-29'
OR
"Date" between '2018-04-01' and '2018-11-29'
OR
"Date" between '2017-04-01' and '2017-11-29'
SELECT
  MIN("Date") AS StartDate
, MAX("Date") AS EndDate
, MAX("Daily data") AS MaxDaily
, COUNT("ID") AS CountId
, SUM("GA%") AS "TotalGa%"
, SUM("MA%") AS "TotalMa%"
FROM  "tableAAA" 
WHERE 
(
  EXTRACT(YEAR FROM "Date") BETWEEN EXTRACT(YEAR FROM CURRENT_DATE) - 5 AND EXTRACT(YEAR FROM CURRENT_DATE) - 1
  OR 
  (EXTRACT(YEAR FROM "Date") = EXTRACT(YEAR FROM CURRENT_DATE) AND EXTRACT(MONTH FROM "Date") <= 3)
)
GROUP BY 
    CASE 
    WHEN EXTRACT(MONTH FROM "Date") <= 3
    THEN EXTRACT(YEAR FROM "Date") - 1
    ELSE EXTRACT(YEAR FROM "Date")
    END
ORDER BY MIN("Date") DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM