开发者

Combining ORACLE snippets into a conditional statement

开发者 https://www.devze.com 2023-04-03 05:11 出处:网络
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.

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 t开发者_如何学运维his:

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.

SELECT *
FROM
(SELECT 
   CASE 
     WHEN terminal_id LIKE 'AGHUPR9%' THEN card_balance 
     ELSE card_balance+total_points 
   END AS card_balance
FROM ag_tranzakcio
WHERE cardnumber = '9348722610095185'
ORDER BY tran_date DESC)
WHERE ROWNUM = 1

This will use card_balance when the terminal_id starts with "AGHUPR9", otherwise it'll use card_balance+total_points, returning the answer in a column named 'card_balance' in either case.

0

精彩评论

暂无评论...
验证码 换一张
取 消