sql server - SQL to extract distinct values from an UNION query ordered by values that are not required -


i trying top 20 distinct address records query union...

the issue want order date first - customer sees recent - each date makes row unique , leaves me ton of replica addresses (please see below).

select      cb.customerguid, cb.displayaddress, cb.locatorid       (select           b.customerguid, cast(b.pickupdatetime date) traveldate,           b.pickupdisplayaddress displayaddress, b.pickupaddressid locatorid                bookings b                customerguid = '463a20f2-a874-4964-865d-70d71065a69b'       union        select           b2.customerguid, cast(b2.pickupdatetime date) traveldate,           b2.destinationdisplayaddress displayaddress, b2.pickupaddressid locatorid                bookings b2                customerguid = '463a20f2-a874-4964-865d-70d71065a69b'      order           traveldate desc) cb 

i felt approach make union query subquery , query (without date) distinct have since learned order of rows in result set controlled order clause in outer select. therefore gives me error:

the order clause invalid in views, inline functions, derived tables, subqueries, , common table expressions, unless top, offset or xml specified.

how around please?

something think work, assuming doesn't matter traveldate sort by:

select top 20 cb.customerguid, cb.displayaddress, cb.locatorid  (select b.customerguid, cast(b.pickupdatetime date) traveldate,  b.pickupdisplayaddress displayaddress, b.pickupaddressid locatorid bookings b customerguid = '463a20f2-a874-4964-865d-70d71065a69b' union  select b2.customerguid, cast(b2.pickupdatetime date) traveldate,  b2.destinationdisplayaddress displayaddress, b2.pickupaddressid locatorid bookings b2 customerguid = '463a20f2-a874-4964-865d-70d71065a69b' ) cb group cb.customerguid, cb.displayaddress, cb.locatorid order max(traveldate) desc 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -