在SQL Server 2008中通过单个查询简单地处理条件

时间:2018-07-27 13:21:29

标签: sql-server sql-server-2008 sql-order-by case

如何在一个查询中简化下面的T-SQL语句?

IF @OrderByDescription = 1
BEGIN
    SELECT d.DeptId, Description
    FROM Dept d 
    LEFT JOIN DeptOrder o ON p.DeptId = o.DeptId
    WHERE d.DeptId IN (3, 7, 9, 10, 17, 20)
    ORDER BY Description
END
ELSE
BEGIN
    SELECT d.DeptId, Description
    FROM Dept d 
    LEFT JOIN DeptOrder o ON p.DeptId = o.DeptId
    WHERE d.DeptId IN (3, 7, 9, 10, 17, 20)
    ORDER BY
        CASE WHEN o.[Order] IS NULL THEN 1
             ELSE 0
        END, o.[Order]
END

3 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT  d.DeptId, Description
FROM    Dept d LEFT JOIN DeptOrder o on p.DeptId = o.DeptId
WHERE   d.DeptId IN (3, 7, 9, 10, 17, 20)
ORDER BY 
   CASE 
      WHEN @OrderByDescription = 1 THEN Description
      ELSE 1
   END,
   CASE 
      WHEN o.[Order] IS NULL THEN 1                                            
      ELSE 0
   END, 
   o.[Order]

答案 1 :(得分:1)

将您的IF条件移到一个CASE中,然后将另一个CASE嵌套在其中。

SELECT
  d.DeptId
 ,Description
FROM
  Dept AS d
  LEFT JOIN
    DeptOrder AS o
      ON
      p.DeptId = o.DeptId
WHERE
  d.DeptId IN
    ( 3, 7, 9, 10, 17, 20 )
ORDER BY
  CASE
    WHEN @OrderByDescription = 1 THEN Description
    ELSE CASE
           WHEN o.[Order] IS NULL THEN 1
           ELSE 0
         END
  END
 ,o.[Order];

答案 2 :(得分:0)

尝试一下。

DECLARE @OrderByDescription INT = 1;

WITH CTE_Order
AS (
    SELECT d.DeptId
        ,Description
        ,CASE 
            WHEN @OrderByDescription = 1
                THEN ROW_NUMBER() OVER (
                        ORDER BY Description
                        )
            ELSE ROW_NUMBER() OVER (
                    ORDER BY CASE 
                            WHEN o.[Order] IS NULL
                                THEN 1
                            ELSE 0
                            END
                        ,o.[Order]
                    )
            END RowNum
    FROM Dept d
    LEFT JOIN DeptOrder o ON p.DeptId = o.DeptId
    WHERE d.DeptId IN (
            3
            ,7
            ,9
            ,10
            ,17
            ,20
            )
    )
SELECT *
FROM CTE_Order
ORDER BY RowNum