如何对两列或更多列进行条件排序

ado*_*lot 11 sql-server order-by

在 MS SQL Server 2005 中,我正在编写一个带有条件排序的查询,我的问题是我不知道如何使用两列进行条件排序?

如果我写了这样的代码,它就可以正常工作

select
    *
from 
    table
order by 
    case @pkr 
           when 'kol' then kol
           when 'nci' then nci
    end
Run Code Online (Sandbox Code Playgroud)

我不知道如何对两列或更多列进行条件排序

select
    *
from 
    table
order by 
    case @pkr
        when 'KOL-NCI' then kol,nci
        when 'kol-MPCI' then kol,mpci
    end
Run Code Online (Sandbox Code Playgroud)

有一个制作动态 TSQL 并使用的想法,sp_executesql但我仍在寻找更好的想法?

Mar*_*ith 13

我承认我以前从来没有这样做过,所以有点头疼。简单的示例表来演示:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') AND type in (N'U'))
    DROP TABLE [dbo].[MyTable]
GO

CREATE TABLE dbo.MyTable
(
    col1 INT
    , col2 CHAR(1)
)
GO

INSERT dbo.MyTable (col1, col2) VALUES (1, 'A')
INSERT dbo.MyTable (col1, col2) VALUES (1, 'B')
INSERT dbo.MyTable (col1, col2) VALUES (1, 'C')
INSERT dbo.MyTable (col1, col2) VALUES (2, 'A')
INSERT dbo.MyTable (col1, col2) VALUES (2, 'B')
INSERT dbo.MyTable (col1, col2) VALUES (2, 'C')
INSERT dbo.MyTable (col1, col2) VALUES (3, 'A')
INSERT dbo.MyTable (col1, col2) VALUES (3, 'B')
INSERT dbo.MyTable (col1, col2) VALUES (3, 'C')
Run Code Online (Sandbox Code Playgroud)

使用 @SortStyle 参数来区分排序顺序,col1 ASC, col2 DESC@SortStyle = 1 将 sort by和 @SortStyle=2 sort by col2 DESC, col1 ASC

DECLARE @SortStyle INT
SET @SortStyle = 1

SELECT
    col1
    , col2
FROM
    dbo.MyTable
ORDER BY
    CASE
        WHEN @SortStyle = 1 THEN col1
    END ASC,
    CASE
        WHEN @SortStyle = 1 THEN col2
    END DESC,
    CASE
        WHEN @SortStyle = 2 THEN col2
    END DESC,
    CASE
        WHEN @SortStyle = 2 THEN col1
    END ASC

SET @SortStyle = 2

SELECT
    col1
    , col2
FROM
    dbo.MyTable
ORDER BY
    CASE
        WHEN @SortStyle = 1 THEN col1
    END ASC,
    CASE
        WHEN @SortStyle = 1 THEN col2
    END DESC,
    CASE
        WHEN @SortStyle = 2 THEN col2
    END DESC,
    CASE
        WHEN @SortStyle = 2 THEN col1
    END ASC
Run Code Online (Sandbox Code Playgroud)

如何按参数排序涵盖了仅按 1 列排序的更简单情况。


gbn*_*gbn 5

假设你有更多的案例(我加了一个),并且所有类型都兼容,

order by 
    case @pkr
        when 'KOL-NCI' then kol
        when 'kol-MPCI' then kol
        when 'foo-bar' then foo
    end,
    case @pkr
        when 'KOL-NCI' then nci
        when 'kol-MPCI' then mpci
        when 'foo-bar' then bar 
    end
Run Code Online (Sandbox Code Playgroud)

它不是多列排序:您有一个主要排序,然后是一个次要排序。只需查看 Excel 中的排序对话框即可了解我的意思。