I have a table called Stores which has a key called store_id and a table called Sales which contains a store_id reference and a json field called sales_json.
sales_json looks something like this:
[{'start_date': '2-20-15', 'end_date': '2-21-15', 'start_time': '11:00 AM',
'end_time': '11:00 PM', 'discount_percentage': 20}, etc]
I have a plpgsql function in which I'm trying to determine if a store is currently having a sale and store a boolean called having_sale in the result table depending on whether this is true or not.
My SELECT statement looks like this:
SELECT Stores.store_id,
CASE WHEN (SELECT COUNT(*)
FROM (SELECT *
FROM json_array_elements(sales_json) AS sale
WHERE (now()::date BETWEEN (sale->>'start_date')::date AND
(sale->>'end_date')::date) AND
(now()::time BETWEEN (sale->>'start_time')::time AND
(sale->>'end_time')::time)
) AS current_sales) > 0
THEN TRUE
ELSE FALSE
END) AS having_sale
FROM Stores INNER JOIN Sales
ON Stores.store_id = Sales.store_id;
The code looks correct to me but I get the following error:
psycopg2.DataError: cannot extract field from a non-object
What am I doing wrong and how do I fix it?
sales_jsonvalue from above, and it does not contain any null values.