This is my package table
+----+--------------+---------------+
| id | order_number | purchase_date |
+----+--------------+---------------+
| 1 | P1 | 11-22-2019 |
| 2 | P2 | 11-21-2019 |
| 3 | P3 | 11-20-2019 |
| 4 | P4 | 11-17-2019 |
| 5 | P5 | 11-21-2019 |
+----+--------------+---------------+
which is connected to the tags table through the object_tags table where the object_id is the package.id
object_tags tags
+----+-----------+--------+ +----+---------+
| id | object_id | tag_id | | id | name |
+----+-----------+--------+ +----+---------+
| 1 | 2 | 1 | | 1 | special |
| 2 | 3 | 1 | | 2 | normal |
+----+-----------+--------+ +----+---------+
A package can be considered as a special package if the package has a tag special or if the purchase_date exceeded 3 or more days from today. This is what the output should be:
+------------+--------------+--------+
| package_id | order_number | is_vip |
+------------+--------------+--------+
| 1 | P1 | 0 |
| 2 | P2 | -1 |
| 3 | P3 | -1 |
| 4 | P4 | -1 |
| 5 | P5 | 0 |
+------------+--------------+--------+
Now this is what I have tried:
SELECT packages.id as package_id,
packages.order_number as order_number,
(CASE
WHEN EXISTS(SELECT p.id as id
FROM packages p
INNER JOIN object_tags ot on ot.object_id = p.id
INNER JOIN tags t on t.id = ot.tag_id
WHERE tag.name = 'special'
)vip on packages.id = vip.id THEN -1 /*(PG::SyntaxError: ERROR: syntax error at or near "vip"*/
WHEN p.purchased_at NOT BETWEEN NOW() AND NOW() - interval '3 days' then -1
ELSE 0 END) as is_vip
FROM packages p
I am not quite sure about the CASE - EXISTS part of this. Any help would be appreciated.
p.id as id,that shouldn't be there...0and-1as the values of theis_vipcolumn? If not, a boolean would make more sense.vip on packages.id = vip.idhas no place in the query. Not sure what you're trying to achieve with it?