Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL SERVER-订购方式_Sql_Sql Server_Sql Order By - Fatal编程技术网

SQL SERVER-订购方式

SQL SERVER-订购方式,sql,sql-server,sql-order-by,Sql,Sql Server,Sql Order By,hi-im使用sql server 2019 使用northwind数据库 我希望客户按国家分类。不同的是,首先是美国、德国和法国,然后是其他国家的升序。您可以在顺序中使用case表达式: order by (case when country in ('United States', 'Germany', 'France') then 1 else 0 end), country @戈登的回答将在最后一段中继续提到这些国家 您需要使用用例表达式,如下所示: order by

hi-im使用sql server 2019 使用northwind数据库
我希望客户按国家分类。不同的是,首先是美国、德国和法国,然后是其他国家的升序。

您可以在
顺序中使用
case
表达式:

order by (case when country in ('United States', 'Germany', 'France') then 1 else 0 end),
         country

@戈登的回答将在最后一段中继续提到这些国家

您需要使用用例表达式,如下所示:

order by (case when country in ('United States', 'Germany', 'France') then 0
          else 1 
          end),
         country
order by (case when country = 'United States' then 0
               When country = 'Germany' then 1
               When country = 'France' then 2 
               else 3 
          end),
         country
如果您希望在上述国家/地区内获得特定订单,请在以下情况下使用多个订单:

order by (case when country in ('United States', 'Germany', 'France') then 0
          else 1 
          end),
         country
order by (case when country = 'United States' then 0
               When country = 'Germany' then 1
               When country = 'France' then 2 
               else 3 
          end),
         country

< >为了使代码更加灵活,考虑在你的国家表中添加一个“Meta排序”列,这会给你很多灵活性WRT排序。 然后使用
按元顺序ASC排序,国家/地区ASC

通过这种结构,您可以在将来从“顶级”列表中添加/删除国家,甚至有几个级别,例如GER、USA、FRA优先(元顺序列中为0),然后是按字母顺序排列的欧盟国家(元顺序列中均为1),然后是按字母顺序排列的世界其他国家(元顺序列中均为2)

如果您想按该顺序订购GER、USA、FRA,您将分别为它们分配0、1和2,然后所有欧盟国家a 3和行a 4等

稍后对所需排序的更新只需要更新表,而不需要更新SQL,这使得它可以由用户配置