SQL Server: Get the most recent Instance of date record that's added within 90 days - sql

So I have this code where it gets me these columns/data and the tables they belong to:
StudentName -- ST
stunum -- ST
ssn -- ST
Campus -- CA
SchoolStatus -- SS
Program -- AE
AYStart -- FS
AYEnd -- FS
AYStatus -- PS
StaffName -- SF
fastudentayid -- AU
DateAdded -- AU
This is my code
select rtrim(st.lastname) +', '+rtrim(st.FirstName) as StudentName,
st.StuNum,
st.SSN as SSN,
ca.Descrip as Campus,
ss.Descrip as SchoolStatus,
ae.adProgramDescrip as Program,
convert(varchar(10),fs.StartDate,101) as AYStart,
convert(varchar(10),fs.EndDate,101) as AYEnd,
ps.Descrip as AYStatus,
rtrim(sf.lastname) +', '+rtrim(sf.FirstName) as StaffName,
fs.faStudentAyID as faStudentAyID,
convert(varchar(10), MAX(af.DateAdded),101) as DateAdded
from stuTbl (nolock) as ST
join CpsTbl (nolock) as CA
on ca.CpsID = st.CpsID
join scStatTbl (nolock) as SS
on ss.ScStatTblID = st.ScStatTblID
join AdEnTbl (nolock) as AE
on ae.stuTblID = st.stuTblID
join faStAy (nolock) as FS
on fs.AdEnTblID = ae.AdEnTblID
join FaPStat (nolock) as PS
on ps.FaPStatID = fs.FaPStatID
join (select RecordID, ColumnName, NewVal, UserID, DateAdded, MAX(DateAdded) as MDA
from syA_FaPStatTbl
where ColumnName = 'Package Status'
and (NewVal = '38'
or NewVal = '40'
or NewVal = '43'
or NewVal = '67'
or NewVal = '68')
and DateAdded between getDate()-90 and getDate()
group by RecordID, ColumnName, NewVal, UserID, DateAdded) as AF
on af.RecordID = fs.faStAyID
join StaffTbl (nolock) as SF
on af.UserID = sf.StaffTblID
where (ps.Descrip = 'Submitted'
or ps.Descrip = 'Resubmitted'
or ps.Descrip = 'Pell Submitted'
or ps.Descrip = 'Aid Submitted'
or ps.Descrip = 'Aid Resubmitted')
and af.DateAdded between getDate()-90 and getDate()
Group by st.lastname, st.FirstName,
st.StuNum,
st.SSN,
ca.Descrip,
ss.Descrip,
ae.adProgramDescrip,
fs.StartDate,
fs.EndDate,
ps.Descrip,
sf.lastname, sf.FirstName,
fs.faStudentAyID
I am getting what I need as far as the data goes in that I am not duplicating entries. My problem is if someone alters the status at the client end software, it pulls both instances where the status was switched to Submitted as long as the change is within 90 days of today's date.
Here's a sample data -- notice Crytal Ball's record? Someone updated the status and submitted it on 5/11 and again on 6/5/2018. I just need the latest record no matter how many times the status is updated regardless of how many times it happened the past 90 days, which in this case is the 6/5/2018 one.
Jones, Mary || 124926 || xxx-xx-xxxx || Seattle || Active || MCA Prog || 05/28/2018 || 12/23/2018 || Submitted || Doe, John || 1763799 || 06/06/2018
Doe, Dawn || 126954 || xxx-xx-xxxx || Online || Ready to Start || MBC Prog || 05/28/2018 || 12/23/2018 || Resubmitted || Jones, Bob, || 1760731 || 06/06/2018
Ball, Crystal || 12399 || xxx-xx-xxxx || Chattanooga || Active || MCA Dipl || 07/02/2018 || 02/10/2019 || Submitted || Jones, Jenny || 1734032 || 05/11/2018
Ball, Crystal || 12399 || xxx-xx-xxxx || Chattanooga || Active || MCA Dipl || 07/02/2018 || 02/10/2019 || Resubmitted || Tavares, John || 1734032 || 06/05/2018
Barnes, Matt || 11817 || xxx-xx-xxxx || Online || Drop || 4 yr BSAH Mgt || 04/23/2018 || 11/18/2018 || Submitted || Doe, Luis || 1759782 || 04/27/2018
EDIT:
- I've tried putting Top 1 on the JOIN (Select) portion of the code and it doesn't let me pull any records at all.

