mysql使用sum和max来查找支付最高的发票

8fsztsew  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(432)

我试图找出如何从一个表中获得值之和的最大结果,以便显示收据的最高支付金额。我也应该用subselect,但我搞不懂。到目前为止,这个查询得到了除最大值以外的所有需要显示的内容。这是需要使用的表格(发票+od)这是我目前得到的这是我应该得到的
在哪里可以添加max()(总和)?

SELECT invoicenumber invoice
     , invoicedate date
     , SUM(orderqty*ordersell) AS 'Invoice Total' 
  FROM invoice 
  JOIN orderdetail 
    ON invoice.invoiceid = orderdetail.invoiceid 
 GROUP 
    BY invoice ;
pepwfjgg

pepwfjgg1#

如果在select中使用sum或max,则需要按其他列分组:

SELECT invoicenumber AS invoice
 , invoicedate AS date
 , SUM(orderqty*ordersell) AS 'Invoice Total' 
FROM invoice 
JOIN orderdetail ON invoice.invoiceid = orderdetail.invoiceid 
GROUP BY invoicenumber,invoicedate;
s4chpxco

s4chpxco2#

我不知道这是否与你所看到的很接近,但我认为这是可行的(如果我正确理解你想要达到的目标)。

SELECT inv.invoicenumber,
       inv.invoice, 
       inv.invoicedate AS 'Date',
       MAX((SELECT ord.orderqty+ord.ordersell FROM DUAL)) AS 'Invoice Total' 
  FROM invoice inv
  JOIN orderdetail ord
    ON inv.invoice.invoiceid = ord.orderdetail.invoiceid 
 GROUP BY inv.invoice, 
          inv.invoice, 
          inv.invoicedate;
niknxzdl

niknxzdl3#

你可以试试这个(加上前面的答案):

SELECT invoicenumber AS invoice
 , invoicedate AS date
 , SUM(orderqty*ordersell) AS 'Invoice Total' 
FROM invoice 
JOIN orderdetail ON invoice.invoiceid = orderdetail.invoiceid 
GROUP BY invoicenumber,invoicedate ORDER BY `Invoice Total` DESC LIMIT 1;

可能效率不太高,但只返回最高的结果。

相关问题