I have this query that works fine apart from one scenario:
SELECT d.year,
d.month,
specieskey,
d.sourcecreated,
d.locationtype,
d.statslocation,
d.clubplacekey,
(SUM(IFMISSINGORNULL(d.hoursfished,0))*60 + SUM(IFMISSINGORNULL(d.minutesfished,0))) minutesfished,
COUNT(*) count,
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 targetspecies AS specieskey
WHERE d.type='FishingTrip'
AND ((d.locationlevel2='91'
AND d.locationtype='1')
OR (d.locationlevel4='91'
AND d.locationtype='2'))
AND d.statspublic
AND specieskey IS VALUED
AND d.locationtype IS VALUED
AND d.statslocation IS VALUED
AND d.year IS VALUED
AND d.month IS VALUED
GROUP BY d.year,
d.month,
specieskey,
d.sourcecreated,
d.locationtype,
d.statslocation,
d.clubplacekey
ORDER BY d.year DESC,
d.month
If d.sourcecreated
does not exist (on some old documents) then I would like to calculate the value. So if d.userkey
has a value then I want to return β1β for d.sourcecreated
else β4β.
β¦ and actually, if d.userkey
exists I would like to add another condition (length of d.key
) to determine the right value
I have tried to change it to:
SELECT d.year,
d.month,
specieskey,
IFMISSINGORNULL(d.sourcecreated,(CASE WHEN d.userkey IS NOT VALUED THEN '4' ELSE (CASE WHEN LENGTH(`KEY`)=32 THEN '1' ELSE '2' END) END)) source,
d.locationtype,
d.statslocation,
d.clubplacekey,
(SUM(IFMISSINGORNULL(d.hoursfished,0))*60 + SUM(IFMISSINGORNULL(d.minutesfished,0))) minutesfished,
COUNT(*) count,
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 targetspecies AS specieskey
WHERE d.type='FishingTrip'
AND ((d.locationlevel2='91'
AND d.locationtype='1')
OR (d.locationlevel4='91'
AND d.locationtype='2'))
AND d.statspublic
AND specieskey IS VALUED
AND d.locationtype IS VALUED
AND d.statslocation IS VALUED
AND d.year IS VALUED
AND d.month IS VALUED
GROUP BY d.year,
d.month,
specieskey,
source,
d.locationtype,
d.statslocation,
d.clubplacekey
ORDER BY d.year DESC,
d.month
But I get this error:
"code": 3080,
"msg": "Ambiguous reference to field 'source' (near line 28, column 15).",
If I do a query without grouping the result then this line works as expected:
:
IFMISSINGORNULL(d.sourcecreated,(CASE WHEN d.userkey IS NOT VALUED THEN '4' ELSE (CASE WHEN LENGTH(`KEY`)=32 THEN '1' ELSE '2' END) END)) source,
:
How can I get this to work with the grouped query?