SQL:ORDER BY语句中的嵌套大小写

时间:2018-07-09 13:14:46

标签: sql sql-server sql-server-2008

我试图在我的查询的ORDER BY部分中将一个case语句嵌套到另一个语句中。这是我得到的:

ORDER BY 

CASE WHEN v.Interior = 'MEL (White - 113)' AND v.Interior = 'MEL 290 (Maple)' 
THEN v.[Finish] ELSE

( CASE
        WHEN v.[Item] like 'Adjustable%'  THEN v.[Item]                 
        WHEN v.[Item] Like 'Fixed%'       THEN v.[Item]
        WHEN v.[Item] like '%Divider%'    THEN v.[Item]
        END DESC)

,v.[Finish], v.[W mm] DESC

END

但是这样做给我一个错误。我也尝试过:

ORDER BY 

CASE WHEN v.Interior = 'MEL (White - 113)' AND v.Interior = 'MEL 290 (Maple)' 
THEN v.[Finish] END

,CASE
        WHEN v.[Item] like 'Adjustable%'  THEN v.[Item]         
        WHEN v.[Item] Like 'Fixed%'       THEN v.[Item]
        WHEN v.[Item] like '%Divider%'    THEN v.[Item]
        END DESC

,v.[Finish], v.[W mm] DESC

但是,这并没有按照我需要的方式对结果进行排序。

这是错误修复后得到的结果:

enter image description here

但是上述结果不符合第一个案例陈述。我不能按LEVEL订购,因为当我将结果导出到另一个程序时会引起问题。

有人知道如何解决此问题吗?

感谢您的提前帮助!

3 个答案:

答案 0 :(得分:0)

在两个查询之间,您解决了一个问题,但创建了另一个问题。最好一次只更改一件事情。

尝试一下:

ORDER BY 

CASE 
  WHEN v.Interior = 'MEL (White - 113)' AND v.Interior = 'MEL 290 (Maple)' 
  THEN v.[Finish] 
  ELSE CASE
        WHEN v.[Item] like 'Adjustable%'  THEN v.[Item]                 
        WHEN v.[Item] Like 'Fixed%'       THEN v.[Item]
        WHEN v.[Item] like '%Divider%'    THEN v.[Item]
        ELSE NULL --need to have some default if all cases are false.
  END DESC
END   
,v.[Finish], v.[W mm] DESC

这至少应该不是错误,但是从您的问题尝试中并不能确定它是否满足您的要求。

答案 1 :(得分:0)

例如,您可以使用cte

With cte(
Select CASE WHEN v.Interior = 'MEL (White - 113)' AND v.Interior = 'MEL 290 (Maple)' 
THEN v.[Finish] ELSE

( CASE
        WHEN v.[Item] like 'Adjustable%'  THEN v.[Item]                 
        WHEN v.[Item] Like 'Fixed%'       THEN v.[Item]
        WHEN v.[Item] like '%Divider%'    THEN v.[Item]
        END DESC) as 'Columnname'

,v.[Finish], v.[W mm]
From Yourtablename)
Select *
From cte
Order By Columnname, Finish, [W mm] DESC

答案 2 :(得分:0)

尝试将您的case语句放在括号内,其顺序方向在括号之外,如下所示:

ORDER BY 

(CASE WHEN v.Interior = 'MEL (White - 113)' OR v.Interior = 'MEL 290 (Maple)' 
 THEN v.[Finish]
 ELSE
     (CASE WHEN v.[Item] like 'Adjustable%'  THEN v.[Item]                 
           WHEN v.[Item] Like 'Fixed%'       THEN v.[Item]
           WHEN v.[Item] like '%Divider%'    THEN v.[Item]
           ELSE '' --Use '' as default. An empty order by will not affect your final result
      END) 
END) DESC
,v.[Finish]
,v.[W mm] DESC