Sql Join三表

时间:2016-07-12 11:34:37

标签: mysql sql sql-server database

这是我的表..我想要这个输出:

pid | pname | custname | quantity | total base price | sale price | profit

模式:

create table customers
(
    cid int,
    cname varchar(1000),
    cg varchar(1000)
)

create table prod
(
    pid int,
    pname varchar(1000),
    baseprice int,
    saleprice int
)

create table orders
(
    oid int,
    custid int,
    pid int,
    quantity int,
    odate date
)

如何为此编写查询?

2 个答案:

答案 0 :(得分:0)

comp.unix.admin

答案 1 :(得分:0)

--pid | pname | custname | quantity | total base price | sale price | profit
select o.pid, p.pname, c.cname AS custname, SUM(o.quantity) AS quantity, 
SUM(p.baseprice) AS 'total base price', SUM(p.saleprice) AS 'sale price', 
SUM(p.baseprice) - SUM(p.saleprice) AS profit -- change this math to what you need
from orders o join prod p
on o.pid = p.pid
join customers c
on o.custid = c.cid
group by o.pid, p.pname, c.cname