All you need to do is use a row_number() to get the right data like below
select
StudentName,StuNum,SSN,Campus,
SchoolStatus,Program,AYStart,AYEnd,AYStatus,
StaffName,faStudentAyID,DateAdded
from
(select *,
row_number() over( partition by fs.faStudentAyID order by DateAdded) as rn
from
(
select rtrim(st.lastname) +', '+rtrim(st.FirstName) as StudentName,
st.StuNum,
st.SSN as SSN,
ca.Descrip as Campus,
ss.Descrip as SchoolStatus,
ae.adProgramDescrip as Program,
convert(varchar(10),fs.StartDate,101) as AYStart,
convert(varchar(10),fs.EndDate,101) as AYEnd,
ps.Descrip as AYStatus,
rtrim(sf.lastname) +', '+rtrim(sf.FirstName) as StaffName,
fs.faStudentAyID as faStudentAyID,
convert(varchar(10), MAX(af.DateAdded),101) as DateAdded
from stuTbl (nolock) as ST
join CpsTbl (nolock) as CA
on ca.CpsID = st.CpsID
join scStatTbl (nolock) as SS
on ss.ScStatTblID = st.ScStatTblID
join AdEnTbl (nolock) as AE
on ae.stuTblID = st.stuTblID
join faStAy (nolock) as FS
on fs.AdEnTblID = ae.AdEnTblID
join FaPStat (nolock) as PS
on ps.FaPStatID = fs.FaPStatID
join (select RecordID, ColumnName, NewVal, UserID, DateAdded, MAX(DateAdded) as MDA
from syA_FaPStatTbl
where ColumnName = 'Package Status'
and (NewVal = '38'
or NewVal = '40'
or NewVal = '43'
or NewVal = '67'
or NewVal = '68')
and DateAdded between getDate()-90 and getDate()
group by RecordID, ColumnName, NewVal, UserID, DateAdded) as AF
on af.RecordID = fs.faStAyID
join StaffTbl (nolock) as SF
on af.UserID = sf.StaffTblID
where (ps.Descrip = 'Submitted'
or ps.Descrip = 'Resubmitted'
or ps.Descrip = 'Pell Submitted'
or ps.Descrip = 'Aid Submitted'
or ps.Descrip = 'Aid Resubmitted')
and af.DateAdded between getDate()-90 and getDate()
Group by st.lastname, st.FirstName,
st.StuNum,
st.SSN,
ca.Descrip,
ss.Descrip,
ae.adProgramDescrip,
fs.StartDate,
fs.EndDate,
ps.Descrip,
sf.lastname, sf.FirstName,
fs.faStudentAyID
) t
)t
where rn=1

Related

How to unite several tables in a one so the names of the columns became the row names?

for instance I have
SELECT customer_id, first_name || ', ' || last_name || ', ' || email as "customer's info"
FROM customer
WHERE customer_id = 5
;
SELECT count(i.film_id) AS "num.of films rented" FROM payment p
JOIN rental r ON p.rental_id = r.rental_id
JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE r.rental_date >= ('2014-01-01'::date)
AND r.rental_date <= ('2017-05-03'::date)
AND p.customer_id = 5
;
I want in output
metric1 | metric2
----------------------------
customer's info | blalalalal
num.of films rented | blalalalal
I try smth like, but nothing
SELECT * FROM crosstab(
SELECT first_name || ', ' || last_name || ', ' || email
FROM customer WHERE customer_id = 5,
SELECT count(i.film_id) FROM payment p
JOIN rental r ON p.rental_id = r.rental_id
JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE r.rental_date >= ('2014-01-01'::date)
AND r.rental_date <= ('2017-05-03'::date))
AS ('fjfjf' TEXT, 'fjfjf' int );
Could you help me?
I dont know how to do it in postgress
Thanks a lot
I would UNION ALL the two queries together - but remember to CAST the count value as a string, as you need matching data types to UNION:
SELECT
'customer''s info' AS "name"
, first_name || ', ' || last_name || ', ' || email AS "value"
FROM customer c
UNION ALL
'num.of films rented' AS "name"
, COUNT(i.film_id)::VARCHAR(5) AS "value"
FROM payment p
JOIN rental r ON p.rental_id = r.rental_id
JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE r.rental_date >= ('2014-01-01'::date)
AND r.rental_date <= ('2017-05-03'::date)
WHERE customer_id = 5
;
It is unclear to me why inventory is in the second join.
SELECT 'customer''s info' as metric1,
first_name || ', ' || last_name || ', ' || email as metric2
FROM customer
WHERE customer_id = 5
UNION ALL
SELECT 'num.of films rented' as metric1, count(i.film_id)::text AS metric2
FROM payment p JOIN
rental r
ON p.rental_id = r.rental_id
WHERE r.rental_date >= '2014-01-01'::date AND
r.rental_date <= '2017-05-03'::date AND
p.customer_id = 5;
You could also combine this into a single query if you are just trying to get the results in a single result set:
SELECT (first_name || ', ' || last_name || ', ' || email) as customer_info,
count(i.film_id) as num_films
FROM payment p JOIN
rental r
ON p.rental_id = r.rental_id JOIN
customer c
ON c.customer_id = p.customer_id
WHERE r.rental_date >= '2014-01-01'::date AND
r.rental_date <= '2017-05-03'::date AND
c.customer_id = 5
GROUP BY c.customer_id;
(This puts the values in one row with two columns.) Using a subquery, the results can be easily unpivoted.

