按产品类别名称的订单行

时间:2019-11-24 20:05:19

标签: sql postgresql

我的客户希望我针对不同的类别订购不同的产品,例如,当类别名称为“ alternator”时,我应首先显示生产者为“ ABC”的零件,当类别名称为“ starter”时,我应首先显示生产者为“ DEF”的零件,否则按images_count和parameters_count排序。我的架构如下所示。

零件(id,生产者ID,类别ID) 类别(ID,名称) 生产者(编号,名称)

我已经尝试过按ORDER BY对结果进行排序,就像这样。

SELECT *
FROM   parts 
       JOIN categories 
         ON parts.category_id = categories.id 
       JOIN producers 
         ON parts.producer_id = Cast(producers.lauber_id AS INT) 
ORDER  BY CASE 
            WHEN categories.NAME = 'alternator' 
                  OR categories.NAME = 'starter' THEN 
            producers.NAME = 'STARDAX' 
             OR producers.NAME = 'POWERTRUCK' 
          END DESC, 
          CASE 
            WHEN categories.NAME = 'something else' THEN 
            producers.NAME = 'POINTGEAR' 
             OR producers.NAME = 'LAUBER' 
          END DESC, 
          images_count DESC, 
          parameters_count DESC 

我不确定我是否做对了,我不是SQL的高手。我正在使用Postgres。

1 个答案:

答案 0 :(得分:1)

您可以使用CASE

SELECT *
FROM   parts 
       JOIN categories 
         ON parts.category_id = categories.id 
       JOIN producers 
         ON parts.producer_id = Cast(producers.lauber_id AS INT) 
ORDER  BY CASE WHEN categories.NAME = 'alternator' AND producers.NAME = 'ABC' THEN 0
               WHEN categories.NAME = 'starter' AND producers.NAME = 'DEF' THEN 0
               -- ...
               ELSE 1
          END,
          images_count DESC, 
          parameters_count DESC