查询遇到麻烦,请根据情况选择不同的顺序

时间:2019-07-12 08:32:22

标签: sql postgresql select distinct

在问题的帮助下,我学会了如何将SELECT DISTINCTORDER BY一起使用:
How to use DISTINCT and ORDER BY in same SELECT statement?

我从这个问题中学到了使用ORDER BY CASE
How do I return rows with a specific value first?

但是我有一个很难写的查询:

我有一个表CUSTOMER和一列NAME,我想获取所有客户的与众不同的名称,并且我想首先找到名称“ Hamza”。

SELECT DISTINCT "CUSTOMER"."NAME",
    Max("CUSTOMER"."NAME")
FROM "CUSTOMER"
WHERE
    "CUSTOMER".id >= 2
GROUP BY "CUSTOMER"."NAME"
ORDER BY CASE WHEN ("CUSTOMER"."NAME" = 'HAMZA' ) THEN 1 ELSE 2 END


错误

  

错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中
  第15行:按情况排序(“ CUSTOMER”。“ NAME” ='HAMZA')然后以1 EL ...
  _________________。^
  SQL状态:42P10
  角色:372


修改

解决方法:

SELECT "CUSTOMER"."NAME", -- distinct keyword removed here
    Max("CUSTOMER"."NAME")
FROM "CUSTOMER"
WHERE
    "CUSTOMER".id >= 2
GROUP BY "CUSTOMER"."NAME"
ORDER BY
CASE WHEN ("CUSTOMER"."NAME" = 'HAMZA' ) THEN 1 ELSE 2 END,
CASE WHEN ("CUSTOMER"."NAME" = 'GIORNO' ) THEN 1 ELSE 2 END

2 个答案:

答案 0 :(得分:1)

分组已经可以确保您获得不同的客户名称。只需删除此修饰符,您就可以了:

SELECT "CUSTOMER"."NAME", -- distinct keyword removed here
    Max("CUSTOMER"."NAME")
FROM "CUSTOMER"
WHERE
    "CUSTOMER".id >= 2
GROUP BY "CUSTOMER"."NAME"
ORDER BY CASE WHEN ("CUSTOMER"."NAME" = 'HAMZA' ) THEN 1 ELSE 2 END

答案 1 :(得分:1)

  

我想获得所有不同的客户名称,并且我想首先找到名称“ Hamza”。

为什么不这样做呢?

SELECT "CUSTOMER"."NAME"
FROM "CUSTOMER" 
GROUP BY "CUSTOMER"."NAME" 
ORDER BY ("CUSTOMER"."NAME"  = 'Hamza') DESC

SELECT DISTINCT与聚合函数一起使用通常只会混淆查询逻辑。

我也不知道你为什么要两次选择这个名字。