Join two of the same tables to another table and output the info of the (same) table in the same row

Sorry for the bad/long title but I don't know how else to put it.
What I want to do is join to 'A' tables and join it to the 'B' table where both 'A' have a foreign key in common and display info from both 'A' tables in the same row while preventing duplicates such as the example in the pic:
I know the query is just doing it's job, but is there a way to prevent 'duplicates' by comparing between the rows before output?
Here's what I tried, I know it may be bad performance-wise and there may be better ways but this is for a mini-project with a small DB, where performance shouldn't really matter:
SELECT w.emp_id AS emp1_id, w2.emp_id AS emp2_id,
e.fname || ' ' || e.lname AS emp1_name, e1.fname || ' ' || e1.lname AS emp2_name,
e.jobtitle AS emp1_jobtitle, e1.jobtitle AS emp2_jobtitle, e2.fname || ' ' || e2.lname AS cs_name
FROM work_on w
LEFT JOIN work_on w2
on w.emp_id != w2.emp_id and w.ticket_id = w2.ticket_id
LEFT JOIN employee e
on w.emp_id = e.emp_id
LEFT JOIN employee e1
on w2.emp_id = e1.emp_id
LEFT JOIN ticket t
on t.ticket_id = w.ticket_id
LEFT JOIN customer_problem p
on p.problem_id = t.problem_id
LEFT JOIN employee e2
on e2.emp_id = p.emp_id
WHERE e2.emp_id = 20 and p.submit_date >= '2018-04-08'
and p.submit_date <= '2018-04-11' and e1.emp_id != e.emp_id
ORDER BY w.emp_id;
My tables:
Employee: | Work_On: | Ticket: | Problem
----------+------------+--------------+------------
emp_id work_id ticket_id problem_id
fname emp_id problem_id emp_id
lname ticket_id
In this case I'm trying to combine two Employee on Work_On where they have the Ticket in common and another Employee which connects to the ticket via the Problem table.
Here is one option using least/greatest:
SELECT DISTINCT
LEAST(w.emp_id, w2.emp_id) AS emp1_id,
GREATEST(w.emp_id, w2.emp_id) AS emp2_id,
LEAST(e.fname || ' ' || e.lname, e1.fname || ' ' || e1.lname) AS emp1_name,
GREATEST(e.fname || ' ' || e.lname, e1.fname || ' ' || e1.lname) AS emp2_name,
LEAST(e.jobtitle, e1.jobtitle) AS emp1_jobtitle,
GREATEST(e.jobtitle, e1.jobtitle) AS emp2_jobtitle,
e2.fname || ' ' || e2.lname AS cs_name
FROM work_on w
LEFT JOIN work_on w2
ON w.emp_id != w2.emp_id AND w.ticket_id = w2.ticket_id
LEFT JOIN employee e
ON w.emp_id = e.emp_id
LEFT JOIN employee e1
ON w2.emp_id = e1.emp_id
LEFT JOIN ticket t
ON t.ticket_id = w.ticket_id
LEFT JOIN customer_problem p
ON p.problem_id = t.problem_id
LEFT JOIN employee e2
ON e2.emp_id = p.emp_id
WHERE
e2.emp_id = 20 AND
p.submit_date >= '2018-04-08' AND
p.submit_date <= '2018-04-11' AND
e1.emp_id != e.emp_id
ORDER BY w.emp_id;
To see why the least/greatest trick works, consider the following two records/columns:
emp1_id | emp2_id
2 | 15
15 | 2
It should be clear that while these records are distinct now, if we instead choose the least id followed by the greatest id, they appear identical:
LEAST(emp_id1, emp_id2) | GREATEST(emp_id1, emp_id2)
2 | 15
2 | 15
Then, using SELECT DISTINCT removes one of the two duplicate rows.

