这是我的SQL查询。我有一个表A,但当我尝试将此表用于HAVING(A.CATEGORY)时显示错误ORA-00979: not a GROUP BY expression
。另一方面,如果我在同一个地方复制表A中的所有代码,它就可以工作。如何让这个查询在第一路上正常工作?感谢
第一(不正确):
SELECT
DEMO_PRODUCT_INFO.PRODUCT_NAME
FROM
DEMO_PRODUCT_INFO,
(SELECT
DEMO_PRODUCT_INFO.CATEGORY
FROM
DEMO_PRODUCT_INFO
HAVING
MAX(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MAX(MAX(DEMO_PRODUCT_INFO.LIST_PRICE))
FROM DEMO_PRODUCT_INFO
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY
DEMO_PRODUCT_INFO.CATEGORY) A
WHERE
DEMO_PRODUCT_INFO.CATEGORY = A.CATEGORY
HAVING
MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
FROM DEMO_PRODUCT_INFO
WHERE DEMO_PRODUCT_INFO.CATEGORY = A.CATEGORY
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY
DEMO_PRODUCT_INFO.PRODUCT_NAME
SECOND(CORRECT):
SELECT
DEMO_PRODUCT_INFO.PRODUCT_NAME
FROM
DEMO_PRODUCT_INFO,
(SELECT
DEMO_PRODUCT_INFO.CATEGORY
FROM
DEMO_PRODUCT_INFO
HAVING
MAX(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MAX(MAX(DEMO_PRODUCT_INFO.LIST_PRICE))
FROM DEMO_PRODUCT_INFO
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY
DEMO_PRODUCT_INFO.CATEGORY) A
WHERE
DEMO_PRODUCT_INFO.CATEGORY = A.CATEGORY
HAVING
MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
FROM DEMO_PRODUCT_INFO
WHERE DEMO_PRODUCT_INFO.CATEGORY
= (SELECT DEMO_PRODUCT_INFO.CATEGORY
FROM DEMO_PRODUCT_INFO
HAVING MAX(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MAX(MAX(DEMO_PRODUCT_INFO.LIST_PRICE))
FROM DEMO_PRODUCT_INFO
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY
DEMO_PRODUCT_INFO.PRODUCT_NAME
答案 0 :(得分:0)
GROUP BY子句在HAVING子句之前。这是正确的顺序:
SELECT ...
FROM ...
WHERE ...
GROUP BY ...
HAVING ...
答案 1 :(得分:0)
我不是你想要做的100%,但错误是因为你的脚本的这一部分:
HAVING
MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
FROM DEMO_PRODUCT_INFO
WHERE DEMO_PRODUCT_INFO.CATEGORY = A.CATEGORY
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
select min(ilst_price)...group by category
将生成list_prices列表。因此having
子句有效地说“只有最小list_prices 等于最小list_prices列表的行,按类别分组”。当然,这是不合逻辑的。
我假设你想要该类别的最低list_price?您需要删除group by
。此外,list {price周围的min()
需要位于内部选择的外部。这是一个完整的工作版本:
SELECT
DEMO_PRODUCT_INFO.PRODUCT_NAME
FROM
DEMO_PRODUCT_INFO,
(SELECT
DEMO_PRODUCT_INFO.CATEGORY
FROM
DEMO_PRODUCT_INFO
HAVING
MAX(DEMO_PRODUCT_INFO.LIST_PRICE)
= (SELECT MAX(MAX(DEMO_PRODUCT_INFO.LIST_PRICE))
FROM DEMO_PRODUCT_INFO
GROUP BY DEMO_PRODUCT_INFO.CATEGORY)
GROUP BY
DEMO_PRODUCT_INFO.CATEGORY) A
WHERE
DEMO_PRODUCT_INFO.CATEGORY = A.CATEGORY
HAVING
MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
= MIN((SELECT MIN(DEMO_PRODUCT_INFO.LIST_PRICE)
FROM DEMO_PRODUCT_INFO
WHERE DEMO_PRODUCT_INFO.CATEGORY = A.CATEGORY))
GROUP BY
DEMO_PRODUCT_INFO.PRODUCT_NAME