0

Breakdown of the problem that I'm trying to solve. I need to:

  1. Fetch earliest created_date for every user_id. I know that this can be done with the following query:

    SELECT user_id, MIN(created_date)
    FROM new_schema.transactions
    GROUP BY user_id
    
  2. Integrate the above query into the below query. The below works fine on its own.

    SELECT *, t.amount / POWER(10, cd.exponent) * fx.rate AS usd_equivalent
    FROM new_schema.transactions t
    JOIN new_schema.fx_rates fx ON t.currency = fx.ccy
    JOIN new_schema.currency_details cd ON t.currency = cd.currency
    WHERE fx.base_ccy = "USD" 
        AND t.state = "COMPLETED" 
        AND t.type = "CARD_PAYMENT"
    HAVING usd_equivalent > 10;
    

Basically, in addition to the manipulations I'm performing in my second query I also need to fetch the records with earliest created_date for every user_id after applying the said manipulations. How can I enrich my current query to facilitate this?

asleniovas
  • 193
  • 3
  • 21
  • The specified duplicate was simply not a duplicate of this particular question (at least, the answer is not the best answer for this question). – Gordon Linoff May 19 '21 at 21:06

1 Answers1

0

You can use a window function:

SELECT *, t.amount / POWER(10, cd.exponent) * fx.rate AS usd_equivalent
FROM (SELECT t.*,
              MIN(created_date) OVER (PARTITION BY user_id) as first_created_date
      FROM new_schema.transactions t
     ) t JOIN
     new_schema.fx_rates fx
     ON t.currency = fx.ccy JOIN
     new_schema.currency_details cd
     ON t.currency = cd.currency
WHERE fx.base_ccy = 'USD' AND
      t.state = 'COMPLETED' AND
      t.type = 'CARD_PAYMENT'
HAVING usd_equivalent > 10;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thank you. Please ignore my previous comment. I can see this query returns a `first_created_date` column against all the records, even against multiple records of the same `user_id`. How can I fetch only the records that actually have the `first_created_date` in `created_date`? So it should only be 1 record per user, as we are looking for the earliest `created_date`. – asleniovas May 19 '21 at 21:04
  • 1
    @asleniovas . . . Just add `t.created_date = t.first_created_date` to the `where` clause. – Gordon Linoff May 19 '21 at 21:06