0

我有 3 个表productcustomertransaction

产品:

id_product    price
    1         1000
    2         2000

顾客:

id_customer    name
    1          Tom
    2          Jack

交易:

id_transaction    id_product     id_customer    qty    date
    1                 1              1           10    2013-02-21
    2                 2              1           50    2013-02-21
    3                 1              2           15    2013-02-21

我想达到这个结果:

id_customer      name      total_transaction      purchase_qty      subtotal
    1            Tom             2                     60            110000
    2            Jack            1                     15             15000

如何使用 MySQL 中的查询获得该结果?

4

4 回答 4

1
SELECT  t.id_customer, c.name, 
        COUNT(t.id_customer) AS total_transaction, 
        SUM(t.qty) as purchase_qty
FROM transaction t
INNER JOIN customer c
ON t.id_customer = c.id_customer
GROUP BY t.id_customer,c.name
于 2013-02-21T10:51:28.503 回答
0
SELECT cs.id_customer, cs.name, COUNT(tr.transaction) AS total_transaction, SUM(tr.qty) as purchase_qty, SUM(tr.qty*pr.prize)
FROM customer AS cs
LEFT JOIN transaction AS tr ON tr.id_customer = cs.id_customer
LEFT JOIN product AS pr ON pr.id_product = tr.id_product
GROUP BY cs.id_customer

我想你是一个完全的初学者,所以我为你做了这个。下次,如果您有任何自己的想法,请提供给我们,这样我们就不必为您编写整个查询。表现出一些努力。

于 2013-02-21T10:48:42.390 回答
0
SELECT c.id_customer, c.name, count(t.id_transaction) AS total_transaction
FORM Customer c INNER JOIN Transaction T
 ON C.id_customer = T.id_customer
GROUP BY c.id_customer
于 2013-02-21T10:48:42.707 回答
-1

您需要一个group by声明,因为您想汇总给定客户的结果:

SELECT id_customer, name, count(id_transaction) AS total_transaction
FORM Customer, Transaction
WHERE Transaction.id_customer = Customer.id_customer
GROUP BY id_customer

这并不能解决您的全部问题,但您已经明白了。

于 2013-02-21T10:44:15.170 回答