Aggregate function as condition

I'm having problem trying to use aggregate function result as a condition. Basically, I need to select rows that have "View count" more than 3. Here is code that works:
SELECT b.BranchNo AS "Branch Number",
p.PropertyNo || ', ' || p.PostCode || ', ' || p.City || ', ' || p.Street AS "Object address" , count(v.ViewDate) as "View count"
FROM Branch b INNER JOIN PropertyForRent p ON b.BranchNo=p.PropertyBranchNo
INNER JOIN Viewing v ON p.PropertyNo=v.ViewPropertyNo WHERE v.ViewDate>='2014-01-01'
GROUP BY b.BranchNo, p.PropertyNo;
I was trying to use something like that:
HAVING count(v.ViewDate)>=3
But that obviously didn't work. Is there a way of making such condition without using a subquery?
It looks like the fields in your select don't match up with the group by, but other than that, the "condition based on aggregate" is exactly what the having clause is for. For example, this query should work:
SELECT
b.BranchNo AS "Branch Number",
p.PropertyNo || ', ' || p.PostCode || ', ' || p.City || ', ' || p.Street AS "Object address" ,
count(v.ViewDate) as "View count"
FROM Branch b INNER JOIN PropertyForRent p ON b.BranchNo=p.PropertyBranchNo
INNER JOIN Viewing v ON p.PropertyNo=v.ViewPropertyNo WHERE v.ViewDate>='2014-01-01'
GROUP BY b.BranchNo, p.PropertyNo, p.PostCode, p.City, p.Street
HAVING count(v.ViewDate) >= 3;
You need to do grouping in Viewing table sub-query to get the counts. Then join to that.
SELECT b.BranchNo AS [Branch Number],
p.PropertyNo + ', ' + p.PostCode + ', ' + p.City + ', ' + p.Street AS [Object address],
v.ViewCount
FROM Branch b
INNER JOIN PropertyForRent p ON b.BranchNo=p.PropertyBranchNo
INNER JOIN (SELECT ViewPropertyNo, COUNT(*) as ViewCount
FROM Viewing
WHERE v.ViewDate>='2014-01-01'
GROUP BY ViewPropertyNo
) AS v ON p.PropertyNo = v.ViewPropertyNo
WHERE v.ViewCount >= 3;

Postgresql: Subquery in FROM must have an alias - with multiple joins

