使用联接表,分组依据和位置的SQL查询

时间:2019-03-21 20:05:12

标签: mysql sql database

问题: 哪些订单的价值大于5,000美元?

查询我当前正在使用:

SELECT o.orderNumber, o.orderDate, d.quantityOrdered*d.priceEach AS totalAmt
FROM orderdetails d, orders o, products p 
WHERE p.productCode = d.productCode 
    AND d.orderNumber = o.orderNumber;

输出看起来像:

'10100','2003-01-06 00:00:00','4080'
'10100','2003-01-06 00:00:00','2754.5'
'10100','2003-01-06 00:00:00','1660.12'
'10100','2003-01-06 00:00:00','1729.21'
'10101','2003-01-09 00:00:00','2701.5'
'10101','2003-01-09 00:00:00','4343.56'
'10101','2003-01-09 00:00:00','1463.8500000000001'
'10101','2003-01-09 00:00:00','2040.1000000000001'

如您所见,每个订单都订购了多个产品,因此例如,我需要查询以合并10101订单的所有totalAmt,以将其大于或等于5,000。

5 个答案:

答案 0 :(得分:1)

我看不出此查询中如何需要表products
将表ordersorderdetails连接起来,并在quantityOrdered*priceEach上求和:

SELECT 
  o.orderNumber, 
  o.orderDate, 
  SUM(d.quantityOrdered*d.priceEach) totalamt
FROM orders o INNER JOIN orderdetails d
ON d.orderNumber = o.orderNumber
GROUP BY
  o.orderNumber, 
  o.orderDate
HAVING totalamt > 5000

答案 1 :(得分:1)

您将需要使用SUM()函数和GROUP BY function()对订单金额求和。所以它将是:

SELECT
    o.orderNumber,
    o.orderDate,
    SUM(d.quantityOrdered * d.priceEach) AS totalAmt
FROM
    orderdetails d,
    orders o,
    products p
WHERE
    p.productCode = d.productCode
AND d.orderNumber = o.orderNumber
GROUP BY
    o.orderNumber,
    o.orderDate
HAVING
    SUM(d.quantityOrdered * d.priceEach) >= 5000;

需要注意的一件事:如果只想对“产品”表中存在的产品的产品价值求和,则需要加入“产品”表。

答案 2 :(得分:1)

您真的需要产品表吗? 无论如何,将SUM()与GROUP BY一起使用,并且HAVING将获得所需的结果。

SELECT
    o.orderNumber,
    o.orderDate,
    SUM(d.quantityOrdered * d.priceEach) AS totalAmt
FROM
    orderdetails d,
    orders o,
    products p
WHERE
    p.productCode = d.productCode
AND d.orderNumber = o.orderNumber
GROUP BY
    o.orderNumber
HAVING
    totalAmt >= 5000;

输出将是这样的。

    '10100' 2003-01-06 00:00:00 10223.83
    '10101' 2003-01-09 00:00:00 10549.01

答案 3 :(得分:0)

a。在子查询中使用[分组依据],然后在父查询中进行过滤 b。使用具有

答案 4 :(得分:0)

首先,您在联接中不需要products表,因为该表中没有列参与选择投影,并且为了合并记录,您需要按orderNumber和{ {1}}并通过orderDate函数汇总其余的列,在您的情况下为MAX

d.quantityOrdered * d.priceEach