i have a CASE statement, which classify my Customer-Revenue and set Flag, when Revenue <> 0 is. But my problem i should search also same month record on my case statement. Logic : if two records (Revenue & Credit) exist on same month and sum of those 2 records are zero then put flag.
my Script :
SELECT CUSTOMER,
CASE WHEN SUM(FLAG) > 0 THEN 'X' ELSE 'Y' END FLAG
FROM (
SELECT CUSTOMER, CALMONTH, SUM(INVCD_VAL),
CASE WHEN INVCD_VAL <> 0 THEN 1 ELSE 0 END AS FLAG
FROM
(
SELECT CALMONTH, CUSTOMER, INVCD_VAL FROM CUSTOMER_HISTORY
UNION ALL
SELECT LEFT(CALDAY, 6), SOLD_TO, REVENUE FROM CUST_HISTORY_MIS
)
GROUP BY CUSTOMER, CALMONTH, INVCD_VAL
)
GROUP BY CUSTOMER
ORDER BY CUSTOMER
My Source and Target tables look like :
Thanks alot for your answer.
Best Answer
Posting the create table statements and insert statements instead of pictures could really help the next time you ask a question. Less trouble for both parties as you will get a faster answer.
Having said that, below is a way to do it but there are a few considerations / uncertanties due:
Calculating it for each customer for each month:
But as you will notice, this returns some more values than the result set specified, I also added
CALMONTH
.Resultset
To get closer to your resulset, I decided that whenever a customer has a revenue that is <> 0, the flag for that customer is set to 'X', even if he has a revenue of 0 in one of the months. Query
Resultset
Dataset used