I get the following error:
ERROR: subquery in FROM must have an alias
LINE 11: (SELECT "domiciles"."id" AS id,
^
HINT: For example, FROM (SELECT ...) [AS] foo.
with the following SQL query:
SELECT "domiciles".*
FROM "domiciles"
LEFT OUTER JOIN
(SELECT "domiciles"."id" AS id,
string_agg("locations"."name"::text, ' ') AS name
FROM "domiciles"
INNER JOIN "locations" ON "locations"."id" = "domiciles"."place_id"
AND "locations"."type" IN ('Place')
GROUP BY "domiciles"."id") place ON place.id = "domiciles"."id"
LEFT OUTER JOIN
(SELECT "domiciles"."id" AS id,
string_agg("accounts"."email"::text, ' ') AS email
FROM "domiciles"
INNER JOIN "accounts" ON "accounts"."id" = "domiciles"."user_id"
AND "accounts"."type" IN ('User')
GROUP BY "domiciles"."id") user ON user.id = "domiciles"."id"
WHERE "domiciles"."deleted_at" IS NULL
I have tried to add AS 'some_text' in many parts of the query, but I cannot solve this problem. Any idea?
Here the complete SQL query to have an idea what I want to do:
SELECT "domiciles".*,
((ts_rank((to_tsvector('german', unaccent(coalesce("domiciles"."is_default"::text, ''))) || to_tsvector('german', unaccent(coalesce("domiciles"."created_at"::text, ''))) || to_tsvector('german', unaccent(coalesce("domiciles"."updated_at"::text, ''))) || to_tsvector('german', unaccent(coalesce(place.name::text, ''))) || to_tsvector('german', unaccent(coalesce(user.email::text, ''))) || to_tsvector('german', unaccent(coalesce(owner.email::text, '')))), (to_tsquery('german', ''' ' || unaccent('abc') || ' ''' || ':*')), 0))) AS pg_search_rank
FROM "domiciles"
LEFT OUTER JOIN
(SELECT "domiciles"."id" AS id,
string_agg("locations"."name"::text, ' ') AS name
FROM "domiciles"
INNER JOIN "locations" ON "locations"."id" = "domiciles"."place_id"
AND "locations"."type" IN ('Place')
AND "locations"."deleted_at" IS NULL
GROUP BY "domiciles"."id") place ON place.id = "domiciles"."id"
LEFT OUTER JOIN
(SELECT "domiciles"."id" AS id,
string_agg("accounts"."email"::text, ' ') AS email
FROM "domiciles"
INNER JOIN "accounts" ON "accounts"."id" = "domiciles"."user_id"
AND "accounts"."type" IN ('User')
AND "accounts"."deleted_at" IS NULL
GROUP BY "domiciles"."id") user ON user.id = "domiciles"."id"
LEFT OUTER JOIN
(SELECT "domiciles"."id" AS id,
string_agg("accounts"."email"::text, ' ') AS email
FROM "domiciles"
INNER JOIN "locations" ON "locations"."id" = "domiciles"."place_id"
AND "locations"."type" IN ('Place')
AND "locations"."deleted_at" IS NULL
INNER JOIN "accounts" ON "accounts"."id" = "locations"."user_id"
AND "accounts"."type" IN ('User')
AND "accounts"."deleted_at" IS NULL
GROUP BY "domiciles"."id") owner ON owner.id = "domiciles"."id"
WHERE "domiciles"."deleted_at" IS NULL
AND "domiciles"."user_id" = $1
AND (((to_tsvector('german', unaccent(coalesce("domiciles"."is_default"::text, ''))) || to_tsvector('german', unaccent(coalesce("domiciles"."created_at"::text, ''))) || to_tsvector('german', unaccent(coalesce("domiciles"."updated_at"::text, ''))) || to_tsvector('german', unaccent(coalesce(place.name::text, ''))) || to_tsvector('german', unaccent(coalesce(user.email::text, ''))) || to_tsvector('german', unaccent(coalesce(owner.email::text, '')))) ## (to_tsquery('german', ''' ' || unaccent('abc') || ' ''' || ':*'))))
Found the problem! The following sentences:
place ON place.id
coalesce(place.name::text, '')
should be
"place" ON "place"."id"
coalesce("place"."name"::text, '')
and this for all sentences: place, owner, user, id

SQL: call second query if no rows are returned from the first query

I'm struggling to combine these two statements I've put together into a single statement.
My first statement is in effect 3 statements in where I only want the first statement that returns a value to be returned, which works a treat.
SELECT ReferenceKey, ReferenceValue FROM
(
SELECT a.GBNK076 AS ReferenceKey, TRIM(a.GBNK076) ||' - '|| b.BANM11 AS ReferenceValue, 1 as preference
FROM THTFU.THAP076P AS a LEFT OUTER JOIN OSLTHLF3.CSP11 AS b ON b.BANK11 = a.GBNK076 AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01' AND a.PMTH076 = 'BMG' AND a.CURN076 = 'EUR'
UNION
SELECT a.GBNK076 AS ReferenceKey, TRIM(a.GBNK076) ||' - '|| b.BANM11 AS ReferenceValue, 3 as preference
FROM THTFU.THAP076P AS a LEFT OUTER JOIN OSLTHLF3.CSP11 AS b ON b.BANK11 = a.GBNK076 AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01' AND a.PMTH076 = 'BMG' AND a.CURN076 = ''
UNION
SELECT a.GBNK076 AS ReferenceKey, TRIM(a.GBNK076) ||' - '|| b.BANM11 AS ReferenceValue, 3 as preference
FROM THTFU.THAP076P AS a LEFT OUTER JOIN OSLTHLF3.CSP11 AS b ON b.BANK11 = a.GBNK076 AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01' AND a.PMTH076 = '' AND a.CURN076 = ''
)BankPayingFrom ORDER BY preference
FETCH FIRST 1 ROWS ONLY
However, if none of these three statements return any information I want to be able fire off the SQL statement below to retrieve all possible records.
SELECT BANK11 as ReferenceKey, TRIM(BANK11) ||' - '|| BANM11 as ReferenceValue From OSLTHLF3.CSP11 WHERE CONO11 = '01'
How do I join both these statements together so that I need only make one call from my web service to the back end database (AS/400 DB2 database)?
I’d appreciate any assistance.
Many thanks
Christian
Without knowing your dataset it's hard to know for sure, but I believe this may be a cleaner alternative. It may perform faster, as well, but I can't guarantee that.
WITH BankPayingFrom (referenceKey, referenceValue) as (
SELECT a.GBNK076, TRIM(b.BANK11) ||' - '|| b.BANM11 -- typo? 'b.BANK11'?
FROM THTFU.THAP076P as a
LEFT JOIN OSLTHLF3.CSP11 as b
ON b.BANK11 = a.GBNK067
AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01'
AND ((a.PMTH076 = 'BMG' AND a.CURN076 = 'EUR')
OR (a.PMTH076 = 'BMG' AND a.CURN076 = '')
OR (a.PMTH076 = '' AND a.CURN076 = ''))
-- You may be able to use the following, but only if
-- a.PMTH076 is set for every set value of a.CURN076
-- AND (a.PMTH076 = 'BMG' OR a.PMTH067 = '')
-- AND (a.CURN076 = 'EUR' OR a.CURN076 = '')
ORDER BY a.PMTH076 DESC, a.CURN076 DESC
FETCH FIRST 1 ROW ONLY)
SELECT referenceKey, referenceValue
FROM BankPayingFrom
UNION
SELECT BANK11 as referenceKey, TRIM(BANK11) ||' - '|| BANM11 as referenceValue
FROM OSLTHLF3.CSP11
WHERE CONO11 = '01'
AND NOT EXISTS (SELECT '1'
FROM BankPayingFrom)
... Although looking at it further, the only real difference is a.GBNK076 in the CTE. Is it that you only want 1 row if a 'matching' row exists in THAP076P, otherwise you want all of them?
Not sure about AS/400 (iSeries), but here's how I might do it on Linux Unix Windows:
WITH BankOrderFromOne(ReferenceKey, ReferenceValue)
AS (
SELECT ReferenceKey, ReferenceValue FROM
(
SELECT a.GBNK076 AS ReferenceKey, TRIM(a.GBNK076) ||' - '|| b.BANM11 AS ReferenceValue, 1 as preference
FROM THTFU.THAP076P AS a LEFT OUTER JOIN OSLTHLF3.CSP11 AS b ON b.BANK11 = a.GBNK076 AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01' AND a.PMTH076 = 'BMG' AND a.CURN076 = 'EUR'
UNION
SELECT a.GBNK076 AS ReferenceKey, TRIM(a.GBNK076) ||' - '|| b.BANM11 AS ReferenceValue, 3 as preference
FROM THTFU.THAP076P AS a LEFT OUTER JOIN OSLTHLF3.CSP11 AS b ON b.BANK11 = a.GBNK076 AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01' AND a.PMTH076 = 'BMG' AND a.CURN076 = ''
UNION
SELECT a.GBNK076 AS ReferenceKey, TRIM(a.GBNK076) ||' - '|| b.BANM11 AS ReferenceValue, 3 as preference
FROM THTFU.THAP076P AS a LEFT OUTER JOIN OSLTHLF3.CSP11 AS b ON b.BANK11 = a.GBNK076 AND b.CONO11 = a.CONO076
WHERE a.CONO076 = '01' AND a.PMTH076 = '' AND a.CURN076 = ''
)BankPayingFrom ORDER BY preference
FETCH FIRST 1 ROWS ONLY
)
SELECT ReferenceKey, ReferenceValue FROM BankOrderFromOne
UNION
SELECT BANK11 as ReferenceKey, TRIM(BANK11) ||' - '|| BANM11 as ReferenceValue From OSLTHLF3.CSP11 WHERE CONO11 = '01'
AND NOT EXISTS (SELECT ReferenceKey, ReferenceValue FROM BankOrderFromOne)