Sorting by date across two separate columns in a Full Outer Join

933 Views Asked by At

I have two columns of data I am lining up using a Full Outer Join but it includes two separate date columns which make it challenging to sort by.

Table 1 has sales rank data for a product. Table 2 has actual sales data for the same product.

Each table may have entries for dates on which the other does not.

So envision after the full join, we end up with something like this simplified example:

ProdID  L.Date         P.Date       Rank   Units
101     null           2011-10-01   null   740
101     2011-10-02     2011-10-02   23     652
101     2011-10-03     null         32     null

Here is the query I am using to pull this data:

select L.ListID, L.ASIN, L.date, L.ranking, P.ASIN, P.POSdate, P.units from ListItem L
full outer join POSdata P on 
    L.ASIN = P.ASIN and 
    L.date = P.POSdate and 
    (L.ListID = 1 OR L.ASIN is null)
where (L.ASIN = 'xxxxxxxxxx' and L.ListID = 1) or  
      (P.ASIN = 'xxxxxxxxxx' and L.BookID is null) 
order by POSdate, date

It's a bit more complex because products may appear on multiple lists so I have to account for that as well, but it returns the data I need. I am open to suggestions on improving it of course should someone have one.

The problem is, how can I sort this properly when both date columns are likely to have at least some NULLs in them. The way I am Ordering By now will not work when both columns have at one NULL.

Thanks.

1

There are 1 best solutions below

2
On BEST ANSWER

ORDER BY ISNULL(P.POSdate,L.date) should do what you need I think?