I have this simplified query that I try to get to work (the original query does some grouping etc. on more fields):
SELECT d.year,
d.month,
d.targetspecies,
sourcecreated,
IFMISSINGORNULL(d.hoursfished,0)*60 + IFMISSINGORNULL(d.minutesfished,0) minutesfished,
IFMISSINGORNULL(ARRAY_LENGTH(d.catchkeys),0) catchcount,
CASE WHEN ARRAY_LENGTH(d.catchkeys) = 0 THEN 1 ELSE 0 END zerotrips
FROM data d
UNNEST d.targetspecies specieskey
LET sourcecreated = IFMISSINGORNULL(d.sourcecreated,(CASE WHEN d.userkey IS NOT VALUED THEN '4' ELSE (CASE WHEN UPPER(d.`key`)=d.`key` THEN '1' ELSE '2' END) END))
WHERE d.type='FishingTrip'
AND d.assockey='1'
AND d.statspublic
AND d.year IS VALUED
AND d.month IS VALUED
ORDER BY d.year DESC,
d.month,
specieskey,
sourcecreated
LIMIT 1000
Basically, for some of the documents I have an empty d.targetspecies
. If I use the “UNNEST” then all of the documents with the empty field are not included in the query result (even if I don’t show the unnested values as above).
If there is an empty d.targetspecies
then what I want is really to check all of the keys in d.catchkeys
(0-n) and do a lookup to find the value of species
in each of those and return the unique array of these values as d.targetspecies
. The key for the direct lookup can be built like Catch:<key>
.
Edit:
What I am trying to obtain is something like:
SELECT d.year,
d.month,
specieskey,
sourcecreated,
SUM(IFMISSINGORNULL(d.hoursfished,0)*60) + SUM(IFMISSINGORNULL(d.minutesfished,0)) minutesfished,
SUM(IFMISSINGORNULL(ARRAY_LENGTH(d.catchkeys),0)) catchcount,
SUM(CASE WHEN ARRAY_LENGTH(d.catchkeys) = 0 THEN 1 ELSE 0 END) zerotrips
FROM data d
UNNEST d.targetspecies specieskey
LET sourcecreated = IFMISSINGORNULL(d.sourcecreated,(CASE WHEN d.userkey IS NOT VALUED THEN '4' ELSE (CASE WHEN UPPER(d.`key`)=d.`key` THEN '1' ELSE '2' END) END))
WHERE d.type='FishingTrip'
AND d.assockey='1'
AND d.statspublic
AND d.year IS VALUED
AND d.month IS VALUED
GROUP BY d.year,
d.month,
specieskey,
sourcecreated
ORDER BY d.year DESC,
d.month,
specieskey,
sourcecreated
I have moved out on too deep water for my query knowledge - but can someone perhaps point me in the right direction to solve it - if this can be done?
/John