我有一个SQL查询
SELECT spt.paymenttype,
MAX(nest.paytypetotal) total
FROM sportpaymenttype spt
INNER JOIN (SELECT spt.paymenttype,
SUM(sod.detailunitprice * sod.detailquantity) paytypetotal
FROM sportorderdetail sod
INNER JOIN sportorder so ON so.orderid = sod.orderid
INNER JOIN sportpaymenttype spt ON spt.paymenttype = so.paymenttype
GROUP BY spt.paymenttype) nest ON nest.paymenttype = spt.paymenttype
GROUP BY spt.paymenttype;
我希望它返回一行(因为MAX函数)但是,它返回4行。我想出了一个痛苦的方法来正确地做到这一点,但我想知道,为什么max函数表现得这样?
此外,这些是结果,我只期望第一个
PAYMENTTYPE TOTAL
Loan 8640.95
Check 147.34
Credit Card 479.93
Cash 25.95
我想知道的是,如果有更好的方法可以做到这一点......
SELECT spt.paymenttype,
nest.paytypetotal total
FROM sportpaymenttype spt
INNER JOIN (SELECT spt.paymenttype,
SUM(sod.detailunitprice * sod.detailquantity) paytypetotal
FROM sportorderdetail sod
INNER JOIN sportorder so ON so.orderid = sod.orderid
INNER JOIN sportpaymenttype spt ON spt.paymenttype = so.paymenttype
GROUP BY spt.paymenttype) nest ON nest.paymenttype = spt.paymenttype
WHERE nest.paytypetotal = (SELECT MAX(nest.paytypetotal)
FROM (SELECT spt.paymenttype,
SUM(sod.detailunitprice * sod.detailquantity) paytypetotal
FROM sportorderdetail sod
INNER JOIN sportorder so ON so.orderid = sod.orderid
INNER JOIN sportpaymenttype spt ON spt.paymenttype = so.paymenttype
GROUP BY spt.paymenttype) nest);
感谢。
答案 0 :(得分:2)
它的行为方式是因为您告诉Oracle按paymenttype
如果您执行了MAX(spt.paymenttype)
并删除GROUP BY
,那么它将按您的意愿运行。
答案 1 :(得分:0)
MAX函数是一个聚合。当您使用GROUP BY(在您的情况下,结尾处为“GROUP BY spt.paymenttype”)时,聚合将应用于GROUP BY生成的每个组,而不是整个结果集。您确实为每种付款类型获得了一个结果行,因为GROUP BY应该在没有过滤器的情况下执行。
要获得一行,请选择所需的单一付款方式,然后添加
HAVING spt.paymenttype = 'FOO'
在查询的最后。如果你想要所有paytypetotal值的最大值,可能最简单(不一定是最好的)将整个事物变成子查询,然后从中选择最大的付款值。