How to get first row value from each group and apply to first record only, rest will be 0 or null in SQL Server

602 views Asked by At

This is our output:

category Rev trandate BankAccNo Fee
Credit Cards 1 01-09-2022 10000175090 576
Credit Cards 1 01-09-2022 10000175090 576
Loan 2.2 01-01-2022 10000175090 678
Loan 2.2 01-02-2022 10000175090 678
Loan 3.4 01-03-2022 10000175090 678
Loan 2.2 01-05-2022 10000175090 678
Loan 2.2 01-06-2022 10000175090 678
Loan 5.81 01-08-2022 10000175090 678
Loan 2.2 01-09-2022 10000175090 678

But we are looking for expected result should be look like mentioned below.

category Rev trandate BankAccNo Fee
Credit Cards 1 01-09-2022 10000175090 576
Credit Cards 1 01-09-2022 10000175090 0
Loan 2.2 01-01-2022 10000175090 678
Loan 2.2 01-02-2022 10000175090 0
Loan 3.4 01-03-2022 10000175090 0
Loan 2.2 01-05-2022 10000175090 0
Loan 2.2 01-06-2022 10000175090 0
Loan 5.81 01-08-2022 10000175090 0
Loan 2.2 01-09-2022 10000175090 0

Final result would look like 2nd table mentioned on the above.

1

There are 1 answers

0
Tim Biegeleisen On

Using ROW_NUMBER() along with a CASE expression:

SELECT category, Rev, trandate, BankAccNo,
       CASE WHEN ROW_NUMBER() OVER (PARTITION BY category, BankAccNo ORDER BY trandate) = 1
            THEN Fee ELSE 0 END AS Fee
FROM yourTable
ORDER BY 1, 5;

In the event that two or more records from the same category happen to fall on the same earliest transaction date, then only one of those records will arbitrarily report the actual fee value, with the other tie records reporting 0.