I am creating a Stacked Chart from a database. There are 12 months of data, and 3 items in the series: A AA and AAA. For the Stacked Chart to populate correctly, it needs to find a value for each of the three series, for each of all 12 months.
Problem with the database I am querying is, each series is not found in each month. Essentially, when a series value is 0, it is simply not recorded in the database.
I need to know how to return a value of 0 when A, AA, or AAA DOES NOT EXIST for Month 1, Month 2, Month 3, etc. Therefore, the query results for the 3 series and 12 months, will return 36 Total values.
Thank you, ERIK
IMPORTANT: I AM POSTING BELOW QUERY FOR REFERENCE ONLY, I AM NOT ASKING YOU TO COMPLETELY EDIT MY QUERY. IF I CAN GET INPUT ON THE CORRECT FUNCTION/CODE, I CAN APPLY IT.
CURRENT QUERY
select E.DES_CARTERA_CC Fund_Name,
DATE_FORMAT(D.F_ULT_CIERRE_MENSUAL, "%d/%m/%Y") Date_as_of,
DATE_FORMAT(A.F_CORTE, "%Y/%m") Date_of_distribution_SORT,
DATE_FORMAT(A.F_CORTE, "%m/%Y") Date_of_distribution,
C.DES_CALIFICACION Item_description,
ROUND(SUM(A.POR_CALIFICACION), 2) Percentage_of_distribution
from det_calificaciones A
Join mcalificaciones C on ( A.ID_CALIFICACION = C.ID_CALIFICACION )
Join mcarteras E on ( A.ID_CARTERA = E.ID_CARTERA )
Join mpaises D on ( E.COD_PAIS = D.COD_PAIS )
where A.ID_CARTERA = @ID_CARTERA
AND A.F_CORTE BETWEEN DATE_ADD(D.F_ULT_CIERRE_MENSUAL, INTERVAL -11 MONTH) AND D.F_ULT_CIERRE_MENSUAL
GROUP BY A.F_CORTE, C.DES_CALIFICACION
ORDER BY Date_of_distribution_SORT ASC
Typically, you do this by CROSS JOINing the two axis of your graph, which means
select x.Col1, y.DateCol, ... other columns ...
from (select distinct Col1 from tbl1) x
cross join (select distinct DateCol from tbl2) y
LEFT JOIN (... original query...) z ON z.col1 = x.col1 and z.datecol = y.datecol
The first two sets produce all the rows you need, and the original results are grafted on.
It's easier to have a dates
table of some sort to get the months from, or if tbl2 will have the dates, just taking the distinct dates from it could work.
Putting the entire original query into the LEFT JOIN is a naive approach, you can easily LEFT JOIN into all the involved tables in one flat query.
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.