Hi,
I am trying to extract a column value from the "first" row that satisfies some criteria, where "first" is defined by a hard-coded list of column values. Unfortunately I'm a SQL amateur. I'm using DB2.
I can do it inefficiently like this:
SELECT COALESCE(
(SELECT COL FROM SOMETABLE WHERE X = "txt1" AND Y = "txt2" AND COL = 'A'),
(SELECT COL FROM SOMETABLE WHERE X = "txt1" AND Y = "txt2" AND COL = 'B'),
(SELECT COL FROM SOMETABLE WHERE X = "txt1" AND Y = "txt2" AND COL = 'C'),
(SELECT COL FROM SOMETABLE WHERE X = "txt1" AND Y = "txt2" AND COL = 'D')
)
The problem here is that SOMETABLE is very big. So instead I would like to do something like:
SELECT COALESCE(
(SELECT COL FROM T WHERE COL = 'A'),
(SELECT COL FROM T WHERE COL = 'B'),
(SELECT COL FROM T WHERE COL = 'C'),
(SELECT COL FROM T WHERE COL = 'D')
)
FROM
(SELECT COL FROM SOMETABLE WHERE X = "txt1" AND Y = "txt2") AS T
This is invalid, since I cannot reference the T table.
Assume that T above contains the following rows:
'E'
'B'
'D'
Then I would like to pick 'B', because it is the first value specified in the COALESCE statement.
I realise I can get somewhat nearer what I want by doing something like:
SELECT
(CASE COL WHEN 'A' THEN COL ELSE NULL END),
(CASE COL WHEN 'B' THEN COL ELSE NULL END),
(CASE COL WHEN 'C' THEN COL ELSE NULL END),
(CASE COL WHEN 'D' THEN COL ELSE NULL END)
FROM
(SELECT COL FROM SOMETABLE WHERE X = "txt1" AND Y = "txt2") AS T
This yields the result:
- - - - - - - D - B - -
Now I would like to aggregate or "flatten" this into a single row like so:
- B - D
And then I would simply coalesce on the columns.
Any suggestions would be greatly appreciated!