We have a loyalty card database at my company. The card system is served by two types of terminals nationwide. The trouble is, the two terminals count the current point balance differently.
I want to make a query that first finds the last row of a single user’s transaction list by date, then checks the ID of the terminal, and based on what the ID is, returns the card balance from the same row.
The two types of terminals can be expressed like this:
terminal_id LIKE 'AGHUPR9%'
terminal_id LIKE 'AGHUPR7%'
The AGHUPR9% ones get the balance simply from a column called card_balance.
The AGHUPR7% ones need to sum the card_balance and the total_points columns to get the current balance.
I wrote the main parts of the query but I’m not familiar enough with ORACLE so I don’t know how to combine them syntactically. This is what I’d appreciate your help with. Below is what I came up with, with comments where I’m not sure about the code needed.
SELECT *
FROM
(SELECT terminal_id
FROM ag_tranzakcio
WHERE cardnumber = '9348722610095185'
ORDER BY tran_date DESC)
WHERE ROWNUM = 1
In case the above statement returns a terminal_id starting with AGHUPR9, do this:
SELECT *
FROM
(SELECT card_balance
FROM ag_tranzakcio
WHERE cardnumber = '9348722610095185'
ORDER BY tran_date DESC)
WHERE ROWNUM = 1
In case the first statement returns a terminal_id starting with AGHUPR7, do this instead:
SELECT *
FROM
(SELECT card_balance+total_points
FROM ag_tranzakcio
WHERE cardnumber = '9348722610095185'
ORDER BY tran_date DESC)
WHERE ROWNUM = 1
How do I combine them into a working query? I’m trying to use CASE with little success.
Thank you in advance.
Simply use a CASE statement.
This will use
card_balancewhen theterminal_idstarts with “AGHUPR9”, otherwise it’ll usecard_balance+total_points, returning the answer in a column named ‘card_balance’ in either case.