在同一SQL语句中使用where和having时,查询输出错误

时间:2013-04-20 10:48:56

标签: sql oracle

select CURRENCY.currencyname, currency.currencysymbol, COUNTRYNAME.currencycode, 
       currency.exchangerate
from CURRENCY,COUNTRYNAME
where currency.currencycode=COUNTRYNAME.currencycode
having currency.exchangerate >= max(currency.exchangerate)
group by CURRENCY.currencyname, currency.currencysymbol, 
         COUNTRYNAME.currencycode, currency.exchangerate;

这是我得到的输出,我知道是错的,因为我试图只显示最大汇率。因此,任何帮助解决此查询将非常感激。我是oracle sql developer

CURRENCYNAME         CURRENCYSYMBOL       CURRENCYCODE EXCHANGERATE
-------------------- -------------------- ------------ ------------
British Pound        £                    GBP                     1,
US Dollar            $                    USD                1.9626 ,
Danish Krone         kr                   DKK                9.9918 ,
Malaysian Ringgit    RM                   MYR               6.35392 ,
Euro                 €                    EUR               1.34076 ,
Indian Rupee         Rs                   INR               77.3265 ,
Japanese Yen         ¥                    JPY               209.881, 

3 个答案:

答案 0 :(得分:0)

尝试以下

SELECT CURRENCY.currencyname, currency.currencysymbol, 
       COUNTRYNAME.currencycode, MAX(currency.exchangerate) as ExchangeRate
FROM CURRENCY
INNER JOIN COUNTRYNAME ON COUNTRYNAME.currencycode = currency.currencycode
GROUP BY CURRENCY.currencyname, currency.currencysymbol, COUNTRYNAME.currencycode;

答案 1 :(得分:0)

关于您的查询...

1。您无法将MAX(聚合)值与同一查询级别中的基值进行比较。您可以使用派生表(也称为“子查询”),例如

    select c.currencyname, c.currencysymbol, n.currencycode, c.exchangerate
    from CURRENCY c
    join COUNTRYNAME n on c.currencycode=n.currencycode
    where c.exchangerate = (select max(exchangerate) from currency)

2。您将从上面注意到我使用JOIN链接两个表。随着ANSI-92连接语法的出现,大约21年前,使用逗号列表的表名已经过时了。

3。您显示的查询无法正常工作。 GROUP BY子句位于HAVING子句之前,而不是之后。话虽如此,上面的第一点适用,你无法将MAX值与(基本)列值进行比较。

答案 2 :(得分:0)

此查询可能简化为:

select max(currencyname), max(currencysymbol), currencycode, max(exchangerate)
from currency group by currencycode

( - 假设没有任何国家从未使用的货币。)