SQL查询 - 按列

时间:2016-06-24 02:24:56

标签: sql

我有一个SQL查询,目前显示这些结果:

Product ID Vendor Site Location 
-----------------------------------------------
ANTIFOAM 51 CHEMICAL COMPANY MANUFACTURING SITE
ANTIFOAM 51 CHEMICAL COMPANY MANUFACTURING SITE
ANTIFOAM 51 CHEMICAL COMPANY HQ HQ-FOOD
ACID 509    CSPA MANUFACTURING SITE
ACID 509    CSPA HQ HQ-FOOD
ACID 509    NORTH MANUFACTURING SITE
ACID 509    NORTH HQ HQ-FOOD

我需要首先在总部订购,然后是生产现场。

非常感谢任何帮助!

所以看起来应该是这样的:

Product ID Vendor Site Location
----------------------------------------
ANTIFOAM 51 CHEMICAL COMPANY HQ HQ-FOOD
ANTIFOAM 51 CHEMICAL COMPANY MANUFACTURING SITE
ANTIFOAM 51 CHEMICAL COMPANY MANUFACTURING SITE
ACID 509    CSPA HQ HQ-FOOD
ACID 509    CSPA MANUFACTURING SITE
ACID 509    NORTH HQ HQ-FOOD
ACID 509    NORTH MANUFACTURING SITE

3 个答案:

答案 0 :(得分:2)

" HQ"来之前" MA"在en-us语言环境中,假设" HQ-FOOD"和"制造网站"是列中唯一的两个值,您可以使用默认排序顺序:

select * from table order by ID, SiteLocation, Vendor

答案 1 :(得分:0)

在PostgreSQL中:

select * from t1
order by
    id,
    regexp_replace(vendor,'\s+HQ$',''),
    case when site_location='HQ-FOOD' then 1 else 2 end
;

output

有关regexp_replace()的文档,请参阅here

测试夹具

drop table if exists t1;
create table t1 (product text, id int, vendor text, site_location text );
insert into t1 (product,id,vendor,site_location) values
    ('ANTIFOAM',51,'CHEMICAL COMPANY','MANUFACTURING SITE'),
    ('ANTIFOAM',51,'CHEMICAL COMPANY','MANUFACTURING SITE'),
    ('ANTIFOAM',51,'CHEMICAL COMPANY HQ','HQ-FOOD'),
    ('ACID',509,'CSPA ','MANUFACTURING SITE'),
    ('ACID',509,'CSPA  HQ','HQ-FOOD'),
    ('ACID',509,'NORTH','MANUFACTURING SITE'),
    ('ACID',509,'NORTH HQ','HQ-FOOD')
;

答案 2 :(得分:0)

您可以看到我的代码(在SQL Server中):

create table #t2 (product varchar(100), id int, vendor varchar(100), site_location varchar(100) );
insert into #t2 (product,id,vendor,site_location) values
    ('ANTIFOAM',51,'CHEMICAL COMPANY','MANUFACTURING SITE'),
    ('ANTIFOAM',51,'CHEMICAL COMPANY','MANUFACTURING SITE'),
    ('ANTIFOAM',51,'CHEMICAL COMPANY HQ','HQ-FOOD'),
    ('ACID',509,'CSPA ','MANUFACTURING SITE'),
    ('ACID',509,'CSPA  HQ','HQ-FOOD'),
    ('ACID',509,'NORTH','MANUFACTURING SITE'),
    ('ACID',509,'NORTH HQ','HQ-FOOD')

select product,id,vendor,site_location
from #t2
order by vendor desc

drop table #t2

输出:

ACID    509 NORTH HQ    HQ-FOOD
ACID    509 NORTH   MANUFACTURING SITE
ACID    509 CSPA  HQ    HQ-FOOD
ACID    509 CSPA    MANUFACTURING SITE
ANTIFOAM    51  CHEMICAL COMPANY HQ HQ-FOOD
ANTIFOAM    51  CHEMICAL COMPANY    MANUFACTURING SITE
ANTIFOAM    51  CHEMICAL COMPANY    MANUFACTURING SITE