必须出现在sql中的group by子句中
我有一个sql语句,我试图添加ORDERBY,当我添加order语句时,我得到一个错误必须出现在sql中的group by子句中,sql,postgresql,Sql,Postgresql,我有一个sql语句,我试图添加ORDERBY,当我添加order语句时,我得到一个错误 错误:列“items.id”必须出现在GROUP BY子句中或用于聚合函数中 我的问题是 WITH "has_children_cte" AS (SELECT DISTINCT "parent_id" AS "item_id", 1 AS "has_children" FROM "items") SE
错误:列“items.id”必须出现在GROUP BY子句中或用于聚合函数中
我的问题是
WITH "has_children_cte"
AS (SELECT DISTINCT "parent_id" AS "item_id",
1 AS "has_children"
FROM "items")
SELECT "item_category_id",
Count(*) AS "count"
FROM "items"
INNER JOIN "items" AS "root_item"
ON ( "root_item"."id" = "items"."root_id" )
LEFT JOIN "item_types"
ON ( "items"."item_type_id" = "item_types"."id" )
LEFT JOIN "item_categories"
ON ( "item_categories"."id" = "item_types"."item_category_id" )
INNER JOIN "order_items"
ON ( "items"."order_item_id" = "order_items"."id" )
INNER JOIN "orders"
ON ( "order_items"."order_id" = "orders"."id" )
LEFT JOIN "has_children_cte"
ON ( "items"."id" = "has_children_cte"."item_id" )
WHERE ( ( "items"."parent_id" IS NULL )
AND ( "items"."state" != 'discarded' ) )
GROUP BY "item_category_id"
ORDER BY "items"."id";
我已经按“项目”添加了订单代码>
然后我得到了这个错误。当我尝试将items.id添加到group by时,我得到了错误的结果
很遗憾,我无法处理此错误。按
排序(逻辑上)发生在聚合之后。聚合后,“项”。“id”
在每一行中都不可用
因此,只需使用聚合函数:
ORDER BY MIN("items"."id")
为什么要按“项目”“id”订购?查询结果显示“类别id”和计数