I have a database where I store fishing licenses. The licenses have from- and to-dates, and I'm using a calendar table to count the amount of sold licenses for each day. Each license has a defined licensetype. The licensetype can be valid for one or more fishing zones.
I'm trying to build a query which shows some columns from the zones table and how many licenses have been sold grouped by day and fishing zone, and filtered by licensetype. I've made it work for the days where licenses have been sold. However, the days where no licenses have been sold yet show only null values.
I've been twisting my head around this for 8 hours now. I'm sure there's an easy solution, I just can't see it. SQL Fiddle here.
I think the schema is quite self-explanatory, so I won't include it here. Please see the fiddle if needed.
SET @licensetype = 1,
@fromdate = '2019-01-01',
@todate = '2019-01-10';
SELECT zoneID,
dy,
seasonmax,
daymax,
COUNT(lID) AS sold
FROM
( SELECT z.zoneID,
z.seasonmax,
z.daymax,
l.ID AS lID,
l.From,
l.To,
lt.ValidForZone
FROM zones z
LEFT JOIN licensetypes lt ON z.zoneID IN(lt.ValidForZone)
LEFT JOIN licenses l ON lt.ID = l.TypeID
WHERE FIND_IN_SET( z.zoneID,
( SELECT lt2.ValidForZone
FROM licensetypes lt2
WHERE lt2.ID = @licensetype ) ) ) derived
RIGHT JOIN calendar ON calendar.dy >= DATE_FORMAT(derived.From, '%Y-%m-%d')
AND calendar.dy < DATE_FORMAT(derived.To, '%Y-%m-%d')
WHERE calendar.dy >= @fromdate
AND calendar.dy <= @todate
GROUP BY dy,
zoneID
ORDER BY dy