문제

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

도움이 되었습니까?

해결책

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,'
                  )

다른 팁

ORDER BY CASE WHEN ProcductCode  = 'efg' THEN 1 
              WHEN ProcductCode  = 'abc' THEN 2
              WHEN ProcductCode  = 'xyz' THEN 3
         END ASC    
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top