Question

SELECT 
    ProcductCode AS Id, 
    ProductPrice AS Price
FROM 
    Products WITH (NOLOCK)
WHERE 
    ProductCode = 'efg' OR ProductCode = 'abc' OR  ProductCode = 'xyz'

In the above query the I want to have the returned data in order by ProductCode but not the default ascending or descending but rather by the order in which the where clause finds a match.

I don't want

ORDER BY ProductCode ASC|DESC; 

So in the above example if we assume that there is a ProductCode entry in the table for all three in the where clause then it should return

ID             Price
---------------------
efg            1.00
abc            1.00  
xyz            1.00

Is there a way to order by "or" order. Kinda stuck on this. Ideas and/or examples would be helpful

Était-ce utile?

La solution

You can use case. Your where clause is easier to read using in:

SELECT ProcductCode AS Id, ProductPrice AS Price
FROM Products WITH (NOLOCK)
WHERE ProductCode IN ('efg', 'abc', 'xyz')
ORDER BY (CASE WHEN ProductCode = 'efg' THEN 1
               WHEN ProductCode = 'abc' THEN 2
               WHEN ProductCode = 'xyz' THEN 3
               ELSE 4  -- in case you change the `where`, put them last
          END);

By the way, if you wanted, you could do this as:

ORDER BY CHARINDEX(','+ProductCode+',',
                   ',efg,abc,xyz,'
                  )

Autres conseils

ORDER BY CASE WHEN ProcductCode  = 'efg' THEN 1 
              WHEN ProcductCode  = 'abc' THEN 2
              WHEN ProcductCode  = 'xyz' THEN 3
         END ASC    
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top