如何在mysql的三个表之间获取顺序和总和?

时间:2019-02-20 09:47:55

标签: mysql sum sql-order-by

我正在尝试使用表2上的排序对表1进行排序 并将表1上每个“订单号”的值相加,然后按“订单号”分组 然后从表3中获取客户名称,则结果应如下所示:

sort    ordernumber  sumvalue   name        location    
01          5555        120         Client 2    location 2
01          5498        50          Client 2    location 2
02          2324        50          Client 1    location1
02          4356        30          Client 1    location1

表格:

table 1 orders
===============
id      ordernumber code_client value
1           2324        01       20 
1           2324        01       30 
1           4356        01       30 
1           5555        02       40 
1           5555        02       40 
1           5498        02       50 
1           5555        02       40 

table 2 sort
============
sort    code_client
1           02
2           01

table 3 client
===============
code_client     name     location
01              Client 1  location1
02              Client 2  location2

我在以下代码中所做的操作不尊重订单,即使每个订单号的总和也是如此

SELECT orders.ordernumber, 
SUM(orders.value) AS totalordersvalue, 
orders.code_client,
sort.code_client,sort.sort,
client.code_client,client.name, client.location,
FROM orders 
LEFT JOIN client 
ON client.code_client = orders.code_client 
LEFT JOIN sort 
ON sort.code_client = orders.code_client 

WHERE orders.id = 1 
GROUP BY orders.ordernumber 
ORDER BY sort.sort

有什么方法可以获取正确的订单和每个订单的正确总和作为最终结果?谢谢

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

select sort, ordernumber ,totalordersvalue as sumvalue,name,location from 
(
SELECT orders.ordernumber, SUM(orders.value) AS totalordersvalue, 
orders.code_client
FROM orders WHERE orders.id = 1 group by orders.ordernumber,orders.code_client
)A inner join client ON client.code_client = A.code_client
inner join sort ON sort.code_client = A.code_client 
ORDER BY sort.sort

答案 1 :(得分:0)

如果获取结果的顺序对您而言无关紧要,则可以使用以下查询

SELECT
  DISTINCT o.ordernumber,
  s.sort,
  (SELECT sum(os.value) AS sum_value FROM orders AS os WHERE o.ordernumber = 
os.ordernumber GROUP BY os.ordernumber) AS sum_value,
  c.name,
  c.location
FROM
  sort AS s,
  orders AS o,
  client AS c
  WHERE c.code_client = o.code_client AND o.code_client=s.code_client
ORDER BY s.sort;

输出:

ordernumber  sort    sumvalue   name        location    
5555         01      120        Client 2    location 2
5498         01      50         Client 2    location 2
2324         02      50         Client 1    location1
4356         02      30         Client 1    location1