How to get the next row value for a particular column if first row contains NULL
?
Data looks like below;
Table 1:
| ID | NAME |
| ------------ | ------------ |
| 1 | BASD |
| 1 | KLJY |
| 2 | Brush |
| 2 | RISHI |
| 3 | Paint |
Table 2 :
ID | ASSET_NUMBER | PRIMARY_FLAG |
---|---|---|
1 | 5478 | Y |
1 | NULL | |
2 | Y | |
2 | 8956 | NULL |
2 | N | |
3 | 2547 | Y |
3 | NULL |
We need to get the combined result from Table 1 and Table 2 using LEFT JOIN where Table 2 PRIMARY_FLAG
column value should be Y
but if there is no value in the ASSET_NUMBER
column for the Y
PRIMARY_FLAG value then query should return next row where ASSET_NUMBER
column should have a numeric value (it should not be null or empty).
OUTPUT:(expected result using table 1 join table 2)
| ID | NAME | ASSET_NUMBER |
| ------------ | ------------ | ------------ |
| 1 | BASD | 5478 |
| 1 | KLJY | 5478 |
| 2 | Brush | 8956 |
| 2 | RISHI | 8956 |
| 3 | Paint | 2547 |
I've written a SQL query below using LEFT JOIN
, however it's not producing the desired results and also the rows are multiplying by table1*table2;
SELECT
t1.ID,
t1.Name,
t2.Asset_Number
FROM
Table1 t1
LEFT JOIN table2 t2 on t1._ID = t2.ID and Primary_Flag = 'Y'
Please suggest the changes in the query to get the desired outcome.
2条答案
按热度按时间ogsagwnx1#
There is an issue with your data structure in that there is no guaranteed order of your rows. It's possible that they could come out of the tables like you've described, but it's also possible that they could come out in a different order.
Unless you address that, there would be no way to create a reliable range of rows between
PRIMARY_FLAG
= 'Y' andPRIMARY_FLAG
= 'N'. For all we know, it's possible to have dozens ofNULL
rows between those two values.However, With this in mind, here are two options. Both are unreliable since the order out of your tables aren't guaranteed -
Original query -
Very next row if
ASSET_NUMBER
isNULL
-First non-
NULL
value for a given ID after aNULL
ASSET_NUMBER
wherePRIMARY_FLAG
= 'Y' -fiddle
9avjhtql2#
There is a problem with your data structure... But this is a repetition :)
db<>fiddle