gpt4 book ai didi

sql - 查询有问题选择不同的顺序

转载 作者:行者123 更新时间:2023-11-29 12:49:47 26 4
gpt4 key购买 nike

在问题的帮助下,我学会了如何将 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,我想获取客户的所有 distinct 名称,我想找到名称 '首先是哈姆扎。

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


错误:

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 15: ORDER BY CASE WHEN ("CUSTOMER"."NAME" = 'HAMZA' ) THEN 1 EL...
_________________.^
SQL state: 42P10
Character: 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

最佳答案

分组将确保您获得不同的客户名称。只需删除此修饰符,您应该没问题:

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

关于sql - 查询有问题选择不同的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57003139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com